I am updating a mysqli database query to use prepared statements. This is the current PHP code:
$randomQQuery = "SELECT question FROM question WHERE tagOne='".$sub."' ORDER BY RAND() LIMIT 1";
$randomQ = mysqli_query($dbc,$randomQQuery);
$qRow = mysqli_fetch_array($randomQ);
$question = $qRow['question'];
This is my initial prepared statement attempt:
$randomQQuery = $dbc->prepare("SELECT question FROM question WHERE tagOne=? ORDER BY RAND() LIMIT 1");
$randomQQuery->bind_param('s',$sub);
$randomQQuery->execute();
$qRow = $randomQQuery->fetch_array();
$question = $qRow['question'];
- Do I need to name my variable $stmt? All examples i've looked at use that name.
- If so, how do I distinguish between numerous SQL queries and the use of a second different $stmt?
- Am i fetching the array and obtaining the $question correctly? I understand that 'bound results' are an option; are these best practice from a security perspective or just more efficient?
$stmtis common just be cause it makes it clear that it contains amysqli_stmtobject as opposed to amysqliresource.fetch_array()as you are, you must callget_result(), but that isn't available on every platform.bind_result()is, but is generally more tedious to use.$result = $randomQQuery->get_result();and then call$qRow = $result->fetch_array()to convert the prepared statement resource's result into a result resource. Per theget_result()docs I linked earlier, you can only do that if you are using the mysqlnd driver, which not every system has. If you get errors aboutget_result()not existing, you'll have to usebind_result()instead -- the principle annoyance of mysqli vs PDO.