What are the best practices for handling database connections and queries in PHP, particularly when dealing with deprecated functions like mysql?
When dealing with deprecated functions like mysql in PHP, it is recommended to switch to newer and more secure alternatives like MySQLi or PDO. These alternatives provide better security features and support for prepared statements to prevent SQL injection attacks. By using these newer functions, you can ensure your database connections and queries are handled in a more secure and efficient manner.
// Using MySQLi for database connection and query
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();