jeudi 20 avril 2017

PHP - Safer and quickest way to interact with MySQL database [duplicate]

This question already has an answer here:

I'm developing in PHP since a couple of year by now and I am still wondering which is the best technique to interact with a MySQL database, to avoid SQL Injection and have good performance. I'm not including function or classes removed in PHP 7 since I'm using that version.

Connection
First of all, which is the safer way to create a connection to a database?


MySQLi class or mysqli_connect function (its alias) :
$host = '';
$username = '';
$password = '';
$database = '';
$conn = new mysqli($host, $username, $password, $database);
$conn = mysqli_connect($host, $username, $password, $database);


PDO :
$dsn = 'mysql:host=localhost;dbname=testdb';
$username = 'username';
$password = 'password';
$options = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
); 

$dbh = new PDO($dsn, $username, $password, $options);



Querying a database
Then, which is the safer and the quickest way to query a database? This time I've got three ways, but I'm pretty sure that the first one isn't great due to SQL Injection.


MySQLi class or mysqli_query function (its alias) :
$sql = "SOME SQL";
$conn->query($sql);
mysqli_query($conn,$sql);


PDOStatement::bindParam :
$sth = $dbh->prepare('SELECT * FROM table WHERE foo=?');
$sth->bindParam('s', $foo);
$foo = 'foo';
$sth->execute();


PDO::prepare and PDOStatement::execute :
$foo = 1;
$sth = $dbh->prepare('SELECT * FROM table WHERE foo = :foo_id');
$sth->execute(['foo_id' => $foo]);



Thanks!






Comments
0 Comments

0 commentaires:

Enregistrer un commentaire