Skip to content
PHP Logo

What best practices should be followed when building and executing dynamic MySQL queries in PHP?

When building and executing dynamic MySQL queries in PHP, it is important to use prepared statements to prevent SQL injection attacks and improve performance. Additionally, it is recommended to properly sanitize user input to ensure data integrity and security. Lastly, consider using parameter binding to pass variables to the query instead of directly concatenating them into the SQL statement.

php
// Example of building and executing a dynamic MySQL query in PHP using prepared statements

// 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 SQL statement with a placeholder for dynamic data
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");

// Bind parameters to the prepared statement
$stmt->bind_param("s", $username);

// Set the value of the username variable
$username = "john_doe";

// Execute the prepared statement
$stmt->execute();

// Get the result set
$result = $stmt->get_result();

// Fetch and display the data
while ($row = $result->fetch_assoc()) {
    echo "Username: " . $row["username"] . "<br>";
}

// Close the statement and connection
$stmt->close();
$conn->close();