简体   繁体   中英

Best way to do a mysql query

Currently I am using:

$query = SELECT * FROM `table` WHERE `id`='column';
$mydata = mysql_query($query);
$element = mysql_result($mydata, 0, "Element");

Is there a faster and a better way to do the same?

You can use mysql, mysqli or PDO. It depends on your requirement and you have to consider few aspects when you are choosing one.

If you are only considering performance, mysql is the fastest one. Though mysql_* functions deprecated after 5.5.x and will not exist in PHP7.

But if you are considering Database support, API, Named parameters, Object mapping, Prepared statements, Stored procedures, etc, you can choose one between mysqli or PDO. mysqli only support mysql database while PDO support 12 databases.

    +--------------------+----------------------+------------------+
    |                    | PDO                  | MySQLi           |
    +--------------------+----------------------+------------------+
    | Database support   | 12 different drivers | MySQL only       |
    | API                | OOP                  | OOP + procedural |
    | Connection         | Easy                 | Easy             |
    | Named parameters   | Yes                  | No               |
    | Object mapping     | Yes                  | Yes              |
    | Prepared statements| Yes                  | Yes              |
    | (client side)                                                |
    | Performance        | Fast                 | Fast             |
    | Stored procedures  | Yes                  | Yes              |
    +--------------------+----------------------+------------------+

This blog has a good comparison between mysqli and PDO

My recommendation is using PDO.

mysql

$c = mysql_connect("example.com", "user", "password");
mysql_select_db("database");
$result = mysql_query("SELECT id, first_name, last_name FROM users");
$rows = mysql_fetch_assoc($result);
var_dump($rows);

mysqli

$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT id, first_name, last_name FROM users");
$row = $result->fetch_assoc();
var_dump($rows);

PDO

$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT id, first_name, last_name FROM users");
$row = $statement->fetch(PDO::FETCH_ASSOC);
var_dump($rows);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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