When developing websites with PHP, developers may encounter various common errors. One typical error is PHP Fatal error: Call to undefined function mysql_query(). This issue usually occurs because the code is still using outdated database functions.
Starting from PHP 5.5, the mysql_* functions were deprecated, and they were completely removed in PHP 7. If your project still uses mysql_query() or similar functions, PHP will throw this fatal error.
To solve it, you should use either MySQLi or PDO, which are the officially recommended database extensions.
<?php $conn = new mysqli('localhost', 'username', 'password', 'database'); if ($conn->connect_error) { die('Failed to connect to database: ' . $conn->connect_error); } $sql = 'SELECT * FROM users'; $result = $conn->query($sql); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { echo 'Username: ' . $row['username'] . ', Email: ' . $row['email'] . '<br>'; } } else { echo 'No users found'; } $conn->close(); ?>
This example demonstrates how to use MySQLi to connect to a database, execute a query, and display results. If the connection fails, it returns an error message.
<?php $dsn = 'mysql:host=localhost;dbname=database'; $username = 'username'; $password = 'password'; try { $conn = new PDO($dsn, $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = 'SELECT * FROM users'; $stmt = $conn->query($sql); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo 'Username: ' . $row['username'] . ', Email: ' . $row['email'] . '<br>'; } } catch(PDOException $e) { echo 'Failed to connect to database: ' . $e->getMessage(); exit; } $conn = null; ?>
PDO not only works with MySQL but also supports multiple databases. It is more flexible and provides better error handling through exceptions.
The error PHP Fatal error: Call to undefined function mysql_query() usually occurs because the old MySQL extension is no longer supported in modern PHP versions. The solution is to update your code to use MySQLi or PDO. This ensures compatibility, improves security, and provides better functionality.
If your project still relies on mysql_* functions, it is strongly recommended to upgrade to MySQLi or PDO as soon as possible to maintain long-term stability and support.