简体   繁体   中英

PHP script doesen't insert data in MySQL

I've created this script to insert some data from PHP to MySQL, but it doesen't work, and I don't know why.

if (isset($_SESSION['userSession'])!="") {
  $session_created=1;
  $session_query = "SELECT * FROM users WHERE user_id=".$_SESSION['userSession'];
  $session_query_result = $DBcon->query($session_query);
  $user_row=$session_query_result->fetch_array();
}
  if(isset($_POST['create_post_button'])){
    $post_name = $DBcon->real_escape_string(strip_tags($_POST['post_title']));
    $post_content = $DBcon->real_escape_string(strip_tags($_POST['post_content']));
    date_default_timezone_set('Europe/Athens');
    $post_date=date("Y-m-d h:i:sa");
    $post_categ_id = $DBcon->real_escape_string(strip_tags($_POST['post_category']));
    $post_creator = $user_row['user_name'];
    $pass_flag=0;
    $error_msg_cp = "Posted!";
      $create_post_query = "INSERT INTO posts(post_name,post_content,post_date,
        post_categ_id,post_user_name) VALUES ('$post_name','$post_content','$post_date','
        $post_categ_id','$post_creator')";
        echo "<br><br><br><br>".$create_post_query;
        if($DBcon->query($create_post_query)){
          $error_msg_cp="Error, pug!";
        }
        echo $error_msg_cp;
  }

Thank you! Edit: The result of this code is: 在此处输入图片说明 Even with ini_set('display_errors', 'stdout'); it doesen't display the error...

This is the structure of the posts table in MySQL: 在此处输入图片说明

Seems to have a newline in your integer field.

Change your query like this. Single quote around '$post_categ_id' has changed.

$create_post_query = "INSERT INTO posts(post_name,post_content,post_date,
  post_categ_id,post_user_name)
  VALUES ('$post_name','$post_content','$post_date',
          '$post_categ_id','$post_creator')";
  echo "<br><br><br><br>".$create_post_query;
  if (!$DBcon->query($create_post_query)){
      $error_msg_cp="Error, pug!";
  }

NB I suggest you to read this post How can I prevent SQL injection in PHP? to prevent your queries against SQL injections.

Change your insert query as follows, use '{$variable}' instead of '$variabe'

$create_post_query = "INSERT INTO posts(post_name,post_content,post_date,
        post_categ_id,post_user_name) VALUES ('{$post_name}','{$post_content}','{$post_date}','
        {$post_categ_id}','{$post_creator}')";

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