php - How Do I Iterate MySQL Table After SELECT PDO Query Using Positional Placeholders?

Ordinarily, I could get each course name in the table by doing this:
<?php
// query users' table to retrieve courses' contents
$courses = $pdo->query("SELECT * FROM courses"); # question marks is used as a place holder
echo '<option value="">Select a course</option>';
foreach ($courses as $row)
{
echo '<option value=" '. $row["c_name"] .' ">'. $row["c_name"] .'</option>';
}
?>
Now I want to do the same via PDO prepared statement using positional placeholders, but it doesn't work. The following is what I've tried:
$stmt = $pdo->prepare("SELECT * FROM courses WHERE c_name = ?");
if ($stmt->execute(array($_GET['c_name'])))
{
while ($row = $stmt->fetch())
{
echo '<option value=" '. $row["cid"] .' ">'. $row["c_name"] .'</option>' .
'<option value=" '. $row["c_name"] .' " selected="selected">'. $row["c_name"] .'</option>' .
'<input type="hidden" name="cid" . value="' . $row["cid"] .'" id="cid"/>';
}
}
Answer
Solution:
You're using a prepared statement, but not making use of the placeholders in your query. See the PHP PDO Prepared Statements documentation for more details.
// In the below query, I've added `WHERE id = ?` as your placeholder
$stmt = $pdo->prepare("SELECT * FROM courses WHERE id = ?");
$stmt->execute([$cid]);
while ($row = $stmt->fetch()) # get courses data
{
...
}
Edit:
I may have missed out where you were doing a check on whether$cid
was posted or not, this should satisfy your requirement:
$cid = $_POST["cid"] ?? NULL;
if (is_null($cid)) {
$stmt = $pdo->query("SELECT * FROM courses");
}
else {
$stmt = $pdo->prepare("SELECT * FROM courses WHERE id = ?");
$stmt->execute([$cid]);
}
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) {
...
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: using $this when not in object context laravel
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.