What is the best practice for projecting SQL queries in PHP to display data on a webpage?
When projecting SQL queries in PHP to display data on a webpage, it is best practice to use prepared statements to prevent SQL injection attacks and ensure data security. Prepared statements separate the SQL query from the user input, making it impossible for malicious input to alter the query structure. This approach also improves performance by allowing the database to optimize query execution.
// Establish a database connection
$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);
}
// Prepare and execute a SQL query using prepared statements
$stmt = $conn->prepare("SELECT column1, column2 FROM table WHERE condition = ?");
$stmt->bind_param("s", $condition);
$condition = "value";
$stmt->execute();
$result = $stmt->get_result();
// Display data on the webpage
while ($row = $result->fetch_assoc()) {
echo "Column 1: " . $row['column1'] . " - Column 2: " . $row['column2'] . "<br>";
}
// Close the connection
$stmt->close();
$conn->close();