Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting multiple rows with prepared statement

I'm quite new to prepared statements and am not sure I am doing this right.

Here is what I try:

$currgame = 310791;

$sql = "SELECT fk_player_id, player_tiles, player_draws, player_turn, player_passes, swapped FROM ".$prefix."_gameplayer WHERE fk_game_id = ?";
$stmt = $mysqli->stmt_init();

$data = array();
if($stmt->prepare($sql)){
    $stmt->bind_param('i', $currgame);
    $stmt->execute();

    $fk_player_id = null; $player_tiles = null; $player_draws = null; $player_turn = null; $player_passes = null; $swapped = null;
    $stmt->bind_result($fk_player_id, $player_tiles, $player_draws, $player_turn, $player_passes, $swapped);

    $res = $stmt->get_result();
    
    while ($row = $res->fetch_assoc()){
        $data[] = $row;
    }
    $stmt->close(); 
}

// to display own games
foreach ($data as $row) {
    if ($row['fk_player_id'] == $playerid) {
        
        $udraws = $row['player_draws']+1; 
        $upass = $row['player_passes'];
        $uswaps = $row['swapped'];
        
        echo 'uDraws: '.$udraws.'<br>';
        echo 'uPass: '.$upass.'<br>';
        echo 'uSwaps: '.$uswaps.'<br><br>';
    }
}
// to display other games
foreach ($data as $row) {
    if ($row['fk_player_id'] != $playerid) {
        
        $opponent = $row['fk_player_id'];
        $oppTiles = $row['player_tiles'];
        
        $odraws = $row['player_draws']+1;
        $opass = $row['player_passes'];
        $oswaps = $row['swapped'];
        
        echo 'oID: '.$opponent.'<br>';
        echo 'oTiles: '.$oppTiles.'<br>';
        
        echo 'oDraws: '.$odraws.'<br>';
        echo 'oPass: '.$opass.'<br>';
        echo 'oSwaps: '.$oswaps.'<br><br>';

    }
}

I get an "ServerError" when trying to run this: It is the $res = $stmt->get_result(); that makes the error, but not sure why.

PHP Fatal error: Call to undefined method mysqli_stmt::get_result() in /home/mypage/public_html/TEST/preparedstatement.php on line 61

like image 472
Mansa Avatar asked Feb 03 '13 10:02

Mansa


1 Answers

Depending on your PHP/MySQL setup you may not be able to use get_result().

The way to get around this is to bind the results.

For example:

$stmt->execute();

$fk_player_id = null; $player_tiles = null; $player_draws = null; $player_turn = null; $player_passes = null; $swapped = null;

$stmt->bind_result($fk_player_id, $player_tiles, $player_draws, $player_turn, $player_passes, $swapped);

while ($stmt->fetch()) { // For each row
    /* You can then use the variables declared above, which will have the 
    new values from the query every time $stmt->execute() is ran.*/
}

For more information click here

like image 75
EM-Creations Avatar answered Oct 20 '22 14:10

EM-Creations