What is the significance of mixing 'mysql' and 'mysqli' functions in the PHP code for database operations?
Mixing 'mysql' and 'mysqli' functions in PHP code for database operations can lead to errors and inconsistencies in the code. It is important to use either 'mysql' or 'mysqli' consistently throughout the codebase to ensure compatibility and maintainability. To solve this issue, you should choose one MySQL extension ('mysql' or 'mysqli') and stick with it for all database operations in your PHP code.
// Connect to MySQL using mysqli extension
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Perform database operations using mysqli functions
$sql = "SELECT * FROM table";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// Output data
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}
} else {
echo "0 results";
}
// Close connection
$mysqli->close();