Solved

PHP - Mysql error handling seems to prevent further mysql queries from running

Posted on 2014-01-06
8
632 Views
Last Modified: 2014-01-11
I have a PHP script which inserts data from a form into a MySQL table

After this it checks to see if a duplicate row error has occurred.  If there is an error the form is redisplayed so the user can change the primary key value.

As below:

$query4 = "INSERT INTO.....";                  
$result4 = @mysql_query($query4); //Run the query
            
if (mysql_errno() == 1062) {  //duplicate entry error
   echo '<font color = \'red\'> Error! A record with this Review date already exists </font>';
}


The problem I'm having is, after the error the form is failing to run MYSQL queries and therefore show the drop down options correctly within the redisplayed form.  

For example, the following query ($queryneed) will not run.

----Form extract-------------------------------------------------------------------------
<tr>
      <TD width="112">
      <font face="Tahoma, Verdana, Arial, Helvetica, Sans Serif" size="2">Level of Support Needed:
      </font></TD>
      <TD><FONT FACE="Tahoma, Verdana, Arial, Helvetica, Sans Serif" SIZE="2" >

<p>';
 
       // Create dropdown Support Need table lookup list
$queryneed = "SELECT level , description FROM pdp_supneed";
$resultneed = @mysql_query($queryneed); // Run the query.

echo '<select name="level">';

while($rowneed = mysql_fetch_array($resultneed, MYSQL_NUM))
{
echo '<option value="'.$rowneed[0].'">'.$rowneed[0].' -> '.$rowneed[1].'</option>';
}

echo '</select>

</p>

</FONT></TD>
</tr>


-------------------------------------------------------------------------------------------

This query runs fine when the form is first loaded prior to submission, but if I submit the form as a test with duplicate data, the error occurs and the form fails to load the drop down list data correctly.

The info I get back from the page says "<b>Warning</b>:  mysql_fetch_array(): supplied argument is not a valid MySQL result resource in <b>C:\clientmon\Inetpub\clientmonitor\pdp\create_review.php</b> "

Why does the query work when the form is first loaded but not after the MySQL_errorno() has occurred?


Any help appreciated.
0
Comment
Question by:EICT
  • 4
  • 2
  • 2
8 Comments
 
LVL 34

Assisted Solution

by:Dan Craciun
Dan Craciun earned 100 total points
ID: 39759075
The first query is an INSERT, the second is a SELECT.

You probably get the error because $resultneed is null.

Try var_dump($resultneed) to check it's content.

HTH,
Dan
0
 

Author Comment

by:EICT
ID: 39759156
Hi Dan,

That's correct before the form is submitted only the SELECT statement is run to populate the form.

After the form is submitted the INSERT statement is run to the form data in the MYSQL table.

In the event of an error the SELECT statement is run again to re-show the form so it can be corrected.

So after the submit, yes you and an INSERT then SELECT (much later in the code).

I used the var dump.

When the SELECT first runs the var_dump result is "resource(6) of type (mysql result)"
when the SELECT runs after the INSERT when the form is submitted I get "bool(false)".

No Idea why though!
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 200 total points
ID: 39759164
There's a lot of work needed here!  Let's start with this statement:

$resultneed = @mysql_query($queryneed);

Remove the @ from the function call.  If the function call issues a message, the @ will suppress the message.  This is Antipractice #5.  You really want to see the messages, so you can correct the conditions that are causing the messages.

Almost all PHP functions return values, and a correctly-written PHP script will test the return values (and take appropriate actions).  The script does not test the return value in $resultneed; it just assumes there is a useful value.  Obviously not a good assumption!  This is Antipractice #23.  The return values from mysql_query() are documented in the online man page, which is required reading for PHP developers.

When you read that page you will find a large, red warning label.  If you're smart, you will want to read this about choosing an API for MySQL.

Some examples of how to test for useful return values and visualize errors are available in this article, that also lays out a roadmap for getting off the obsolete and deprecated MySQL extension.  That's something you will need to do, because PHP is doing away with MySQL.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

The general strategy for running a query and testing for errors goes something like this:
// RUN THE QUERY USING THE STRING IN $sql
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, LOG AND SHOW THE ERROR
if (!$res)
{
    $err
    = "QUERY FAIL: "
    . $sql
    . ' ERRNO: '
    . mysql_errno()
    . ' ERROR: '
    . mysql_error()
    ;
    trigger_error($err, E_USER_ERROR);
}
// IF THE SCRIPT GETS THIS FAR, THE QUERY SUCCEEDED AND YOU CAN USE $res

Open in new window

If you're willing to be tolerant of the "duplicate key" error, you might amend this code to skip the error processing if mysql_errno() == 1062.
0
 

Accepted Solution

by:
EICT earned 0 total points
ID: 39759173
I've just fixed it.

Looking through the code I noticed the mysql_close(); statement within the 'If submitted' clause after the INSERT test.

This was obviously closing the connection to the server before the SELECT run.

Thanks for your help.
0
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 
LVL 34

Expert Comment

by:Dan Craciun
ID: 39759177
LE: Glad you fixed it :)
0
 

Assisted Solution

by:EICT
EICT earned 0 total points
ID: 39759194
Thanks Ray, this is good advice. Didn't realise that PHP was doing away with MYSQL. What's the reason behind this?

I've always written my statements like $result = @mysql_query($query); That's the way I was originally told!

Obviously I have a lot to think about here.

Thanks
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39759493
The reason PHP is removing the MySQL extension is because it's so badly misused and abused.   The article explains some of it.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

Executive summary: PHP code samples, no matter how old or simply awful, wrong and riddled with security holes, never expire!  They just lie around in the dark cesspools of the internet, waiting for unsuspecting searchers to find them.  And PHP, for better or worse, is a language that is designed to be accessible to ordinary folks without a computer science background.  So the threshold for writing PHP code is very, very low.  And that makes it all the more important that you choose your PHP examples carefully.
0
 

Author Closing Comment

by:EICT
ID: 39773116
I've accepted my solution as the best result but given your helpful advise I have given points accordingly.
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Router for PHP reqeusts 12 33
Button Click 11 26
Getting info from database not working 6 17
PHP json decode 9 20
Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Creating and Managing Databases with phpMyAdmin in cPanel.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
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.

759 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now