PHP MySQL PDO SELECT with prepared statement and question mark placeholders
From w3cyberlearnings
Contents |
PHP PDO Select Records By Using Question Mark place holder
Query records by using Prepare and Execute Statements with the question mark place holder.
Syntax PDO Question mark place holder for select record
$sql = "SELECT id,first_name, last_name, email FROM user_infor WHERE id IN(?,?,?)"; $sq = $db->prepare($sql); $sq->execute(array($id1, $id2, $id3));
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(?,?,?)"; $sq = $db->prepare($sql); // check execute statement if (!$sq->execute(array($id1, $id2, $id3))) { 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>'; ?>
Example 2
Using Binds parameter to variable for the question mark place holder.
$sql = "SELECT id,first_name, last_name, email FROM user_infor WHERE id IN(?,?,?)"; $sq = $db->prepare($sql); $sq->bindParam(1,$id1, PDO::PARAM_INT); $sq->bindParam(2,$id2, PDO::PARAM_INT); $sq->bindParam(3,$id3, PDO::PARAM_INT); // check execute statement if (!$sq->execute()) { echo "Error!"; }
Output