Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for writing sql statements in php

Tags:

php

mysql

Can someone point me towards a resource or show me an example of a good way of writing sql statements in php.

Most statements seem so ugly and unreadable.

like image 377
gregh Avatar asked Jun 15 '10 20:06

gregh


People also ask

Can we write SQL code in PHP?

You can use php/mssql extensions .

Is PHP used in SQL?

While PHP often does mediate between SQL and HTML its is capable of doing many more things and does not require SQL at all. In your scenario; HTML is how you view data, MySQL is how you store data, PHP is how you control the process of getting data from MySQL to HTML.


1 Answers

  1. Use prepared statements
  2. Feel free to format your code

Code sample:

$stmt = $pdo->prepare('
    SELECT ...
    FROM   ...
    JOIN   ...
    JOIN   ...
    WHERE  ... AND abc = :abc AND def = :def
');

$stmt->execute(array(
    'abc' => 'abc value',
    'def' => 'def value'
));
like image 156
Crozin Avatar answered Sep 28 '22 21:09

Crozin