When I was learning about SQL security and preventing SQL injection, I learnt that its better to use bindparam when fetching results for an id like this:
//Prepare Statement
$stmt = $mysqli->prepare("SELECT * FROM my_table WHERE id=?");
if ( false===$stmt ) {
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}
$rc = $stmt->bind_param("i", $id);
if ( false===$rc ) {
die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$rc = $stmt->execute();
if ( false===$rc ) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
// Get the data result from the query. You need to bind results for each column that is called in the prepare statement above
$stmt->bind_result($col1, $col2, $col3, $col4);
/* fetch values and store them to each variables */
while ($stmt->fetch()) {
$id = $col1;
$abc = $col2;
$def = $col3;
$xyz = $col4;
}
$stmt->close();
$mysqli->close();
Atm, when I am fetching all results, I am using this:
$query= "SELECT * FROM my_table";
$result=mysqli_query($connect, $query);
if (!$result)
{
die('Error fetching results: ' . mysqli_error());
exit();
}
echo '<table border="1">'; // start a table tag in the HTML
//Storing the results in an Array
while ($row = mysqli_fetch_array($result)) //Creates a loop to loop through results
{
echo "<tr><td>" . $row['abc'] . "</td><td>" . $row['def'] . "</td><td>" . $row['xyz'] . "</td></tr>";
}
echo '</table>'; //Close the table in HTML
My question is:
For my second code, do I need to use
bind_result
when fetching all results for any security reasons similar to my first example?If yes, how can I use prepare statement with
bind_result
when I am fetching all results and not using$id
?If I use the second example the way it is for fetching all results, are there any security issues?