简体   繁体   中英

How can I convert this working mysql statement to PDO effectively?

I'm trying to convert to using PDO, but can't seem to get results from my PDO while loop.

This mysql statement gives me results:

$q = mysql_query("SELECT * FROM artist ORDER BY artist ASC");
while ($row = mysql_fetch_array($q)) {
  $theartist .= '<option value="'.($row['artist_id']).'">'.($row['artist'])."</option>";
}    

PDO database connection (that appears to work)

//the below isn't throwing any errors
$host='localhost';
$dbname='james_test';
$user='test';
$pass='testpass';

try {
  # MySQL with PDO_MYSQL
  $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOException $e) {
    echo $e->getMessage();
}

This PDO statement does not give me any results:

$query = $DBH->prepare("SELECT * FROM artist ORDER BY artist ASC");
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
    $theartist .= '<option value="'.($row['artist_id']).'">'.($row['artist'])."</option>";
}

You missed the step where you run the query. With a PDO, you can prepare the query which optimises performance and helps prevent SQL injection, but you must still "execute" the statement.

$query = $DBH->prepare("SELECT * FROM artist ORDER BY artist ASC");
$result = $query->execute();
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
    $theartist .= '<option value="'.($row['artist_id']).'">'.($row['artist'])."</option>";
}

Related PHP manual entries:

http://php.net/manual/en/pdostatement.execute.php

http://php.net/manual/en/pdo.prepare.php

This just makes it work by slightly changing your code.



//$query = $DBH->prepare("SELECT * FROM artist ORDER BY artist ASC");
$rows = $DBH->query("SELECT * FROM artist ORDER BY artist ASC");

//while($row = $query->fetch(PDO::FETCH_ASSOC)) {
if ($rows) {
  foreach ($rows as $row) {
      $theartist .= ''.($row['artist'])."";
  }
}

Edit: The query function does both prepare and execute in one go and is useful if you don't have variables to use in the query.

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