Updating old mysql_ based code involves more than just getting the code to run without any errors. The mysql_ extension itself has been removed. What little protection magic_quotes provided for string values has been removed. Error handling has been switched to use exceptions.
As to the first error, you would need to use the corresponding mysqli defined constant or use the mysqli_fetch_assoc() function. As to the second error, the code inside your loop is probably assigning a string to the $result variable, causing the error after the loop has executed the first time. You also need to change the mysql_error() call to use mysqli_error(), which also requires the connection variable as a parameter.
To future proof your code, you should -
- Use the much simpler and better designed PDO extension.
- Set the character set to match your database tables (you should be doing this now, but it was almost never done in old code or worked correctly with the old database extensions.)
- Set the default fetch mode to assoc, so that you don’t need to specify it in each fetch statement.
- For the PDO extension, set emulated prepared queries to false, so that you use real prepared queries.
- Set the error mode to use exceptions (this is the default setting now in php8+.)
- Use a prepared query when supplying dynamic data to a query when it gets executed.
- Only catch and handle a database exception for user recoverable errors, such as when inserting/updating duplicate user submitted data.
For the query/code you have shown, after you make the connection using the PDO extension, it would look like -
$query = "SELECT * FROM elezioni2024_liste";
$stmt = $pdo->query($query);
while($row = $stmt->fetch())
{
// your loop code using elements in $row
}
Typical PDO connection code -
$DB_HOST = ''; // database host name or ip address
$DB_USER = ''; // database username
$DB_PASS = ''; // database password
$DB_NAME = ''; // database name
$DB_ENCODING = 'utf8mb4'; // db character encoding. set to match your database table's character set. note: utf8 is an alias of utf8mb3/utf8mb4
$options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // set the error mode to exceptions. this is the default setting now in php8+
PDO::ATTR_EMULATE_PREPARES => false, // run real prepared queries
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC // set default fetch mode to assoc
];
$pdo = new pdo("mysql:host=$DB_HOST;dbname=$DB_NAME;charset=$DB_ENCODING",$DB_USER,$DB_PASS,$options);