the_boy_za
the_boy_za

Reputation: 287

bind param array php mysql

I have written a code to bind with an array. The code i have now is:

$user_id = $_SESSION['user_id'];

$db = new mysqli("localhost", "username", "password", "database");

$stmt = $db -> prepare("SELECT aps FROM `scu_user-data` WHERE id=? LIMIT 1");
$stmt->bind_param('i', $user_id);
$stmt->execute();
$res = $stmt->get_result();

while ($row = $res->fetch_array(MYSQLI_ASSOC)) {
  if ($res[0] == 0){
    echo '<script type="text/javascript">';
    echo 'window.location = "http://localhost/system/aps.php"';
    echo '</script>';
  } else {
    echo " ";
  }
}

$stmt->close();

i get an errror message saying:

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

Upvotes: 0

Views: 55

Answers (2)

Joni
Joni

Reputation: 111229

The error is here:

if ($res[0] == 0)

$res is a result set object. Presumably you meant to use the variable $row you used on the previous line:

if ($row['aps'] == 0)

Upvotes: 1

dearsina
dearsina

Reputation: 5192

By using the MYSQLI_ASSOC constant your code will behave identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will behave identically to the mysqli_fetch_row() function, which is the one I think you want.

Try using MYSQLI_NUM.

Also, make sure you check to see whether the query has run successfully before attempting to extract rows from it, change $res = $stmt->get_result(); to:

if(!$res = $stmt->get_result()){
    die($db->error);
}

Upvotes: 0

Related Questions