0

I am trying to learn object oriented mysqli and I have a (pretty basic I'm sure) question. I am following the guide here

When it comes to writing queries, what's the difference (if any) between the following queries;

First

$sql = <<<SQL
    SELECT *
    FROM `users`
    WHERE `live` = 1 
SQL;

Second

$sql = ("SELECT * FROM users WHERE live = 1");

I would like to start as I mean to go on so any advice is appreciated.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
jonboy
  • 2,729
  • 6
  • 37
  • 77

2 Answers2

4

The first is heredoc syntax: heredoc

They both serve the same purpose. Using heredoc makes it easier to mix static text with variables without having to worry about string concatenation or using {$variable} to have variables inside strings.

Using heredoc also allows multilining your queries for easier reading in a cleaner way.

Disclaimer: I don't use heredoc extensively, but for lengthy queries it makes it easier to break down in lines and read them :)

Miguel Mesquita Alfaiate
  • 2,851
  • 5
  • 30
  • 56
0

I would advocate concatenation instead.

$sql = 'SELECT * FROM table WHERE ID = ' . (int)$somevar . ' LIMIT 1';

Or you can skip the concatenation in SQL and use a prepared statement instead.

$sql = 'SELECT * FROM table WHERE ID = ? LIMIT 1';

Heredoc does allow inlining but it's also MUCH stricter on rules and sometimes creates strange problems in coding, especially when you want to indent code (the closing string has to be on a line by itself with no indenting). Consider that it is considered a best practice that you indent code when you have code inside a block statement

// Syntax error
if($something) {
    $sql = <<<SQL
        SELECT *
        FROM `users`
        WHERE `live` = 1 
    SQL;
}

I know of no major open source PHP that makes extensive use of heredoc. Most write standard strings and either escape the data or use prepared statements

Community
  • 1
  • 1
Machavity
  • 30,841
  • 27
  • 92
  • 100
  • I mentined concatenation as means to building dynamic queries, not for concatenating parameters. But I totally hate that . notation . I like this better: `$var = "SELECT * FROM {$mytable}";` – Miguel Mesquita Alfaiate Jul 02 '15 at 16:25