alias51
alias51

Reputation: 8648

How to insert value into MySQL table with PHP

I have a table [user_id, name] that is prepopulated with a list of user_IDs. I want to create a form to allow a user to register a name against their user_id.

Here's the basic HTML form:

    <form action="" id="contact-form" class="form-horizontal" method="post">
          <label class="control-label" for="inputName">Enter Name</label>
          <input type="text" class="form-control  input-lge" name="inputName" id="inputName">       
            <input type="hidden"  class="form-control" id="hidUid" name="hidUid" value="<?php echo $reg_user_id?>">
<input type="submit" id="sub_button" class="btn btn-default btn-lg" value="Save"/>
</form>

Note the $reg_user_id is the user_id variable set by a session.

Here is my start at the PHP:

if(isset($_POST['hidUid']) && isset($_POST['inputName'])){
  $inputName=$_POST['inputName'];
  $inputUid=$_POST['hidUid'];
  if ($stmtint = $mysqli->prepare("SELECT user_email FROM users WHERE user_ID=?")) {
   $stmtint->bind_param("s", $inputUid);
   $stmtint->execute();
   $stmtint->bind_result($user_email);
   $stmtint->fetch();
   $stmtint->close();
   if($user_email != "" && $inputName !=""){
    $user_email="";
    if ($stmtint = $mysqli->prepare("UPDATE users SET name=? where user_ID=?")) {
     $stmtint->bind_param("ss", $inputName,$inputUid);
     $stmtint->execute();
     $stmtint->close();        

      echo "User saved successfully";
      exit;
    }
  }
  else{
    echo "Please enter correct Name and password";
    exit;
  }

}
}

My problem is the form submits successfully, but the database doesn't update. I have no errors in either the PHP output or the console log. Any ideas?

Upvotes: 1

Views: 237

Answers (1)

Maverick
Maverick

Reputation: 945

If you want to see the error try this.

if(isset($_POST['hidUid']) && isset($_POST['inputName'])){

 $inputName = $_POST['inputName'];
 $inputUid = $_POST['hidUid'];

 if ($stmtint = $mysqli->prepare("SELECT user_email FROM users WHERE user_ID = ?")) {

   $stmtint->bind_param("s", $inputUid);

   if ($stmtint->execute()) {
     $stmtint->bind_result($user_email);
     $stmtint->fetch();
     $stmtint->close();
   }else{
     die("Error Message:".$mysqli->error);
   }

   if ($user_email != "" && $inputName != "") {

     $user_email="";

     if ($stmtint = $mysqli->prepare("UPDATE users SET name = ? where user_ID = ?")) {

       $stmtint->bind_param("ss", $inputName,$inputUid);

       if ($stmtint->execute()) {
         $stmtint->close();
         echo "User saved successfully";           
       }else{
         die("Error Message:".$mysqli->error);
       }

       exit;
     }

   }else{
   echo "Please enter correct Name and password";
   exit;
   }
 }
}

Upvotes: 1

Related Questions