Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I write PHP code across multiple lines per statement?

Is it okay to write code like this, with statements spanning across multiple lines?

$db_selected = 
mysql_select_db(
    'my_dbase', 
    mysql_connect(
        'localhost', 
        'mysql_user', 
        'mysql_password'
    )
);

In HTML, new lines are ignored, but in PHP I sometimes get errors. I'm not too familiar with PHP, but thought this should be just fine, no?

like image 515
tim Avatar asked Jul 14 '11 21:07

tim


3 Answers

Yes, but for certain things, such as text I do something like ...

$someText = " blah blah blah ".
"some more blah blah blah";

Hope this helps

UPDATE 2022 haha

I know this is super old, but another way would be using EOF

$str = <<<EOF

   You can put whatever <p>text</p>. <b>you want to put</b> 
in here, for as
many lines as you want ()I)(#*$)#*($)#

EOF;
like image 92
Brian Patterson Avatar answered Oct 28 '22 13:10

Brian Patterson


No, but not for why you think. The whitespace is fine, but there is an issue with that code:

mysql_select_db(
    'my_dbase', 
    // don't call mysql_connect here!!!
    mysql_connect( 
        'localhost', 
        'mysql_user', 
        'mysql_password'
    )
);

MySQL connect will return FALSE on error. This means that you'll not be able to handle the mysql_error() there AND it will cause an error in mysql_select_db.

You're better off:

$conn = mysql_connect( 
        'localhost', 
        'mysql_user', 
        'mysql_password'
) or die( mysql_error() );

mysql_select_db(
    'my_dbase', 
    $conn // optional parameter, but useful nonetheless.
);
like image 26
cwallenpoole Avatar answered Oct 28 '22 12:10

cwallenpoole


Whitespace is generally ignored, so you can insert line breaks as needed. However, you need to end each statement with a semicolon (;).

like image 32
George Cummins Avatar answered Oct 28 '22 13:10

George Cummins