如何使用带有PHP的预准备语句插入MySQL
2022-08-30 12:04:47
###File样本.html
<form action="sample.php" method="POST">
<input name="sample" type="text">
<input name="submit" type="submit" value="Submit">
</form>
###File样本.php
<?php
if (isset($_POST['submit'])) {
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'user', 'password', 'mysampledb');
$stmt = $mysqli->prepare("INSERT INTO SampleTable VALUES (?)");
$stmt->bind_param('s', $sample); // Bind $sample to the parameter
$sample = $_POST['sample'] ?? '';
/* Execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
}
这是一个非常基本的例子。如今,许多PHP开发人员正在转向PDO。Mysqli并没有过时,但PDO要容易得多,恕我直言。