1

i am creating a simple form comment that will allow user to send a comment and inserti into the database using php mysql jquery for no refreshing in the page all work fine but the problem is : that when i write i comment the mysql database take 4 lines and fill the same data in it can anyone help me with error??

my_db.sql

--
-- Database: `my_db`
--

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

--
-- Table structure for table `comments`
--

CREATE TABLE IF NOT EXISTS `comments` (
  `id` tinyint(4) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `email` varchar(70) NOT NULL,
  `comments` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `comments`
--

INSERT INTO `comments` (`id`, `name`, `email`, `comments`) VALUES
(1, 'test', '[email protected]', 'testcomments'),
(2, 'test', '[email protected]', 'testcomments'),
(3, 'test', '[email protected]', 'testcomments'),
(4, 'test', '[email protected]', 'testcomments');

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

index.php // where the form and the function of jquery

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>feedback page</title>
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel ="stylesheet" href = "css/default.css" />

<script type = "text/javascript">

$(function(){

   $('#submit').click(function(){
     $('#container').append('<img src = "img/loading.gif" alt="Currently loading" id = "loading" />');

         var name = $('#name').val();
         var email = $('#email').val();
         var comments = $('#comments').val();


         $.ajax({

            url: 'submit_to_db.php',
            type: 'POST',
            data: 'name =' + name + '&email=' + email + '&comments=' + comments,

            success: function(result){
                 $('#response').remove();
                 $('#container').append('<p id = "response">' + result + '</p>');
                 $('#loading').fadeOut(500, function(){
                     $(this).remove();
                 });

            }

         });         

        return false;

   });


});

</script>




</head>

<body>
   <form action = "submit_to_db.php" method = "post">
   <div id = "container">
      <label for = "name">Name</label>
      <input type = "text" name = "name" id = "name" />

      <label for = "email">Email address</label>
      <input type = "text" name = "email" id = "email" />

      <label for = "comments">Comments</label>
      <textarea rows = "5"cols = "35" name = "comments" id = "comments"></textarea>
      <br />

      <input type = "submit" name = "submit" id = "submit" value = "send feedBack" />
    </div>
   </form>



   </div>
</body>
</html>

submit_to_db.php

<?php
  $conn = new mysqli('localhost', 'root', 'root', 'my_db');
  $query = "INSERT into comments(name, email, comments) VALUES(?, ?, ?)";

  $stmt = $conn->stmt_init();
  if($stmt->prepare($query)){

     $stmt->bind_param('sss', $_POST['name'], $_POST['email'], $_POST['comments']);
     $stmt->execute();

  }

  if($stmt){

  echo "thank you .we will be in touch soon";
  }
  else{
   echo "there was an error. try again later.";
   }  


?>
13
  • Please reformat your question so its not in the title. Im not sure what your asking. Commented Mar 13, 2013 at 15:44
  • Do you have Firebug or anything installed? If so you can you see if it only submitting once or if the ajax is submitting 4 times for some reason. Commented Mar 13, 2013 at 15:46
  • the problem is that if you look to the my_db.sql you will find 4 rows that are fill in the same data but in fact this must fill one row and not 4 did you understand my problem ?? i did not know how to ask the question in a good way hope that help and thank you Commented Mar 13, 2013 at 15:46
  • Is my_db.sql a dump of the current database or the sql you used to create the table? Commented Mar 13, 2013 at 15:49
  • @ Pitchinnate yes i have firebug and when i go to the phpmyAdmin it show me this error CSP WARN: allow directive is deprecated, use the equivalent default-source directive instead Commented Mar 13, 2013 at 15:59

1 Answer 1

1

I actually took your scripts, loaded them onto my server, created the database table, and tested the script.

Only one row is being inserted per submission.

Your script is working correctly.

However, there is a flaw in your testing procedure.

I also checked the Firebug console and the AJAX call is working as expected.

Unless you have other diagnostics, I don't think I can help you any further.

Bug Alert
There is a bug in your code which will cause you immense grief in your life in the years ahead...

if($stmt){
   echo "thank you .we will be in touch soon";
}
else{
    echo "there was an error. try again later.";
}

This if statement will always evaluate to true since the query is executed (unless of course, MySQL is not running).

What you intended is to see if the insert was successful, and for that, you need to check:

if($stmt->affected_rows){...}

$stmt->affected_rows will return -1 upon failure or +1 on success.

Debugging Strategies
(1) Add an extra field in your with a timestamp so that you can see when the records are inserted. This will give you more insight into what is going in.

(2) Empty your table and try your code again. You may think you are getting multiple inserts but it could also be that you hit the submit button 4 times.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.