mysql - Using a prepared statement in php & mysqli -
i using prepared statements first time. , cannot select work. reason, returns records cannot them variables. know returns records because if add echo '1'; loop echo's 1 each record.
any assistance great. code below:
function builditems($quote_id){ if ($stmt = $this->link->prepare("select * `0_quotes_items` `quote_id` = ?")) { // bind variable parameter string. $stmt->bind_param("i", $quote_id); // execute statement. $stmt->execute(); while ($row = $stmt->fetch()) { echo $row['id']; } // close prepared statement. $stmt->close(); } } update: in error log, see following error after adding while ($row = $stmt->fetch_assoc()) { suggested:
php fatal error: call undefined method mysqli_stmt::fetch_assoc()
i found link same issue had, not understand how implement fix. assistance great, regards example.
the php mysqli fetch method not access query data using brackets notation: $row['id'].
so see 2 options remedy: first find line:
while ($row = $stmt->fetch()) { ...and modify to, either, first add bind_result method, , access data bit differently:
$stmt->bind_result($id, $other, $whatnot); // assuming 3 columns retrieved in query while ($row = $stmt->fetch()) { echo "$id $other $whatnot<br>"; } ...or, first access result object's fetch_assoc method , use fetch_assoc instead of fetch:
$result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { now can use table column names keys access query data in loop: $row['id'].
php mysqli method fetch requires use bind_result. doing allows call data variable names you've bound to.
to use field name result array index, such as: $row['id'], need use php mysqli fetch_assoc method. , use fetch_assoc need first result object in order access fetch_assoc method.
Comments
Post a Comment