0% found this document useful (0 votes)
7 views

PHP PROGRAMS

HYPERTEXT PREPROCESSOR PROGRAMMS
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

PHP PROGRAMS

HYPERTEXT PREPROCESSOR PROGRAMMS
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

PHP PROGRAMS

1)Even numbers
<?php
for ($i = 2; $i <= 20; $i += 2) {
echo "$i"."\n ";
}
?>
2)Associative arrays
<?php
$students = array("Alice" => "A", "Bob" => "B", "Charlie" => "C");
foreach ($students as $name => $grade) {
echo "$name: $grade"."\n";
}
?>

3)Cookies creation,accessing
<?php
setcookie("user", "John", time() + (10 * 60), "/"); // Cookie expires in 10 minutes
echo "Cookie 'user' is set!";
?>
//accessing
<?php
if(isset($_COOKIE["user"])) {
echo "User: " . $_COOKIE["user"];
} else {
echo "Cookie not found!";
}
?>
4)PARAMETERS FROM HTML PAGE
<form action="process.php" method="POST">
<input type="text" name="username" placeholder="Enter your name">
<input type="submit" value="Submit">
</form>
PHP Code (process.php):
<?php
echo "Hello, " . $_POST['username'];
?>
5)File creation
<?php
$file = fopen("example.txt", "w");
fwrite($file, "This is a sample text.");
fclose($file);
echo "File created successfully.";
?>
6)MYSQL Connection
<?php
$conn = new mysqli("localhost","root", "root"); // servername,username,password
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

7)Inserting records
<?php
$conn = new mysqli("localhost", "root", "root", "bank_management");
$sql = "INSERT INTO student(name, grade) VALUES ('Alice', 'A')";
if ($conn->query($sql) === TRUE) {
echo "Record inserted successfully";
} else {
echo "Error: " . $conn->error;
}
$conn->close();
?>
8)Display records
<?php
$conn = new mysqli("localhost", "root", "root", "bank_management");
$sql = "SELECT * FROM student";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo " Name: " . $row["name"] . " - Grade: " . $row["grade"] . "<br>";
}
} else {
echo "No records found";
}
$conn->close();
?>

You might also like