简体   繁体   English

使用PHP连接和查询MySQL数据库的最佳方法是什么?

[英]What is the best way to connect to and query a MySQL database using PHP?

This is a pretty easy question but I would like some clarity on something. 这是一个非常简单的问题,但我想对某些内容进行澄清。

I have seen a number of different ways to connect and query a MySql Database using PHP but which is the best way to connect and create a query using php ? 我已经看到了许多使用PHP连接和查询MySql数据库的方法,但是哪种方法是使用php连接和创建查询的最佳方法?

Hope this makes sense. 希望这是有道理的。

Thanks 谢谢

By far the best way is to use prepared statements . 到目前为止,最好的方法是使用准备好的语句 You can do this using PDO or mysqli, but I prefer the PDO extension for its named parameters. 您可以使用PDO或mysqli来执行此操作,但是我更喜欢PDO扩展作为其命名参数。

Why are prepared statements by far the best way? 为什么迄今为止准备好的陈述是最好的方法? Because they take care of parameter quoting and escaping for you. 因为它们会为您处理参数引用和转义。

Bad, old, error-prone, tedious way: 错误,古老,容易出错,乏味的方式:

$result = mysql_query("SELECT * FROM users WHERE 
                       password='".mysql_real_escape_string($password)."'");

You can bet that, if you've written an application like this, you will have forgotten at some point to escape the user input, and left a gaping SQL injection hole. 您可以打赌,如果您编写了这样的应用程序,那么您有时会忘记转义用户输入,而留下了一个巨大的SQL注入孔。

Nice prepared statement way: 好准备的声明方式:

$stmt = $dbh->prepare("SELECT * FROM users WHERE password=:password");
$stmt->bindParam(':password', $password);
$stmt->execute();

Escaping is done for you, and you don't even have to worry about putting quotes around the parameter types that need them. 转义已为您完成,您甚至不必担心在需要引号的参数类型周围加上引号。

Use the object-oriented versions , assuming your php version is new enough to support 'em. 假设您的php版本足够新以支持'em,请使用面向对象的版本 They're far cleaner IMHO than the random function soup. 他们比随机功能汤干净得多恕我直言。

I don't think it's quite as simple as saying "the best way is..." 我认为这并不像说“最好的方法是……”那么简单

Personally, I hardly ever connect to a database using my own code, I normally have a framework doing that for me. 就我个人而言,我几乎从来没有使用自己的代码连接到数据库,通常我有一个框架可以为我这样做。 That said, I'd use the PHP Data Object (PDO) approach to connect and query a database, if I were writing a small standalone application. 就是说,如果我正在编写一个小型独立应用程序,那么我将使用PHP数据对象(PDO)方法来连接和查询数据库。

See the manual pages for all the information and examples you'll need. 有关所需的所有信息和示例,请参见手册页

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM