Replacing mysql_query() with PDO or MySQLi

mysql_query() executed SQL through PHP's original MySQL extension. The extension was removed in PHP 7. Current code should use PDO or MySQLi, and variable data should be passed through prepared statements.

Historical mysql_query()

<?php
// Historical only: removed from PHP 7+
$query = 'SELECT name, class, mark FROM student';
$status = mysql_query($query);
?>

PDO query() for fixed SQL

<?php
$stmt = $dbo->query(
    'SELECT name, class, mark FROM student ORDER BY id'
);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

query() is appropriate for SQL that contains no untrusted values.

PDO prepare() for values

<?php
$stmt = $dbo->prepare(
    'SELECT name, class, mark FROM student WHERE class = :class'
);
$stmt->execute(['class' => 'Four']);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

MySQLi prepared statement

<?php
$stmt = $connection->prepare(
    'SELECT name, class, mark FROM student WHERE class = ?'
);
$class = 'Four';
$stmt->bind_param('s', $class);
$stmt->execute();
$result = $stmt->get_result();
?>

UPDATE and affected rows

<?php
$stmt = $dbo->prepare(
    'UPDATE student SET mark = :mark WHERE id = :id'
);
$stmt->execute(['mark' => 80, 'id' => 1]);
echo $stmt->rowCount();
?>

For failures, prefer exceptions or inspect the current driver's error information rather than terminating with a raw database error. See MySQL error handling and affected rows.

The sample student dataset remains available from student table SQL. For query fundamentals, continue with SELECT, WHERE, and UPDATE.

PHP-specific companions: MySQLi overview and MySQLi query examples.

← All PHP & MySQL topics




Subscribe to our YouTube Channel here



plus2net.com




SQL Video Tutorials










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer