简体   繁体   English

如何将这个有效的mysql语句有效地转换为PDO?

[英]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. 我正在尝试转换为使用PDO,但似乎无法从我的PDO while循环中获得结果。

This mysql statement gives me results: 这个mysql语句给我结果:

$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) PDO数据库连接(似乎有效)

//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: 此PDO语句不会给我任何结果:

$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. 使用PDO,您可以准备查询,以优化性能并帮助防止SQL注入,但是您仍然必须“执行”该语句。

$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: 相关的PHP手册条目:

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

http://php.net/manual/en/pdo.prepare.php http://php.net/manual/zh/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. 编辑:查询函数可以一次性完成准备和执行,如果您没有要在查询中使用的变量,该函数将非常有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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