我尝试转换为使用PDO,但似乎无法在循环时从我的PDO获得结果。
这个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数据库连接(似乎可行)
//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();
}
此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>";
}
答案 0 :(得分:2)
您错过了运行查询的步骤。使用PDO,您可以准备查询以优化性能并帮助防止SQL注入,但您仍然必须执行&#34;执行&#34;声明。
$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>";
}
相关PHP手册条目:
答案 1 :(得分:0)
这只是通过稍微更改代码来实现它。
//$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'])."";
}
}
修改强> 查询函数可以一次性准备和执行,如果您没有在查询中使用变量,则查询函数非常有用。