What are the potential pitfalls when using the query function in PHP to retrieve data from a database?
One potential pitfall when using the query function in PHP to retrieve data from a database is the risk of SQL injection attacks if user input is not properly sanitized. To prevent this, always use prepared statements with parameterized queries to securely pass user input to the database.
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Use prepared statement with parameterized query
$stmt = $conn->prepare("SELECT * FROM table WHERE column = ?");
$stmt->bind_param("s", $user_input);
$user_input = $_POST['user_input']; // Assuming user input is coming from a form submission
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Process each row of data
}
$stmt->close();
$conn->close();