我想要一个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'].'' );
但是它也不起作用:(
答案 0 :(得分:4)
PDO :: query —执行一条SQL语句,将结果集作为PDOStatement对象返回。您试图在更新查询中以数组形式访问$ results。因此,您会看到此错误。您需要在for循环中从$ row中捕获“ id”值,然后在此之后运行更新查询。