Home > Database > Mysql Tutorial > MySQL Functions to PDO: A Secure and Modern Approach?

MySQL Functions to PDO: A Secure and Modern Approach?

Linda Hamilton
Release: 2025-01-10 09:12:40
Original
1062 people have browsed it

MySQL Functions to PDO: A Secure and Modern Approach?

Convert MySQL functions to PDO

Why switch?

MySQL functions have been deprecated due to their outdated architecture, lack of security features, and global state dependencies. PDO (PHP Data Objects) provides a modern, secure, object-oriented alternative for database operations.

Connect to database

MySQL:

<code class="language-php">$dsn = 'mysql:dbname=databasename;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

$dbh = new PDO($dsn, $user, $password);</code>
Copy after login

MSSQL:

<code class="language-php">$dsn = 'sqlsrv:Server=127.0.0.1;Database=databasename';
$user = 'dbuser';
$password = 'dbpass';

$dbh = new PDO($dsn, $user, $password);</code>
Copy after login

Execute query

PDO uses prepared statements to prevent SQL injection.

Use named variables:

<code class="language-php">$SQL = 'SELECT ID, EMAIL FROM users WHERE user=:username';
$stmt = $dbh->prepare($SQL);
$stmt->execute(['username' => $username]);</code>
Copy after login

Use index variables:

<code class="language-php">$SQL = 'SELECT ID, EMAIL FROM users WHERE user=?';
$stmt = $dbh->prepare($SQL);
$stmt->execute([$username]);</code>
Copy after login

Get results

Use fetchAll:

<code class="language-php">$rows = $stmt->fetchAll();</code>
Copy after login

Use fetch:

<code class="language-php">while ($row = $stmt->fetch()) {
  echo $row['ID'], $row['EMAIL'];
}</code>
Copy after login

The above is the detailed content of MySQL Functions to PDO: A Secure and Modern Approach?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template