I'm trying to go through the result of a paremeterized query in PHP. I'm trying this way
//creating a prepared statement
$stmt = $mysqli->stmt_init();
$query = "SELECT pcode,price,description FROM products WHERE description like ? ORDER BY PRICE";
$stmt->prepare($query);
$search_criteria = '%'.$search_criteria.'%';
$stmt->bind_param('s', $search_criteria);
$stmt->execute();
$i=0;
while($stmt->fetch())
{
if ($i %2 == 0) $trow = "even"; else $trow = "odd";
echo " <tr class='{$trow}'>";
echo " <td>{$row['pcode']}</td><td>{$row['price']}</td><td>{$row['description']}</td>";
echo " </tr>";
}
if ($i==0) {
echo "<tr class='even'><td colspan='3'><h3>No Results.</h3></td></tr>";
}
But my code is entering the if statement. How can I go through the result? The database is MySQL.
<?php
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
mysql_select_db($dbname) or die('Did you <a href="setupreset.php">setup/reset the DB</a>? <p><b>SQL Error:</b>' . mysql_error($conn) . '<p><b>SQL Statement:</b>' . $query);
function execute_query($the_query){
global $conn;
$result = mysql_query($the_query) or die('<font size=2><b>SQL Error:</b>' . mysql_error($conn) . '<br/><p><b>SQL Statement:</b>' . $the_query . '<br/>Did you run <i>setupreset.php</i> to setup/reset the DB?</font>');
return $result;
}
?>
CodePudding user response:
You need to bind the result to some variables:
$query = "SELECT pcode,price,description FROM products WHERE description like ? ORDER BY PRICE";
$stmt = $mysqli->prepare($query);
$search_criteria = '%'.$search_criteria.'%';
$stmt->bind_param('s', $search_criteria);
$stmt->execute();
$i=0; $pcode; $price; $description;
$stmt->bind_result($pcode, $price, $description);
while($stmt->fetch()) {
if ($i %2 == 0)
$trow = "even";
else
$trow = "odd";
echo " <tr class='{$trow}'>";
echo " <td>{$pcode}</td><td>{$price}</td><td>{$description}</td>";
echo " </tr>";
}