gi
Now, we’re ready to head back to the PHP and write some code to pull this data out. Let’s start with this:
define("HOST","localhost");
define("DATABASE","dbname");
define("USERNAME","root");
define("PASSWORD","root");
/* Creating database connection */
try {
$pdo = new PDO("mysql:host=" . HOST . ";dbname=" . DATABASE, USERNAME, PASSWORD);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$pdo->exec("SET NAMES 'utf8'");
} catch(PDOException $e) {
die("<div class='alert alert-danger'>ERROR : " . $e->getMessage() . "</div>");
}
This should connect successfully. The $mysqli variable now holds our connection object. Now we’re ready to start querying the database. We do so by calling the query method on the $mysqli object, like so:
$sql = "SELECT * FROM tableName WHERE id = ?"; $stmt = $pdo->prepare($sql); $stmt->bindValue(1, $id); $stmt->execute(); $result = $stmt->fetchAll();
So, after all that, the $results variable will be a mysqli_result object that has several useful properties and methods. If the query failed for some reason, $results would be false. Therefore, we should make sure we have our object:
<?php
if ($result) { ?>
<table>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Occupation</th>
</tr>
<?php foreach ($result as $row) { ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['firstName']; ?></td>
<td><?php echo $row['lastName']; ?></td>
<td><?php echo $row['occupation']; ?></td>
</tr>
<?php } ?>
</table>
<?php } ?>
You can imagine how this works with our while loop: when the condition is first evaluated, we call fetch_object for the first time and assign its value to $row. Since that will be a record object, which equates to true, we’ll execute the code in the loop.
Next time you come around to evaluating the condition, $row will be assigned the next record, and the loop repeats.
When we’re out of records, $row will be assigned to NULL, and the while loop will stop.
Inside the loop, we’ve got some HTML, with some PHP inside that. You can see how the $row has a property (just like a variable) for every field in our database table, that we’re outputting into the table.
