简体   繁体   中英

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"/>';
                      }
                  }

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) {
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM