Search code examples
phpmysqliexecuteprepare

Calling prepare with mysqli won't fetch data


$data = $mysqli->prepare("SELECT amount FROM items WHERE id=:id");
echo 'forward1';
if(!$data->execute(array(':id' => $id)))
    die("error executing".$data->error);
echo '2';
$row = $data->fetch_object();
die('Losing my mind'.$row->amount);

This will only echo "forward1", not "error executing..." or "2". It works with *$mysqli->query". If I add quotes '' to :id in the query, it will echo "forward1error executing".


Solution

  • First, make sure you understand the prepared statements syntax and working model.

    As in:

    $data = $mysqli->prepare("SELECT amount FROM items WHERE id=(?)");
                // THIS ^^ actually "prepares" an object to be used in the statement
    $data->bind_param("i",$id)
                // ...then you "bind" the parameter for your statement as "i"(nteger)
    echo 'forward1';
    if(!$data->execute())  // And now you simply run it, with no other args
        die("error executing".$data->error);
    echo '2';
    $row = $data->fetch_object();
    die('Loosing my mind'.$row->amount);
    

    I suggest though using something more like

    $data->execute() or die("error executing".$data->error);
    

    The main steps of a prepared statement are: 1. Prepare the query with some placeholder values; 2. "Bind" the required number of values to the query; 3. Execute it!

    I fail to see why this is relevant in your case, with such a simple query. I also assume you actually need it for something bigger. Please let me know if I misunderstood your point or code sample.

    Oh, and.. have fun! :-)