What are the potential issues with using the mysql_query() function in PHP and how can they be avoided?
One potential issue with using the mysql_query() function in PHP is that it is deprecated as of PHP 5.5.0 and removed in PHP 7.0.0. To avoid this issue, it is recommended to use MySQLi or PDO for database operations in PHP.
// Using MySQLi instead of mysql_query()
// Create a connection
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Perform a query
$result = $mysqli->query("SELECT * FROM table");
// Process the result
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Field1: " . $row["field1"] . " - Field2: " . $row["field2"] . "<br>";
}
} else {
echo "0 results";
}
// Close the connection
$mysqli->close();