Skip to content
PHP Logo

How can one optimize the code to avoid deprecated functions like mysql_error() in PHP?

To avoid using deprecated functions like mysql_error() in PHP, you can switch to using the mysqli or PDO extension for database operations. These extensions provide more secure and efficient ways to interact with databases in PHP. By using prepared statements and error handling techniques provided by mysqli or PDO, you can ensure your code is up to date and secure.

php
// Connect to the database using mysqli
$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");

// Check for errors
if (!$result) {
    die("Error: " . $mysqli->error);
}

// Fetch data
while ($row = $result->fetch_assoc()) {
    // Process data
}

// Close connection
$mysqli->close();