简体   繁体   中英

Fatal error: Uncaught Error: Cannot use object of type PDOStatement as array

I want a php script that gives me a random selected row from my db table and change the value of "dispensered" to 1. Im sure its kinda stupid, but Im new to this stuff.

Here is my code:

<?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">&ndash;' . $row['password'] . '</p>';
}




// Close the connection
$db_connection = null;

Best regards

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

EDIT: Tried that;

$test = $results;
$db_connection->query( 'UPDATE accounts SET dispensered=1 WHERE 
id='.$test['id'].'' );

But it didnt work aswell :(

PDO::query — Executes an SQL statement, returning a result set as a PDOStatement object. You're trying to access the $results as an array in your update query. Hence you're seeing this error. You need to capture the 'id' value from $row in the for loop and run your update query after this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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