代码来自:PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)
$db = new PDO("mysql:host=localhost;dbname=map1", 'root', 'root');
$sql = "
DROP TABLE IF EXISTS car;
CREATE TEMPORARY TABLE car (name (varchar 300), type (varchar 300));
INSERT INTO car(name, type) VALUES ('car1', 'coupe');
INSERT INTO car(name, type) VALUES ('car2', 'coupe');
SELECT * FROM car;
";
try {
$stmt = $db->prepare($sql);
$stmt->execute();
$query_results = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch (PDOException $e)
{
echo $e->getMessage();
die();
}
for ($i = 0; $i < count($query_results); $i++) {
echo $query_results[$i]['name']."</br>";
}
echo "resultamount: ".count($query_results);
此查询的结果量返回0(当然,循环不会启动)。如何修复此问题以便返回2行?
答案 0 :(得分:2)
不要在任何地方添加复杂性,你总是会有方便和可预测的结果
$db = new PDO("mysql:host=localhost;dbname=map1", 'root', 'root');
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "DROP TABLE IF EXISTS car;
CREATE TEMPORARY TABLE car (name (varchar 300), type (varchar 300));
INSERT INTO car(name, type) VALUES ('car1', 'coupe');
INSERT INTO car(name, type) VALUES ('car2', 'coupe');";
$db->exec($sql);
$sql = "SELECT * FROM car";
$stmt = $db->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "resultamount: ".count($results);