PHP使用mysqli将包含时间和日期的数据插入MySQL

时间:2016-06-07 08:11:22

标签: php mysqli

以下PHP代码有什么问题?它始终显示无法连接到数据库。

require "init.php";

$nottxt = $_POST["nottxt"];
$date = date("Y-m-d");
$time = date("H:i:s");
$sql = "INSERT INTO notice (NOTICE_DETAIL, TIME, DATE) VALUES ('$nottxt', '$time', '$date')";
if (!mysqli_query($con, $sql)) {
    echo "Unable to save the data to the database";
}

4 个答案:

答案 0 :(得分:0)

  

此代码有什么问题?

它不会将参数转义为查询,因此,例如,当$_POST['nottxt']包含撇号时,您可以轻松地中断查询。了解how to prevent SQL injection in PHP

另外,正如@Daniel Dudas已经指出的那样,如果您的错误消息是“无法连接到数据库”,那么错误的原因不在您粘贴的代码中,而是在init.php某处。首先检查数据库主机,用户名和密码。

答案 1 :(得分:-1)

这是经过测试的代码。您可以使用此代码:

<?php
$connection = mysqli_connect("localhost", "root", "","db_name")or die("cannot connect....");

echo $nottxt=$_POST['nottxt'];
echo $date=date("Y-m-d");
echo $time=date("H:i:s");
$sql = "INSERT INTO `notice`(notice_detail,time,date) VALUES('$nottxt','$time','$date')";
$result=mysqli_query($connection,$sql);
if($result)
{
    echo "inserted successfully";
}

?>

答案 2 :(得分:-2)

            <?php
            $connection = mysqli_connect("localhost", "root", "","database_name");
            $nottxt=$_REQUEST['nottxt'];
            $date=date("Y-m-d");
            $time=date("H:i:s");
            $sqls = "INSERT INTO `notice`(notice_detail, time, date) VALUES('".$nottxt."','$time','$date')";
            $result=mysqli_query($connection,$sqls);
            if($result)
            {
                echo "inserted successfully";
            }

            ?>
please use this code...

答案 3 :(得分:-4)

试试这个....

var output = data.reduce(function(prev, cur) {
  if (!prev[cur.topic]) prev[cur.topic] = [];
  prev[cur.topic].push(cur);
  return prev;
}, {});