What are some tips for effectively using PHP to interact with a MySQL database?
When interacting with a MySQL database using PHP, it is important to properly establish a connection, execute queries securely to prevent SQL injection, and handle errors gracefully. One way to achieve this is by using prepared statements to parameterize queries and sanitize user input.
// Establish a connection to the MySQL 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);
}
// Prepare a SQL statement using prepared statements
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Set parameters and execute
$username = "john_doe";
$stmt->execute();
// Bind result variables
$stmt->bind_result($id, $name, $email);
// Fetch results
while ($stmt->fetch()) {
echo "ID: $id, Name: $name, Email: $email";
}
// Close statement and connection
$stmt->close();
$conn->close();