What are the best practices for sending SQL queries to a database in PHP?
When sending SQL queries to a database in PHP, it is important to use prepared statements to prevent SQL injection attacks and ensure data security. Prepared statements separate SQL query logic from data inputs, allowing the database to distinguish between code and data. This helps to prevent malicious SQL injection attempts by treating input values as data rather than executable code.
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Prepare a SQL query using a prepared statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Set parameter values and execute the query
$username = "example_user";
$stmt->execute();
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo "Username: " . $row["username"];
}
// Close the statement and connection
$stmt->close();
$conn->close();