MySQLi prepared statements displaying error becaus

2019-08-11 18:23发布

问题:

I am using this code to run a select statement in MySQLi

$stmt = $mysqli->prepare('SELECT * FROM admin WHERE forename = ? and surname = ? ');
$stmt->bind_param('vv', $forename, $surname);

$foremame = "Forename";
$surname = "Surname";

$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    echo $row["sequence"];
}
$stmt -> close();
$mysqli -> close();

But I am getting a fatal error saying:

Fatal error: Call to undefined method mysqli_stmt::get_result()

Because I do not have MySQLnd installed but I cannot install it as I am using a shared web server and the host will not install it.

How can I use a MySQLi prepared statement without having to have MySQLnd installed as I want to prevent SQL injection attacks

回答1:

You can use $stmt->bind_result() to bind the results to variables, then $stmt->fetch() to fetch the results into the bound variables.

$stmt->execute();
$stmt->bind_result($var1, $var2, $var3, ...); // Use more meaningful variable names

while ($stmt->fetch()) {
    echo $var3; // to get the third column in the results
}

I strongly recommend listing the colum names explicitly in the SELECT clause, rather than *, since this method of accessing the results is dependent on the specific order of the columns.



标签: php mysql mysqli