如何使用PHP准备好的语句插入MySQL
问题描述:
我只是在学习数据库,我希望能够存储用户输入.如何使用PHP获取表单数据并将其保存到数据库的基本示例是什么?
I am just learning about databases and I want to be able to store user inputs. What would be a basic example on how to get form data and save it to a database using PHP?
还要使表单免受 SQL攻击的保护.
Also making the form secure from SQL attacks.
答
文件 sample.html
<form action="sample.php" method="POST">
<input name="sample" type="text">
<input name="submit" type="submit" value="Submit">
</form>
文件 sample.php
<?php
if (isset($_POST['submit'])) {
$mysqli = new mysqli('localhost', 'user', 'password', 'mysampledb');
/* Check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO SampleTable VALUES (?)");
$stmt->bind_param('s', $sample); // Bind $sample to the parameter
$sample = isset($_POST['sample'])
? $_POST['sample']
: '';
/* Execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* Close statement and connection */
$stmt->close();
/* Close connection */
$mysqli->close();
}
?>
这是一个非常基本的示例.今天,许多PHP开发人员都转向 PDO简介. Mysqli并不是过时的,但是PDO容易得多,恕我直言.
This is a very basic example. Many PHP developers today are turning to PDO. Mysqli isn’t obsolete, but PDO is much easier, IMHO.