?
Solved

Display MySQL error in PHP

Posted on 2011-10-04
8
Medium Priority
?
275 Views
Last Modified: 2012-05-12
I am using the following code in my script to perform a SQL operation.  The only problem is that if there is an issue with the query it does not actually give me the error to track down the problem.  How do I alter this to display the error message MySQL reports?

 
   $query1 = "TRUNCATE TABLE ALIASES";
    $result = mysql_query($query1);

    if ($result) 
       echo "ALIASES Table Reset
		 
	";
    else 
       echo "There was a problem resetting ALIASES
		 
	";

Open in new window

0
Comment
Question by:pda4me
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 36909046
$query1 = "TRUNCATE TABLE ALIASES";
$result = mysql_query($query1) or die('Error: ' . mysql_error();

But remember to clear this statement in your production environment to avoid to show your queries to malicious users: use it only in developing environment.

Cheers
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 36909112
Here is a little teaching example that shows the design patterns I like to use.  It shows the failing query along with the diagnostic information.
<?php // RAY_mysql_example.php
error_reporting(E_ALL);


// THE ABSOLUTE MINIMUM YOU MUST UNDERSTAND TO USE PHP AND MYSQL
// MAN PAGE: http://php.net/manual/en/ref.mysql.php
// MAN PAGE: http://php.net/manual/en/mysql.installation.php
// MAN PAGE: http://php.net/manual/en/function.mysql-connect.php
// MAN PAGE: http://php.net/manual/en/function.mysql-select-db.php
// MAN PAGE: http://php.net/manual/en/function.mysql-real-escape-string.php
// MAN PAGE: http://php.net/manual/en/function.mysql-query.php
// MAN PAGE: http://php.net/manual/en/function.mysql-errno.php
// MAN PAGE: http://php.net/manual/en/function.mysql-error.php
// MAN PAGE: http://php.net/manual/en/function.mysql-num-rows.php
// MAN PAGE: http://php.net/manual/en/function.mysql-fetch-assoc.php
// MAN PAGE: http://php.net/manual/en/function.mysql-fetch-array.php
// MAN PAGE: http://php.net/manual/en/function.mysql-insert-id.php



// CONNECTION AND SELECTION VARIABLES FOR THE DATABASE
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";        // GET THESE FROM YOUR HOSTING COMPANY
$db_user = "??";
$db_word = "??";


// OPEN A CONNECTION TO THE DATA BASE SERVER
if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB CONNECTION: ";
    echo "<br/> $errmsg <br/>";
}

// SELECT THE MYSQL DATA BASE
if (!$db_sel = mysql_select_db($db_name, $db_connection))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB SELECTION: ";
    echo "<br/> $errmsg <br/>";
    die('NO DATA BASE');
}
// IF THE SCRIPT GETS THIS FAR IT CAN DO QUERIES




// ESCAPE AN EXTERNAL DATA FIELD FOR USE IN MYSQL QUERIES
$safe_username = mysql_real_escape_string($_POST["username"]);




// CREATE AND SEND A SELECT QUERY AND TEST THE RESULTS
$sql = "SELECT id FROM my_table WHERE username='$safe_username'";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, SHOW THE ERROR
if (!$res)
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/>$sql <br/>";
    die($errmsg);
}
// IF WE GET THIS FAR, THE QUERY SUCCEEDED AND WE HAVE A RESOURCE-ID IN $res SO WE CAN NOW USE $res IN OTHER MYSQL FUNCTIONS




// DETERMINE HOW MANY ROWS OF RESULTS WE GOT
$num = mysql_num_rows($res);
if (!$num)
{
    echo "<br/>QUERY FOUND NO DATA: ";
    echo "<br/>$sql <br/>";
}
else
{
    echo "<br/>QUERY FOUND $num ROWS OF DATA ";
    echo "<br/>$sql <br/>";
}




// ITERATE OVER THE RESULTS SET TO SHOW WHAT WE FOUND
while ($row = mysql_fetch_assoc($res))
{
    var_dump($row);
}




// A WAY OF DETERMINING HOW MANY ROWS WE HAVE IN A TABLE
$sql = "SELECT COUNT(*) FROM my_table";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/>$sql <br/>";
    die($errmsg);
}
// GET THE RESULTS SET ROW IN AN ARRAY WITH A NUMERIC INDEX - POSITION ZERO IS THE COUNT
$row = mysql_fetch_array($res, MYSQL_NUM);
$num = $row[0];
$fmt = number_format($num);
echo "<br/>THERE ARE $fmt ROWS IN THE TABLE";




// MAKING AN INSERT QUERY AND TESTING THE RESULTS
$sql = "INSERT INTO my_table (username) VALUES ('$safe_username')";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/>$sql <br/>";
    die($errmsg);
}
// GET THE AUTO_INCREMENT ID OF THE RECORD JUST INSERTED - PER THE DB CONNECTION
$id  = mysql_insert_id($db_connection);
echo "<br/>YOU JUST INSERTED A RECORD WITH AUTO_INCREMENT ID = $id";

Open in new window

0
 
LVL 27

Expert Comment

by:Cornelia Yoder
ID: 36909118
  $query1 = "TRUNCATE TABLE ALIASES";
echo mysql_error();
    $result = mysql_query($query1);
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 27

Expert Comment

by:Cornelia Yoder
ID: 36909122
Ooops sorry

$query1 = "TRUNCATE TABLE ALIASES";
$result = mysql_query($query1);
echo mysql_error();

AFTER the query itself.
0
 
LVL 4

Accepted Solution

by:
owner66 earned 2000 total points
ID: 36910356
I use this to show mysql errors:

echo '<pre>SQL Error Number =' . mysql_errno() . ": " . mysql_error() . '</pre>';
0
 
LVL 4

Expert Comment

by:owner66
ID: 36917042
Your question was 'How do I alter this to display the error message MySQL reports?', did my response answer your question?
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 36918076
@pda4me, your decision sounds strange even to owner66! Really mysql_errno() function is what you wont? Your question seems to be different and you received three correct answers before the owner66's one, and more detailed about their palce into your code: so I would expected you award points at least splitting them between experts who tried to help you.

You should treat points carefully and take a moment to think how to award them: in the virtual world Experts-Exchange community is, points are like money. Personally, I'm not interested in accumulating hundreds and thousands and million of points, but that 3000 points per month that ensure the access to this wonderful database of knowledge... well they are very precious ;-)

On to the next and good luck with your project.
 
0
 
LVL 4

Expert Comment

by:owner66
ID: 36918525
The difference, marqusG, is that I followed up with the question author.
Also my answer provides more information ie error number and actual error, and is well formatted.
The error number itself is sometimes important in troubleshooting.
I did not say that his decision sounded strange, it was well decided.
0

Featured Post

Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses
Course of the Month14 days, 20 hours left to enroll

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question