Solved

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

Posted on 2014-01-06
8
651 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
  • 2
8 Comments
 
LVL 35

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 110

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
Don't Cry: How Liquid Web is Ensuring Security

WannaCry is just the start. Read how Liquid Web is protecting itself and its customers against new threats.

 

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
 
LVL 35

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 110

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

Transaction Monitoring Vs. Real User Monitoring

Synthetic Transaction Monitoring Vs. Real User Monitoring: When To Use Each Approach? In this article, we will discuss two major monitoring approaches: Synthetic Transaction and Real User Monitoring.

Question has a verified solution.

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

3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
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.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to dynamically set the form action using jQuery.

707 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