In the provided PHP script, what potential pitfalls or issues can arise from not properly handling SQL queries and result sets?
Potential pitfalls of not properly handling SQL queries and result sets include SQL injection attacks, data loss or corruption, and inefficient queries leading to poor performance. To mitigate these risks, always use prepared statements with parameterized queries to prevent SQL injection, handle errors and exceptions properly to avoid data loss, and fetch and process result sets correctly to ensure accurate data retrieval.
// Example of properly handling SQL queries and result sets
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare a parameterized query
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
// Set the parameter value and execute the query
$id = 1;
$stmt->execute();
// Process the result set
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Process each row of data
echo "Name: " . $row["name"] . "<br>";
}
// Close the statement and connection
$stmt->close();
$conn->close();