PDO - 将两个选择值放入数组中

时间:2013-05-30 17:04:35

标签: mysql arrays pdo

我有这个PDO:

$id = 1;
$title = 'resourceName';
$url = 'resourceURL';
$result = array($title => $url);

include('../dbconnect.php');

$pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_password);
$stmt = $pdo->prepare("SELECT resourceName, resourceURL FROM Resources WHERE categoryID = :id");
$stmt->bindParam(':id', $id);
$stmt->execute(array_values($result));
$row = $stmt->fetchAll();
print_r($row);

我刚收到此错误: 警告:PDOStatement :: execute()[pdostatement.execute]:SQLSTATE [HY093]:参数号无效:参数未定义

如何使PDO结果成为一个数组,其中resourceName是键,而resourceURL是值?

2 个答案:

答案 0 :(得分:1)

您正在将不需要的参数绑定到查询中。

$stmt->bindParam(':id', $id);
$stmt->execute(array_values($result)); //On this line. These parameters are 
                                         not needed

让我解释一下

$stmt->bindParam(':id', $id);

将$ id的值绑定到SQL参数:id和再次

$stmt->execute(array_values($result));

您正在绑定另一个没有任何索引的参数。

因此,您的查询需要1个参数,您要发送两个参数

解决方案:使用其中一个

要么

$stmt->bindParam(':id', $id);

或者,就像这样直接

$stmt->execute(array(":id" => $id));

之后,从行中获取列并将其转换为所需格式的新数组

$row = $stmt->fetchAll();
//Now assuming only one was returned from the database this might work
$new = array($row[0] -> resourceName => $row[0] -> resourceURL);

答案 1 :(得分:0)

你正在混合参数绑定

$id = 1;
$title = 'resourceName';
$url = 'resourceURL';
$result = array($title => $url);

include('../dbconnect.php');

$pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_password);
$stmt = $pdo->prepare("SELECT resourceName, resourceURL FROM Resources WHERE categoryID = :id");
$stmt->bindParam(':id', $id);
$stmt->execute(); //the array you put in execute will be used as parameter
$row = $stmt->fetchAll();
print_r($row);

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