致命错误:未被捕获的错误:不能使用PDOStatement类型的对象作为数组
作者:互联网
我想要一个php脚本,可以让我从数据库表中随机选择行,并将“ dispensered”的值更改为1.
我肯定这有点愚蠢,但是我对这个东西还是陌生的.
这是我的代码:
<?php
$hostname = 'localhost';
$user = 'root';
$pass = '';
$database = 'testt';
$db_connection = new PDO( "mysql:host=" . $hostname . ";dbname=" . $database,
$user, $pass );
$results = $db_connection->query( 'SELECT username, password FROM accounts WHERE dispensered = 0 ORDER by rand() LIMIT 1' );
$db_connection->query( 'UPDATE accounts SET dispensered=1 WHERE id='.$results['id'].'' );
foreach ( $results as $row ) {
echo '<p id="username">' . $row['username'] . '</p>';
echo '<p id="password">–' . $row['password'] . '</p>';
}
// Close the connection
$db_connection = null;
最好的祝福
Fatal error: Uncaught Error: Cannot use object of type PDOStatement as
array in C:\xampp\htdocs\test\index.php:13 Stack trace: #0 {main} thrown
in C:\xampp\htdocs\test\index.php on line 13
编辑:尝试过;
$test = $results;
$db_connection->query( 'UPDATE accounts SET dispensered=1 WHERE
id='.$test['id'].'' );
但这也没有用:(
解决方法:
PDO :: query —执行SQL语句,将结果集作为PDOStatement对象返回.您试图在更新查询中以数组形式访问$results.因此,您会看到此错误.您需要在for循环中从$row捕获’id’值,然后运行更新查询.
标签:fatal-error,select,mysql,php,pdo 来源: https://codeday.me/bug/20191024/1923254.html