PHP脚本doesen不在MySQL中插入数据

时间:2018-02-24 08:07:45

标签: php mysql sql-insert

我已经创建了这个脚本,可以将一些数据从PHP插入到MySQL中,但它无法正常工作,我也不知道为什么。

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;
  }

谢谢! 编辑: 这段代码的结果是: enter image description here 即使使用ini_set('display_errors', 'stdout');,它也不会显示错误...

这是MySQL中posts表的结构: enter image description here

2 个答案:

答案 0 :(得分:1)

似乎在整数字段中有换行符。

像这样更改您的查询。 '$post_categ_id'周围的单引号已更改。

$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 我建议您阅读此帖子How can I prevent SQL injection in PHP?,以防止您对SQL注入进行查询。

答案 1 :(得分:-1)

按如下所示更改您的插入查询,使用'{$variable}'代替'$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}')";