1

I have a PHP script that collects form data and inserts some of that data into a MySQL database. I just noticed that some inserts/records were NOT, or never created in the database. I would like to write a retry routine that if the insert fails to retry 3 times and then error out to the user.

Just so you can see my code for the DB and the insert so you can see that I am NOT nuts...

mysql_connect($hostname,$username, $password) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());

Here is my insert code:

$query = "INSERT INTO contacts VALUES      ('','$name','$address','$city','$state','$zip','$phone','$email_address','$arrive','$depart','$room','$found','$promocode','$message','$datetimestamp','$ip')";
mysql_query($query);
mysql_close();

I started out with an IF statement then into a loop but got lost.

@Jay:

So something like this:

$conn = new mysqli($hostname, $username, $password, $dbname);
       // check connection
       if (mysqli_connect_errno())
       {
          exit('Connect failed: '. mysqli_connect_error());
       }

       $query = "INSERT INTO contacts VALUES ('','$name','$address','$city','$state','$zip','$phone','$email_address','$arrive','$depart','$room','$found','$promocode','$message','$datetimestamp','$ip')";
       // Performs the $query on the server to insert the values
       if ($conn->query($query) === TRUE) {
       //echo 'users entry saved successfully';
       }
       else {
         echo 'Error: '. $conn->error;
       }
       $conn->close();

I am already checking for injection before the insert query

Dave Nugent
  • 351
  • 5
  • 10
  • 5
    Instead of retrying, you should make sure the data is safe to insert and does not contain `'` characters for example. A prepared statement in PDO or mysqli would solve that automatically. – jeroen Jan 08 '15 at 16:28
  • Please, [don't use `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://us1.php.net/pdo) or [MySQLi](http://us1.php.net/mysqli). [Prevent SQL Injection!](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Jay Blanchard Jan 08 '15 at 16:30
  • @Jay: so something like this should work – Dave Nugent Jan 08 '15 at 17:03

1 Answers1

-1

Your query is perfect, make sure that number of parameter you are passing in sql query is same as number of column in database table & parameter value in sql is same order of database table column order

jay.jivani
  • 1,560
  • 1
  • 16
  • 33