First things First mysql_* 函数已弃用,并且在最新的 php 版本中不再支持,您应该让 php Manuel 成为您最好的朋友,请使用带有准备好的语句的 mysqli 或 PDO。 p>
如果你还在学习 php,最好开始使用准备好的语句...你可以使用 mysqli Prepared 或 PDO。
选项 1 Mysqli
你的html:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="POST" action="insertform.php">
Topic : <input type="text" name="topic"><br>
Name : <input type="text" name="name"><br>
Attendance : <input type="text" name="attendance"><br>
<button type="submit" name="submit">Submit</button>
</form>
</body>
</html>
然后你的 insertform.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "kevintesting";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['submit'])) {
$topic = $_POST['topic'];
$name = $_POST['name'];
$attendance = $_POST['attendance'];
// prepare and bind
$stmt->$conn->prepare("INSERT INTO testformulario (Topic,Name,Attendance) VALUES (?,?,?)");
$stmt->bind_param("sss", $topic, $name, $attendance);
if ($stmt->execute()) {
echo "New records created successfully";
} else {
echo "No insert";
}
$stmt->close();
$conn->close();
}
?>
准备好的语句让你很容易。
希望这会有所帮助。
编辑:
上面查询中的问号 (?) 是占位符,我们使用它来防止 sql 注入。
bind_param() 函数
这是 SQL 查询的参数,并告诉数据库参数是什么。 “sss”参数列出了参数的数据类型。 s 字符告诉 mysql 参数是一个字符串。告诉mysql期望什么类型的数据,我们将SQL注入的风险降到最低。
注意:当您从外部来源插入任何数据时(如用户输入
从您的情况下的表格中),数据是非常重要的
消毒和验证。始终将用户输入视为来自非常
危险的黑客
带有 PDO 的选项 2
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "kevintesting";
try {
$dbh = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
error_log("Could not connect" . $e->getMessage());
}
if (isset($_POST['submit'])) {
$topic = $_POST['topic'];
$name = $_POST['name'];
$attendance = $_POST['attendance'];
// prepare and bind
try {
$stmt = $dbh->prepare("INSERT INTO testformulario (Topic,Name,Attendance) VALUES(?,?,?)");
if ($stmt->execute(array(
$topic,
$name,
$attendance
))) {
echo "Success";
} else {
echo "Fail "; // then check your error log
}
}
catch (PDOException $e) {
error_log($e->getMessage());
}
}
?>