-1

Since PHP5 and with the delete of mysql_query (RIP.) I'm quite confused on what the most effecient way to run a query. Since there are multiple ways.

The options that I know of are these:

Option 1:

$getInfo = "SELECT * FROM app2 WHERE id='". $appID ."' ";
$oStmt = $dbportal->prepare($getInfo);
$oStmt = $dbportal->execute();

I believe this is PDO.

Option 2:

$createQuery="INSERT INTO usr2 SET login='". $user ."', role='". $role ."'";
$dbportal->query($createQuery);

kinda PDOish?

Would someone be so kinda to push me in the right direction? A link is fine too, couldn't find anything

OfficialBAMM. \o/

  • 4
    Those are incredibly terrible ways of running queries since you are still using string interpolation which is as vulnerable as `mysql_query` would be. Go through this and you'll find much better ways http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?s=1|22.9210 – Hanky Panky Feb 20 '15 at 09:00
  • @Hanky, thanks. The unedited answer wasn't very helpfull >. –  Feb 20 '15 at 09:19

1 Answers1

1

To prevent SQL injection, you should use prepared statements with placeholders:

$getInfo = "SELECT * FROM app2 WHERE id = :id";
$oStmt = $dbportal->prepare($getInfo);
$oStmt->execute(array(':id' => $appID));

Efficiency should not be a concern until you get the code correct. Premature optimization is the root of all evil. And the slow part of performing a database query is accessing the data, not the way you call it.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I am not sure, what does the PO mean by the word "efficient"? The fastest? But prepared statements are almost as fast as primitive `query()` calls. Cause you'll need to escape the suspicious variables anyway. – user4035 Feb 20 '15 at 09:03
  • 3
    Who cares what he means by it? The bottleneck is almost certainly going o be in searching the database, not the form of the query. – Barmar Feb 20 '15 at 09:07
  • @barmar if I have a query without user input, is it okay not to use PDO? –  Feb 20 '15 at 10:06
  • It's still a good idea to use placeholders, you don't have to worry about special characters in the data. – Barmar Feb 20 '15 at 10:10
  • Sorry, placeholders? I'm guessing `':id' => $appID`? –  Feb 20 '15 at 10:21
  • Placeholders are the `:xxx` in the query, e.g. `WHERE id = :id`. They get replaced with the parameters in the `execute()` array, or you can use `$oStmt->bindParam()` to bind them to variables. – Barmar Feb 20 '15 at 10:23
  • This is all explained in the PDO documentation. – Barmar Feb 20 '15 at 10:23
  • Okay thanks. I'll read the PDO doc instead of bothering you. Thanks for your help! –  Feb 20 '15 at 10:26