tags:

views:

108

answers:

2

Hi,

I have a query written as

  mysql_query($query,$conn) 
    or 
    die(
    "A MySQL error has occurred.<br />Your Query: " . $query . "<br /> Error: (" . mysql_errno() . ") " . mysql_error());
    echo "You have been entered into our Database!";

This outputs

A MySQL error has occurred.
Your Query: INSERT INTO users (uid, twname, privacy) VALUES (15400743, 'gdhdh', 'accepted')
Error: (0)

so it doesn't list any errors or anything. When I copy/paste that query into the SQL tab of PHPMyAdmin, it runs successfully, and the DB connection isn't throwing anything bad (I know it works because a query works well elsewhere):

function get_db_conn() {
$conn = mysql_connect($GLOBALS['db_ip'], $GLOBALS['db_user'], $GLOBALS['db_pass']);
mysql_select_db($GLOBALS['db_name'], $conn); 
return $conn;

}

Any thoughts on what I could fix? I'd really appreciate it.

A: 

I'm not sure if this is exactly what you're looking for, but the argument to the function is called $query, and the variable in your error is $your_query, so the value of $your_query displays in the error, but who knows what is in $query, so if it's NULL, that might cause the error number 0 with no message.

Lazy Bob
D'oh! I'd changed that in my live script, sorry for leaving it in. Good eye! It indeed outputs the written string when echo$query is called...
Alex Mcp
But that didn't solve the problem. Any other suggestions?
Alex Mcp
+2  A: 

Error 0 means that no error occurred.

Therefore if the code to output an error is being run when no error occurred you have a logic error in your code surrounding the call to the mysql_query() function.

It's hard to tell from your code what should and shouldn't run under different conditions and where the error may lie.

The following code is logically equivalent to what you are trying to achieve and should work as expected.

This code more clearly separates calling the mysql_query() function from checking the result of calling the function. I have also formatted the code a little to that it displays without any horizontal scrolling, although that's purely optional.

$queryResult = mysql_query($query, $conn);
if ($queryResult === false) {
    $errorMessage = "A MySQL error has occurred.<br />"
                  . "Your Query: ".$query."<br />"
                  . " Error: (".mysql_errno().") ".mysql_error();

    die($errorMessage);
}
Jon Cram
One unrelated question: Why the triple equals to check for false? Just style? Can false be represented in other ways?
Alex Mcp
@Alex Mcp: Style and habit mostly. Triple equals compares equality of both value and type. In this case it doesn't matter. In some cases a function might return zero or false, where zero would be a legitimate and expected return value and false would indicate an error. See the str_pos function (http://php.net/str_pos) for an example of where getting your zero and false mixed up can create insidious bugs that can be very hard to track down.
Jon Cram