[thelist] syntax for mysql_query

Phil Turmel pturmel-webdev at turmel.org
Wed Apr 23 10:36:06 CDT 2008


Nan Harbison wrote:
> Hi folks,
>  
> I was using this syntax for queries to the db:
>  
> $query = blah blah blah;
> $results= mysql_query($query, $db_connection) or die (mysql_error()); 
>  
> This works sometimes, in fact, it seems to work and then later now work, and
> then it throws an error, so I end up removing $db_connection and then it
> works.
> $results= mysql_query($query) or die (mysql_error()); 
> Can someone tell me why sometimes this works and sometimes not?
> I googled it and didn't find anything helpful. I am not a db pro, obviously
> but I have ended up doing lots of queries recently.
>  
> Does this only work in some types of query - INSERT vs SELECT or DELETE or
> something?
>  
> TIA
> Nan

Hi Nan,

What you're describing sounds a lot like a variable scope problem, not a
problem with the mysql_query function.  Bad example:

$db_conn = mysql_connect("host", "user", "pwd");
function query_and_do_something() {
  $sql = "blah blah";
  $result = mysql_query($sql, $db_conn);
  if ($result === FALSE)
    die(mysql_error($db_conn));
}
query_and_do_something();

/*****/

Good example:

$db_conn = mysql_connect("host", "user", "pwd");
function query_and_do_something() {
  global $db_conn;
  $sql = "blah blah";
  $result = mysql_query($sql, $db_conn);
  if ($result === FALSE)
    die(mysql_error($db_conn));
}
query_and_do_something();

/*****/

Note the 'global' statement inside the function.  That enables access to the
database connection resource.  In your case, when you remove the connection
from the mysql_query function, it defaults to the last opened connection, [1]
which is likely to be the right one in a small application.  Can burn your a**
in a large app, though, so it's good practice to always specify it.

HTH,

Phil Turmel

[1] http://us2.php.net/manual/en/function.mysql-query.php

-- 
Need to contact me offlist? 
  Drop -webdev or you probably won't get through.



More information about the thelist mailing list