• 13
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

How do I check if a MySQL query is successful other than using die()

I'm trying to achieve...

mysql_query($query);

if(success){
//move file
}
else if(fail){
//display error
}

This is the first example in the manual page for mysql_query:

$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
    die('Invalid query: ' . mysql_error());
}

If you wish to use something other than die, then I'd suggest trigger_error.

  • 57
Reply Report
      • 2
    • @Rune: Right, but then you won't be able to use the query resource for further actions (i.e. for fetching actual data using mysql_fetch_* functions).
    • Use $result === false not !$result. REASON: There may be queries for which $result is a VALID (non-error) value that is equivalent to ZERO. (I think an empty string is another example.) In php, !0 evaluates to true, so your die would execute, even though is not an error. SIMILARLY, when you want the opposite test, for code that should execute when there is not an error, use if ($result !== false) rather than if ($result).

If your query failed, you'll receive a FALSE return value. Otherwise you'll receive a resource/TRUE.

$result = mysql_query($query);

if(!$result){
    /* check for error, die, etc */
}

Basically as long as it's not false, you're fine. Afterwards, you can continue your code.

if(!$result)

This part of the code actually runs your query.

  • 4
Reply Report

mysql_query function is used for executing mysql query in php. mysql_query returns false if query execution fails.Alternatively you can try using mysql_error() function For e.g

$result=mysql_query($sql)

or

die(mysql_error());

In above code snippet if query execution fails then it will terminate the execution and display mysql error while execution of sql query.

  • 2
Reply Report

put only :

or die(mysqli_error());

after your query

and it will retern the error as echo

example

// "Your Query" means you can put "Select/Update/Delete/Set" queries here
$qfetch = mysqli_fetch_assoc(mysqli_query("your query")) or die(mysqli_error()); 



    if (mysqli_errno()) {
        echo 'error' . mysqli_error();
        die();
    }
  • 1
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions