使用PDO而不是mysql_*

REJ*_*OLA 0 php mysql pdo

我更改了以下代码:

mysql_connect('localhost','username','password');
mysql_select_db('pl') or die( "Unable to select database"); 
Run Code Online (Sandbox Code Playgroud)

PDO('mysql:host=localhost;dbname=pl;charset=UTF-8', 'username', 'password');
Run Code Online (Sandbox Code Playgroud)

它是正确的还是我必须将它传递给变量(在PDO教程中它被传递给变量db;它的目的是什么?http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers)

Dar*_*ill 6

修改您的代码:

PDO('mysql:host=localhost;dbname=pl;charset=UTF-8', 'username', 'password');
Run Code Online (Sandbox Code Playgroud)

至:

$Connection = new PDO('mysql:host=localhost;dbname=pl;charset=UTF-8', 'username', 'password');
Run Code Online (Sandbox Code Playgroud)

并且您的基本查询结构将围绕您的$Connection变量.例:

$Query = $Connection->query("LIST TABLES");
$Results = $Query->fetchAll();
Run Code Online (Sandbox Code Playgroud)

这有点像:

$Query = mysql_query("LIST TABLES");
$Results = mysql_fetch_array($Query);
Run Code Online (Sandbox Code Playgroud)

阅读这些手册:

构造连接(如mysql_connect/mysql_select_db)

PDO查询(类似于mysql_query();

准备好的陈述

执行准备好的陈述

PDO FetchAll(如mysql_fetch_array)

整个PDO手册

  • 请改用预备语句.`mysql_real_escape_string`和类似的技术很混乱,不处理所有注射. (2认同)
  • @ user1925118 - Kitsune使用Prepared语句是正确的; 但是PDO API还提供了一系列绑定,可以为您提供增强的保护 (2认同)