- Hello World!, Code
<!DOCTYPE html>
<html>
<head>
<title>CSC 325</title>
</head>
<body>
<?php
echo "Hello World\n";
?>
</body>
</html>
- Table, Code
<!DOCTYPE html>
<html>
<head>
<title>CSC 325</title>
</head>
<body>
<?php
echo "<table border>\n";
echo "<tr><th>Name</th><th>UIN</th></tr>\n";
echo "<tr><td>David</td><td>0001</td></tr>\n";
echo "</table>\n";
?>
</body>
</html>
- Form, form.php, welcome.php
<html>
<body>
<form action="welcome.php" method="post">
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
<html>
<body>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
- Create connection
<?php
try{
$hostname = 'localhost';
$dbname = 'employees';
$username = 'root';
$password = '';
$DBH = new PDO("mysql:host=$hostname; dbname=$dbname; charset=utf8mb4", $username, $password);
echo 'Connected';
}
catch(PDOException $e){
echo $e->getMessage();
}
?>;
- Query and fetch, Code
<html>
<head>
<title>Database</title>
</head>
<body>
<?php
// check if PDO has been installed
if(!defined('PDO::ATTR_DRIVER_NAME')){
echo 'PDO unavailable';
}
// connect database
try{
$hostname = 'localhost';
$databasename = 'employees';
$username = 'root';
$password = '';
$DBH = new PDO("mysql:host=$hostname; dbname=$databasename; charset=utf8mb4", $username, $password);
//$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
//$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Connected';
}
catch(PDOException $e){
echo $e->getMessage();
}
// prepare query and fetch
try{
$stmt = $DBH->query("select * from employees where gender = 'M'");
while($row = $stmt->fetch())
{
echo "<li>".$row['first_name'].' '.$row['last_name'].'</li>';
//print_r($row);
}
}
catch(PDOException $e){
echo $e->getMessage();
}
// remove connection
$DBH = NULL;
?>
</body>
</html>
- Prepare query and fetch, Code
<html>
<head>
<title>Database</title>
</head>
<body>
<?php
// check if PDO has been installed
if(!defined('PDO::ATTR_DRIVER_NAME')){
echo 'PDO unavailable';
}
// connect database
try{
$hostname = 'localhost';
$databasename = 'employees';
$username = 'root';
$password = '';
$DBH = new PDO("mysql:host=$hostname; dbname=$databasename; charset=utf8mb4", $username, $password);
//$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
//$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Connected';
}
catch(PDOException $e){
echo $e->getMessage();
}
// prepare query and fetch
try{
$stmt = $DBH->prepare("select * from employees where gender = ?");
$stmt->bindParam(1, $gen);
$gen = 'M';
//$stmt=$DBH->prepare("select * from departments");
$stmt->execute();
while($row = $stmt->fetch())
{
echo "<li>".$row['first_name'].' '.$row['last_name'].'</li>';
//print_r($row);
}
}
catch(PDOException $e){
echo $e->getMessage();
}
// remove connection
$DBH = NULL;
?>
</body>
</html>