简体   繁体   English

PHP注意:数组到字符串的转换

[英]PHP Notice: Array to string conversion in

I cannot seem to figure this out. 我似乎无法弄清楚。 I wrote a PHP script and I keep getting a Array to string conversion in... Notice as an error when trying to execute the postgres query: 我写了一个PHP脚本,并且不断获取Array到字符串的转换...请注意 ,尝试执行postgres查询时出现错误:

$tables = array(array('a','table1'),array('c','table2'));
$table = $tables[0][1];
$query = "SELECT * FROM " . $table . " WHERE id = :id LIMIT 1";
$select = $dbconn->prepare($query);
$id = $_GET['id'];
if($select->execute()){
}else{
    echo $select->errorInfo();
}

I am using PostgreSQL version 9.2.1 and the latest PHP 我正在使用PostgreSQL版本9.2.1和最新的PHP

PDOStatement::errorInfo() returns an array , but you are directly echoing it, which will always result in the string Array . PDOStatement::errorInfo()返回一个数组 ,但是您直接在回显它,它将始终导致字符串Array You must store its returned array, and access the components you wish to read: 您必须存储其返回的数组,并访问要阅读的组件:

$err = $select->errorInfo();
print_r($err);

// Example as lifted from PHP docs linked above:
PDO::errorInfo():
Array
(
    [0] => HY000
    [1] => 1
    [2] => near "bogus": syntax error
)

Incidentally, the E_NOTICE for array to string conversion is new in PHP 5.4. 顺便说一下,PHP 5.4中新增了用于数组到字符串转换的E_NOTICE The same code in PHP 5.3 would output Array as a string but would not issue the E_NOTICE . PHP 5.3中的相同代码将Array输出为字符串,但不会发出E_NOTICE

Since you are using PHP 5.4, you can dereference the message [2] directly if you wish: 由于您使用的是PHP 5.4,因此可以根据需要直接取消引用消息[2]

// 5.4+ only...
echo $select->errorInfo()[2];

Now why you are getting an error: 现在为什么会出现错误:

As to why you are entering the else block to report the error in the first place, you have a place holder for :id , but you never bound the variable $id before executing the query. 至于为什么要进入else块以首先报告错误,为什么有一个:id占位符,但是在执行查询之前您从未绑定变量$id

You may use 您可以使用

$select->execute(array(':id', $id))

Or 要么

$select->bindParam(':id', $id, PDO::PARAM_INT); // assuming an integer $id. Use PDO::PARAM_STR for strings

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

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