If you would like to know how the db.php script was created that will be used for most pages in the project, see details below.
PHP scripts are used to send SQL statements (e.g., SELECT, UPDATE, DELETE, INSERT, DROP AND CREATE) to a MySQL database to be executed and the result (e.g., retrieval, insertion, deletion, or selection of data) is returned to the PHP script or an error can be displayed if no result is returned.
Once you have connected to a server, you can then communicate with it by requesting a query and returning a result.
It is a good idea to test the database to see if it will return the desire results before writing a lot of code for the other pages.
<?php
$host ="localhost";
$username = "root";
$password = "";
$database = "pdo_employee_directory1234";
// Create Connection ----------------------------------------
$pdo_conn = new PDO( "mysql:host=$host; dbname=$database", $username, $password);
// Return a record set (also known as resultset) -----------
$sql = 'SELECT FirstName, LastName from employees';
// Loop through the $sql array for each row ----------------
foreach ( $pdo_conn->query($sql) as $row ){
echo $row['FirstName']." ".$row['LastName']."<br>";
}
// Close the database connection ----------------------------
$pdo_conn = null;
?>
CODE EXPLANATION:
- $sql = 'SELECT FirstName, LastName from employees'; statement is used to create a SELECT query and store it in the $sql array.
- The foreach loop is used to iterate through the $sql array for each item ($row).
- The echo command is used to display the result (FirstName LastName) of the database to the screen
- The $dpo_conn = null; statement is used to close the connection.
Carol Green
Bob Jones
Debra Samson
Jason Taylor
Bob Anderson
Ann Ricoh
It is best practice to use the try/catch syntax to check if there is an error when you are attempting to connect to a database.
<?php
$host ="localhost";
$username = "root";
$password = "";
$database = "pdo_employee_directory1234";
try {
// Create Connection ----------------------------------------
$pdo_conn = new PDO( "mysql:host=$host; dbname=$database", $username, $password);
// set the PDO error mode and exception
$pdo_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "<strong>Connected successfully:</strong><br>";
} catch ( PDOException $e ) {
echo "<strong>Connection failed:</strong> <br>" . $e->getMessage() . "<br>";
die();
}
// Return a record set (resultset) --------------------------
$sql = 'SELECT FirstName, LastName from employees';
// Loop through the $sql array for each row ----------------
foreach ( $pdo_conn->query( $sql ) as $row ) {
echo $row[ 'FirstName' ] . " " . $row[ 'LastName' ] . "<br>";
}
// Close the database connection ----------------------------
$pdo_conn = null;
?>
CODE EXPLANATION:
- The try code block test the database connect and if an error is found, the catch code block "catch" and displays it.
- The try code block is used to check for any error. If one if found, it will be "caught" in the catch code block in the $e variable. - The catch code block is used to display a custom error message based on the $error variable that is passed into the catch() method as an argument.
- The getMessage() method is used to give the SPECIFIC type of error that can occur.
Connected successfully:
Carol Green
Bob Jones
Debra Samson
Jason Taylor
Bob Anderson
Ann Ricoh
$database_username = 'CorneliusChopinX';
Connection failed:
SQLSTATE[HY000] [1045] Access denied for user
'CorneliusChopinX'@'localhost' (using password: YES)
$database_username = 'CorneliusChopin';
<?php $host ="localhost";
$username = "root";
$password = "";
$database = "pdo_employee_directory1234";
try {
// Create Connection ----------------------------------------
$pdo_conn = new PDO( "mysql:host=$host; dbname=$database", $username, $password);
// set the PDO error mode to exception
// $pdo_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo "<strong>Connected successfully:</strong><br>";
} catch ( PDOException $e ) {
echo "<strong>Connection failed:</strong> <br>" . $e->getMessage() . "<br>";
die();
}
/* $sql = 'SELECT FirstName, LastName from employees';
// Loop through the $sql array for each row ----------------
foreach ( $pdo_conn->query( $sql ) as $row ) {
echo $row[ 'FirstName' ] . " " . $row[ 'LastName' ] . "<br>";
} */
// Close the database connection ----------------------------
// $pdo_conn = null;
?>
CODE EXPLANATION:
- The lines above were commented or deleted because we want to make the PHP script generic to work for each page that we create.
- If you forgot to comment out the close connection statement ($pdo_conn = null;) the code will not work for the other pages. However, the connection should be closed in EACH of the pages separately.
- Notice the error statement IS NOT commented out because we want it to give an error when the other pages are created.
The examples below is used to give additional examples of what is returned from a database query. The "try/catch" block and close connection are not implemented because this is for demonstration purposes only.
<?php
$host ="localhost";
$username = "root";
$password = "";
$database = "pdo_employee_directory1234";
// Create Connection ----------------------------------------
$pdo_conn = new PDO( "mysql:host=$host; dbname=$database", $username, $password);
?>
<?php
$host ="localhost";
$username = "root";
$password = "";
$database = "pdo_employee_directory1234";
// Create Connection ----------------------------------------
$pdo_conn = new PDO( "mysql:host=$host; dbname=$database", $username, $password); // Retrieve the FIRST record from the database based on the FirstName column
$pdo_statement = $pdo_conn->prepare("SELECT * FROM employees");
$pdo_statement->execute();
$result = $pdo_statement->fetch();
echo ($result["FirstName"]);
?>
CODE EXPLANATION:
- The fetch() method will return a SINGLE record from the database.
$result = $pdo_statement->fetch();
echo ($result["FirstName"]. " ". $result["LastName"]);
$result = $pdo_statement->fetchAll(); foreach($result as $row) { print_r($row);
}
CODE EXPLANATION:
- The foreach loop is used to "loop" through the $result array.
- Notice the print_r() method instead of the print() method is used. The print_r() method is used to print the result of an array.
If you were to used the regular print() method, you would get the following error for each record in the database:
"Notice: Array to string conversion in C:\xampp\htdocs\EmployeeDirectory_JQM_PDO\db_results_examples.php on line 14 Array"
$result = $pdo_statement->fetchAll(PDO::FETCH_ASSOC);
CODE EXPLANATION:
- PDO::FETCH_ASSOC is used to ...
$result = $pdo_statement->fetchAll(PDO::FETCH_ASSOC);
/* foreach( $result as $row )
{
print_r( $row );
} */ ?> <table border="1">
<tr><th>FirstName</th><th>LastName</th></tr>
<?php foreach( $result as $row )
{
echo "<tr><td>";
echo $row['FirstName'];
echo "</td><td>";
echo $row['LastName'];
echo "</td><tr>";
}
?>
</table>
CODE EXPLANATION:
- The first two lines and the last line are static HTML table content.
- The nested foreach loop is used to iterate through the array and dynamically create the "rows" of the table.
- You could write the series of echo statements all of one line to see the HTML table structure (e.g., <tr><td>...</td><td>...</td></tr>) better:
echo "<tr><td>"; echo $row['FirstName']; echo "</td><td>"; echo $row['LastName']; echo "</td><tr>";
</table> <ul>
<?php foreach($result as $row)
{ echo "<li>";
echo $row['FirstName'];
echo " ";
echo $row['LastName'];
echo "</i>";
}
?>
</ul>
CODE EXPLANATION:
- The first and last lines are static HTML unordered list content.
- The nested foreach loop is used to iterate through the array and dynamically create the <li> tags for the bullet list.
</ul> <?php echo ($result[2]["FirstName"]); echo(" "); echo ($result[2]["LastName"]);
?>
?> <?php
$count = $pdo_statement->rowCount();
print("<h1><br>Total Records: <strong> $count</strong> </h1>");
?>