代码源自: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行?

最佳答案

不要无所不在地增加复杂性,您将始终获得方便和可预测的结果

$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);

关于php - 处理来自PDO多重查询的结果行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22833919/

10-13 01:51