0

i am new to php pdo and im trying to make a tournamentcms which randomly generates matches by closing registration. i keep getting this error Uncaught Error: Cannot use object of type stdClass as array. Does anyone know how to fix this or know what i did wrong? all help is appreciated.

i've tried switching up fetch methods but did not change anything.

<?php
include 'db.php';
?>
</head>


<?php
if(isset($_GET["id"])){
   $stmt = $conn->prepare("SELECT * FROM registration WHERE tournament_id = :id 
   ORDER BY RAND()");
   $stmt->execute([":id" => $_GET["id"]
]);

$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$values = array();

$amount = count($result);

for($i = 0; $i < $amount; $i += 2)
{
$values[] = '(' . $result[$i]['id'] . ',' . $result[$i + 1]['id'] . ', :tournament_id)';
}

$values = implode(',', $values);

$stmt = $conn->prepare("insert into game(player1, player2, tournament_id) values ($values)");

$stmt->execute([
    ":tournament_id" => $_GET["id"]
]);

$stmt = $conn->prepare('update tournament set active = 1 where id = :id');
$stmt->execute([
   ':id' => $_GET['id']
]);

header('Location:index.php');

}

?>

the outcome of this piece of code should be that when i close the registrations for the tournament. registrated players should get inserted to the game table in a random order so matches for the tournament get automatically generated.

1 Answer 1

1

I'm pretty sure that the error was thrown before trying to use the PDO::FETCH_ASSOC fetch style. From the documentation of the fetchAll method:

fetch_style controls the contents of the returned array as documented in PDOStatement::fetch(). Defaults to value of PDO::ATTR_DEFAULT_FETCH_MODE (which defaults to PDO::FETCH_BOTH)

Using it like in your code should not cause that error. If it still does it means the error might be thrown in some other place. You could give this a try:

$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$values = [];

while (!empty($results)) {
    $firstPlayer = array_shift($results);
    $secondPlayer = array_shift($results);

    if ($firstPlayer !== null && $secondPlayer !== null) {
        $values[] = '(' . $firstPlayer['id'] . ',' . $secondPlayer['id'] . ', :tournament_id)';
    }
}

$values = implode(',', $values);

// Please note that you must not wrap the resulted `$values` by brackets
$stmt = $conn->prepare("insert into game(player1, player2, tournament_id) values $values");

If the error is still thrown then try $firstPlayer->id and $secondPlayer->id but the reason of returning objects instead of associative arrays would be very strange as you already requested the array fetch style.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.