What are the main differences between mysql_query and mysqli in PHP?
The main difference between mysql_query and mysqli in PHP is that mysql_query is deprecated as of PHP 5.5.0 and removed in PHP 7.0.0, while mysqli is the improved version of the MySQL extension and is recommended for use in PHP applications. Mysqli provides a more secure and feature-rich interface for interacting with MySQL databases compared to the old mysql extension.
// Using mysqli to query a MySQL database
$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);
}
// Query the database
$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";
}
// Close connection
$conn->close();
Keywords
Related Questions
- What are some best practices for handling file uploads in PHP to prevent loss of file extensions?
- What are the steps involved in installing APC or Wincache for PHP, including adding the DLL file to the ext directory and updating PHP.INI?
- How can PHP developers prevent sessions from being passed through target=_blank links?