How can the deprecated function mysql_db_query be replaced in PHP when querying a database?
The deprecated function mysql_db_query can be replaced in PHP by using the mysqli extension or PDO (PHP Data Objects) for interacting with a database. Both mysqli and PDO provide more secure and efficient ways to query a database compared to the deprecated mysql extension.
// Using mysqli extension to query a 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_name";
$result = $conn->query($sql);
// Process the query result
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
}
} else {
echo "0 results";
}
// Close connection
$conn->close();
Related Questions
- What are the best practices for using header() function in PHP to avoid "headers already sent" error?
- How can PHP developers ensure better user experience by avoiding Captcha usage in their forms?
- What are the potential pitfalls of using image-based challenges as a spam protection method in PHP forums?