PHP MySQL PDO SELECT with prepared statement and named placeholders
From w3cyberlearnings
Contents |
PHP PDO Name place holder and bindParam
The name place holder and bindParam use to select a specific record.
Syntax PDO
$sql = "SELECT id,first_name, last_name, email FROM user_infor WHERE id IN(:id1,:id2,:id3)"; $sq = $db->prepare($sql); // bind name place holder $sq->bindParam(':id1', $id1, PDO::PARAM_INT); $sq->bindParam(':id2', $id2, PDO::PARAM_INT); $sq->bindParam(':id3', $id3, PDO::PARAM_INT); $sq->execute(); while ($r = $sq->fetch(PDO::FETCH_NUM)) { ... }
Example 1
<?php $id1 = 1; $id2 = 2; $id3 = 3; // fetch as NUM $dns = 'mysql:host=localhost;dbname=w3cyberlearning'; $user = 'user2000'; $pass = 'password2000'; $db = new PDO($dns, $user, $pass); $sql = "SELECT id,first_name, last_name, email FROM user_infor WHERE id IN(:id1,:id2,:id3)"; $sq = $db->prepare($sql); // bind name place holder $sq->bindParam(':id1', $id1, PDO::PARAM_INT); $sq->bindParam(':id2', $id2, PDO::PARAM_INT); $sq->bindParam(':id3', $id3, PDO::PARAM_INT); // check execute statement if (!$sq->execute()) { echo "Error!"; } echo '<table border="1">'; echo '<tr> <th>Id</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> </tr>'; while ($r = $sq->fetch(PDO::FETCH_NUM)) { echo '<tr>'; echo '<td>' . $r[0] . '</td>'; echo '<td>' . $r[1] . '</td>'; echo '<td>' . $r[2] . '</td>'; echo '<td>' . $r[3] . '</td>'; echo '</tr>'; } echo '</table>'; ?>