Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the best way to add data to a database? [closed]

Tags:

sql

php

$user='root';

try{
$pdo=new PDO('mysql:host=localhost;dbname=test',$user);
$pdo->exec('set character set utf8');
}
catch(PDOException $e){
echo 'Error: '.$e->getMessage();
}

//using bound variables?
$stmt=$pdo->prepare('insert into test(name) value(:name)');
$stmt->bindParam(':name',$_POST['name']);
$stmt->execute();

//using named parameters
$stmt=$pdo->prepare('insert into test(name) value(:name)');
$stmt->execute(array(':name'=>$_POST['name']));

//using placeholders
$stmt=$pdo->prepare('insert into test(name) value(?)');
$stmt->execute(array($_POST['name']));

//using bound parameters w/ placeholders
$stmt=$pdo->prepare('insert into test(name) value(?)');
$stmt->bindParam($_POST['name']);
$stmt->execute();

I just want to know what is the best to use for my as a PHP starter, I'm just confused what to use and I want to know what is the best and commonly use.

like image 324
Sui Go Avatar asked Feb 20 '23 09:02

Sui Go


1 Answers

I find the second method the best:

//using named parameters
$stmt=$pdo->prepare('insert into test(name) value(:name)');
$stmt->execute(array(':name'=>$_POST['name']));

You have named params, so you know what is what in the array - I hate looking at five or more ? in the code and trying to work out if the order is right, and it takes less lines of code to throw in an array and execute it all at the same time than going through many ->bindParam() lines.

If this option was off the table though, I would go through the many lines of ->bindParam() over the others.

This question comes down to personal preference. Choose what is best for you, what is easy to read and understand (especially if you come back to it weeks or months later) and what is easy to read for others who might have to pick through your code to debug it.

Edit: Nothing works faster as such. Putting the query together might take milliseconds longer one way or the other, but the queries will take the same amount of time to execute on the database. Faster really isn't something to look at here.

like image 182
Fluffeh Avatar answered Feb 25 '23 10:02

Fluffeh