Re: [PHP] Quotes vs. Single Quote

[email protected] (tedd)
Newsgroups php.general
Message-ID <p06240802c881a2db7197@[192.168.1.104]>
At 10:10 PM -0400 8/5/10, Rick Dwyer wrote:
>2nd question, in the 3 [2] lines below:
>
>$checkstat = "select field from table where fieldid = $field_id";
>$result1 = @mysql_query($checkstat,$connection) or die("Couldn't 
>execute query");
>
>If I were to recode in the latter style, should they not look like this:
>
>$checkstat = 'select field from table where fieldid = "'.$field_id.'"';
>$result1 = @mysql_query($checkstat,$connection) or die('Couldn\'t 
>execute query');

Rick:

Others gave you good advice on quotes, but I'll address your second 
question on database queries.

The following is in the form of what I normally do:

$query = "SELECT field FROM table WHERE field_id = '$field_id' ";
$result = mysql_query($query) or die("Couldn't execute query");

Please note these are my preferences (others may have different preferences):

1. I use UPPERCASE for all MySQL syntax.

2. I do not use the @ before mysql_query because that suppresses 
errors. I prefer to see errors and fix them.

3. It's not necessary to include the second argument (i.e., 
$connection) in mysql_query.

4. IMO, a query should be named $query and a result should be named 
$result. If I have several results, then I use $result1, $result2, 
$result3, and so on.

5. I try to match MySQL field names to PHP variable names, such as 
field_id = '$field_id'. This makes it easier for me to read and debug.

6. Also note that the PHP variable $field_id is enclosed in single 
quotes within the query.

7. For sake of readability, in the query I also place a space after 
the last single quote and before the ending double quote, such as 
field_id = '$field_id' ". -- I do not like, nor is it readable, to 
have a singledouble quote (i.e., '").

There is one additional thing that I do, but it requires an included 
function. For your kind review, in my query I do this:

$result = mysql_query($query) or die(report($query,__LINE__,__FILE__)));

and the report function I include to the script is:

<?php
//====================  show dB errors  ======================

function report($query, $line, $file)
    {
    echo($query . '<br>' .$line . '<br>' . $file . '<br>' . mysql_error());
    }
?>

That way, if something goes wrong, the report function will show in 
what file and at what line number the error occurred. Now, this is OK 
for development, but for production you should comment out the echo 
so you don't report errors publicly. Besides, you should have all the 
errors fixed before your script becomes production anyway, right?  :-)

HTH,

tedd

-- 
-------
http://sperling.com  http://ancientstones.com  http://earthstones.com
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.