Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This is my first time creating a php form and so I've been reading and copying a ton of tutorials, but none really seem to cover everything from start to finish so I'm piecemealing different people's decisions into one file and it isn't really working.

I think I understand what I've been learning so far, I just don't know enough about how to troubleshoot this php and find out where it's going wrong. Here's the HTML:

<section class="content">
  <form method="POST" action="" enctype="multipart/form-data" name="form">
    <p>Please remember, these results are saved into the database and will be shown to other users. So please do not include any identifying or personal information.</p>
    <label>
      <input type="text" id="object" placeholder="Name an object" required="required" />
      <i class="fa fa-wrench"></i>
    </label>
    <label>
      <input type="text" id="location" placeholder="Name a location" required="required" />
      <i class="fa fa-map-marker"></i>
    </label>
    <label>
      <input type="text" id="person" placeholder="Name a person" required="required" />
      <i class="fa fa-user"></i>
    </label>
    <button type="submit">Submit</button>
  </form>
</section>
<section class="result">
  <div class="return"><?php echo $result; ?></div>
  <h2>See how other people have responded.</h2>
  <div class="previous"></div>
</section>

The js:

<script type="text/javascript">
  $(function(){
    $("button").click(function(e){
      e.preventDefault();
      $.post("phptest.php", {$("form").serialize()}, function(res){
        $(".return").html(res);
        $(".content").hide();
        $(".result").show();
      });
    });
  });
</script>

Here is the php:

<?php
  $mysqli = new mysqli('mysite.com', 'myuser', 'mypass', 'mydb');
  if($mysqli->errno) {
    printf("Connection To Database Failed:<br/> %s", $mysqli->error());
    die();
  };
  $query = "INSERT INTO test_table (person, object, location) VALUES ('{$person}', '{$object}', '{$location}')";
  $stmt = $mysqli->stmt_init();
  $stmt->prepare($query);
  $stmt->bind_param('sss', $person, $object, $location);
  $person = $_POST['person'];
  $object = $_POST['object'];
  $location = $_POST['location'];
  $results = $mysqli->query($query);
  $stmt->execute();
  $stmt->close();
  $mysqli->close();
?>
<?php
  $mysqli = new mysqli('mysite.com', 'myuser', 'mypass', 'mydb');
  if($mysqli->errno) {
    printf("Connection To Database Failed:<br/> %s", $mysqli->error());
    die();
  };
  $query = "SELECT person, object, location FROM test_table WHERE person = ?";
  $stmt = $mysqli->stmt_init();
  $stmt->prepare($query);
  $stmt->bind_param('sss', $person, $object, $location);
  $stmt->execute();
  $result = $stmt->get_result();
  while($row = $result->fetch_assoc()) {
    printf('<strong>%s</strong> is a person. <strong>%s</strong> is an object. <strong>%s</strong> is a location.', $row['person'], $row['object'], $row['location']);
  $stmt->close();
  $mysqli->close();
?>

Now I have rewritten this as I understood the tutorials and taken what the tutorials were saying and tried to apply it to my use case, so anything wrong with the above is my own fault and not the case that I'm following bad advice.

GOAL:

  1. Submit an html form for the fields
  2. Add them to the db
  3. Return the results of the submission to the page where <div class="return">
  4. Return the previous 10 results of prior submissions where <div class="previous"> (hence the i<11 part)
share|improve this question

2 Answers 2

up vote 2 down vote accepted

First you must use name attribute in each your input tag. Eg.:

<input type="text" id="location" name="location" placeholder="Name a location" required="required" />

The js code could be like this:

<script type="text/javascript">
  $(function(){
    $("button").click(function(e){
      e.preventDefault();
      $.post("phptest.php", $("form").serialize())
      .done(function(res) {
        $(".return").html(res);
        $(".content").hide();
        $(".result").show();
      });
    });
  });
</script>

And this is for PHP script. The line with comment sign is your first script:

<?php
  $mysqli = new mysqli('mysite.com', 'myuser', 'mypass', 'mydb');
  if($mysqli->errno) {
    printf("Connection To Database Failed:<br/> %s", $mysqli->error());
    die();
  };
  //$query = "INSERT INTO test_table (person, object, location) VALUES ('{$person}', '{$object}', '{$location}')";
  $query = "INSERT INTO test_table (person, object, location) VALUES (?, ?, ?)";
  $stmt = $mysqli->stmt_init();
  $stmt->prepare($query);
  $stmt->bind_param('sss', $person, $object, $location);
  $person = $_POST['person'];
  $object = $_POST['object'];
  $location = $_POST['location'];
  $results = $mysqli->query($query);
  $stmt->execute();
  $stmt->close();
/* No need a new mysqli object, so i block some lines from your script
  $mysqli->close();
?>
<?php
  $mysqli = new mysqli('mysite.com', 'myuser', 'mypass', 'mydb');
  if($mysqli->errno) {
    printf("Connection To Database Failed:<br/> %s", $mysqli->error());
    die();
  };
*/
  $query = "SELECT person, object, location FROM test_table WHERE person = ?";
  $stmt = $mysqli->stmt_init();
  $stmt->prepare($query);
  $stmt->bind_param('s', $person); // The query just need one parameter
  $stmt->execute();
  $result = $stmt->get_result();
  while($row = $result->fetch_assoc()) {
    printf('<strong>%s</strong> is a person. <strong>%s</strong> is an object. <strong>%s</strong> is a location.', $row['person'], $row['object'], $row['location']);
  } // Don't forget to close a statement
  $stmt->close();
  $mysqli->close();
?>

That's all. I have tried it before and everything is worked. Hope this can help you.

share|improve this answer
    
+1 That goes to show you to correct mistakes when you first notice. I've always heard it is costlier to wait until later to fix mistakes and that's what's happened here. I knew I should use name and then said I'll do it later, I'm working on php right now...dumb. –  o_O Mar 2 at 1:40
    
I think you misread my comment. I was saying I was dumb for never fixing my missing name attributes. You were RIGHT to point it out and it was certainly a good catch. –  o_O Mar 2 at 2:42
    
This is still not working. How can I return the error in the jquery so I can see where my problem is? Maybe it is a syntax error or maybe it is a SQL error. Without some kind of message I don't know how I can find out. –  o_O Mar 2 at 4:17
    
Thank you for this. It was very helpful to compare as the problem was simply a missing semi-colon on my end. Very hard to see. It's now writing to the db but not returning the results yet. I will continue to work on and thank you for your help very much. –  o_O Mar 2 at 5:08
    
You're welcome. Glad to hear. Don't hesitate. :-) –  Pieter Pelealu Mar 2 at 5:19

Ok let's look at PHP.

For your bindparam, do this instead:

$query = "INSERT INTO test_table (person, object, location) VALUES ('?', '?', '?')";

Also your while loop isn't closed:

while($row = $result->fetch_assoc()) {
    printf('<strong>%s</strong> is a person. <strong>%s</strong> is an object. <strong>%s</strong> is a location.', $row['person'], $row['object'], $row['location']);
  $stmt->close();
}

Add the } to its end.

Also, you only need $stmt->close();

Might I also suggest you eventually move over to PDO? Believe me it is 100x easier when you learn it :)

share|improve this answer
    
This is still not working. How can I return the error in the jquery so I can see where my problem is? Maybe it is a syntax error or maybe it is a SQL error. Without some kind of message I don't know how I can find out. –  o_O Mar 2 at 4:19
    
use console.log(yourvariablehere); That will paste it in the console, which you can get to in chrome by right clicking and selecting inspect element, then going to "console" –  David G Mar 2 at 14:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.