简体   繁体   中英

php form data not being submitted in database correctly

my database name is login and has a table called users three columns:name,id and post. when I hit the submit button, the id is incremented and a new record created but no actual data is created in these fields. please help

 <?php
$servername="localhost";
$username="root";
$password="";
$dbname="login";

$conn=new mysqli($servername,$username,$password,$dbname);
if($conn->connect_error){
    die("connection error:".$conn->connect_error);
}else{
    echo 'connected successfully';
}
#defining varriables
$user_name = isset($_POST['user_name']);
$post = isset($_POST['post']);

#connect this to login details and pick the userrname

$sql="INSERT INTO posts(user_name,post)
VALUES('$user_name','$post')";
if($conn->query($sql)===TRUE){
    echo "your post was published";
}?>

form data

    <form action="" method="post">
    <input type="text" name="user_name"/>
    <input type="text" name="post"/>
    <input type="submit" name="post to cdrone"/>
    </form>

PHP's isset() returns a boolean value. So your $user_name and $post variables are each going to be set to either true or false , rather than the values posted from your form.

Consider setting the values conditionally, depending on the value of isset() .
I prefer using the ternary operator to include some validation:

if (!empty($_POST)) {

  $user_name = !empty(trim($_POST['user_name'])) ? trim($_POST['user_name']) : false;
  $post = !empty(trim($_POST['post'])) ? trim($_POST['post']) : false;

  if (!$user_name) {
    echo "User Name is required.";
  } elseif (!$post) {
    echo "Post is required.";
  } else {
    // insert into database
  }

}

The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM