PHP 在提交时不会将 sql 数据从 发送到数据库


PHP wont send sql data from to database when submitting?

我是PHP的新手,我正在制作一个插入函数,它将html输入插入我的SQL数据库,但是在我提交时什么也没发生,也没有信息输入到数据库中。关于如何获得输入信息以提交到数据库的任何帮助将不胜感激。

<html>
<head>
</head>
<body>
  <div align = "center">

           <form method = "POST" class="basic-grey">
           <h1><i>Insert</i></h1>
              <label>Title  :<input type = "text" name="title"/></label>
              <label>Content  :<input type = "text" name="content"/></label>
              <label>User  :<input type = "text" name="user"/></label>
              <label><input type = "submit" value = "submit"/></label>
           </form> 
           <div style = "font-size:11px; color:#cc0000; margin-top:10px"><?php echo $error ?></div>
           </div>
</html>
<?php
include_once 'db_config.php';
session_start();
if (!(isset($_SESSION['login_user']) && $_SESSION['login_user'] != '')) {
header ("Location: login2.php");
 }

if(isset($_POST["submit"])) {

$title = $_POST['title'];
$content = $_POST['content'];
$user = $_POST['user'];
$sql = "INSERT INTO 'diary' ('ID', 'TITLE', 'CONTENT', 'USER') 
VALUES (NULL, '$title','$content', '$user',)";
if ($conn->query($sql) === TRUE) {
header("location: results.php");
 } else {
 echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();

?>

你的脚本不会工作,因为你没有名为"submit"的任何内容供if(isset($_POST["submit"])) {测试。通过命名提交按钮来解决此问题:

<label><input type="submit" name="submit" value="submit"/></label>

单击现在按钮的名称将出现在$_POST数组中。


另外:session_start()应该紧跟在你打开的PHP标签之后。

您的脚本面临 SQL 注入攻击的风险。了解PDO和MySQLi的预准备语句,并考虑使用PDO,这真的很容易。

您的错误检查将显示您引用了表名和列名,而不是反勾号,并且您有一个额外的逗号。按如下所示更改插入查询:

$sql = "INSERT INTO `diary` (`ID`, `TITLE`, `CONTENT`, `USER`) VALUES (NULL, '$title','$content', '$user')";

您使用了无效的 mysql 语法。您对表名和列名使用了错误的字符串文字 '。你可以使用这个 ' ,或者根本不使用文字。

选项 1 :

$sql = "INSERT INTO `diary` (`ID`, `TITLE`, `CONTENT`, `USER`) VALUES (NULL, '$title','$content', '$user')";

选项 2 :

$sql = "INSERT INTO diary (ID, TITLE, CONTENT, USER) VALUES (NULL, '$title','$content', '$user')";

也许你没有使用"提交"的名称来执行,例如:

<input type="submit" **name="simpan"** value="SIMPAN"/>