My code doesn't seem to work. I'm using the following:
$statement = $db->prepare("SELECT * FROM carts WHERE (order_id = ':order_id')");
$result = $statement->execute(array(':order_id' => $order_id));
$result = $statement->fetch();
Which returns a boolean according to gettype($result)
; print_r($result)
simply displays Array, though this is not expected. The data I'm reading is:
So I should expect an Array to be returned, not a Boolean. The PDO is correct and working, as I can call a write command. What's the best way using PDO to read a row based on the Primary Key order_id
into a parsable array?
And as a split, is there a more efficient way than SELECT * WHERE
to read a single row of data from a TABLE
when the data is based on the Primary Key
?
before all, set properly your error mode. If you can run the query with single quotes without an error popping, set this:
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$statement = $db->prepare("SELECT * FROM carts WHERE order_id=:order_id");
$result = $statement->execute(array(':order_id' => $order_id));
$row = ($result ? $statement->fetch(PDO::FETCH_ASSOC) : array('problem' => 'with your query'));
print_r($result);
PDO fails with single-quotes around parameters. check your $result
for the return value of execute()
. you may have to specify a fetching mode for the fetch. depending on your sql database, parenthesis around the condition may also cause the query to fail.
you have to store the result in somewhere, add:
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
next to $result = $statement->fetch();
to store in $rows
the data returned