How can the use of mysql_db_query be improved in PHP code?
The use of mysql_db_query in PHP code is deprecated and should be avoided. Instead, it is recommended to use the mysqli or PDO extension for interacting with a MySQL database. This will not only provide better security and performance but also ensure compatibility with newer versions of PHP.
// Improved way to query a MySQL database using mysqli
$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_name";
$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();
Keywords
Related Questions
- Are there specific PHP functions or techniques that can help in efficiently managing and serving cached images to users?
- What precautions should be taken when constructing URLs with query strings in PHP to ensure data security and integrity?
- What are the best practices for handling graphical representations of data in PHP, such as theater seating plans?