2

I have the following code and where if 1 row is found I would like to set the result to $aPrds, how can I do this?

$stmt = $db->prepare("select * from products where id=?");
$stmt->bind_param("s", $_GET['id']);

if($stmt->execute())
{
  $stmt->store_result();
  echo $stmt->num_rows;
  if($stmt->num_rows==1)
  {
    //SET RETURNED ROW TO aPrds 

  }
  else
  {
    echo "no results or too many found";
  }
}
else
{
   echo "sql invalid";
}

I have also tried the following code which has been unsuccessful (returns (null):

$stmt = $db->prepare("select productid, product_name, description from product where productid=?");
$a=1;
$stmt->bind_param("i", $a);
if($stmt->execute()){
    $stmt->store_result();
    if($stmt->num_rows==1){
        $stmt->bind_result($b, $c, $d);         
        print_r($b);
        print_r($c);
        print_r($aPrds);
    }else{
        echo "no result or more than 1 returned";
    }
}else{
    echo "invalid sql";
}

Please note that I have tested the SQL and it works, also the $db mysqli connection is definitely working.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Dino
  • 1,445
  • 4
  • 24
  • 43

1 Answers1

4

I think you are looking for the get_result and fetch_assoc methods:

// ....
$result = $stmt->get_result();
$aPrds = $result->fetch_assoc();
// ....

Edit:

Apparently these functions are not yet available (should have tested this, sorry). So this is tested:

function bind_array($stmt, &$row) {
    $md = $stmt->result_metadata();
    $params = array();
    while($field = $md->fetch_field()) {
        $params[] = &$row[$field->name];
    }

    call_user_func_array(array($stmt, 'bind_result'), $params);
}

// ....

if($stmt->execute()) {
    bind_array($stmt, $row);
    $stmt->fetch();

    print_r($row);

    // ....

And you second solution should also work if you added $stmt->fetch() after $stmt->bind_result($b, $c, $d);

vstm
  • 12,407
  • 1
  • 51
  • 47
  • Hi I tried adding the two lines but I seem to only get (null) when I print_r($aPrds), I have tested the sql and works fine.So i'm stumped. Please note I have added another code block above to show alternative code I have tried. – Dino Aug 10 '11 at 21:34
  • Thank you for the feedback. I have added a new solution which I've tested, so it should work. – vstm Aug 11 '11 at 05:30
  • I tried to use wile stms->fetch() but it's skipping the first record. How can we loop over all result records? – Lamar Jun 05 '16 at 10:32