<html>
<?php
$servername = "localhost";
$username = "root";
$password = "4242";
$dbname = "myDB";
$table = "exercises";
$date = date("Y,m,d");
$conn = new mysqli($servername,$username,$password, $dbname);
if($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "insert into $table (name, exercise, number,date) values ($_POST['name'],$_POST['exercise'],$_POST['number'],$date)";
?>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
The number you picked was <?php echo $_POST["number"]; ?> on <?php echo date("Y/m/d") ?><br>
</body>
</html>
问题似乎是声明$ sql。如果我宣布注释掉这样的行
$sql = "insert into $table (name, exercise, number,date) values "//($_POST['name'],$_POST['exercise'],$_POST['number'],$date)";
工作正常。我无法弄清楚为什么这样做。我将此作为一个学习项目。
答案 0 :(得分:0)
$sql
中有几个问题。
首先,您需要在VALUES
子句中围绕字符串引用。其次,您需要将{ }
放在数组引用周围,以便在索引中使用引号。
$sql = "insert into $table (name, exercise, number,date) values ('{$_POST['name']}','{$_POST['exercise']}',{$_POST['number']},'$date')";
但是,mysqli
支持参数化查询,最好使用它来防止SQL注入。
$sql = "insert into $table (name, exercise, number,date) values (?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssis", $_POST['name'], $_POST['exercise'], $_POST['number'], $date);
$stmt->execute();
答案 1 :(得分:0)
也许对PHP字符串中的变量的连接和使用的简单理解足以回答您的问题。
<强>查询:强>
$sql = "INSERT INTO $table (name, exercise, number,date)
VALUES (
'".$_POST['name']."'
,'".$_POST['exercise']."'
,'".$_POST['number']."'
,'$date')";
如果您想使用mysqli
方式进行查询,只需通过bind_param
将值绑定到变量