how to insert into mysql using Prepared Statement with php
This question already has an answer here:
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: %sn", 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();
}
?>
This is a very basic example. Many PHP developers today are turning to PDO. Mysqli isn't obsolete, but PDO is much easier, IMHO.
链接地址: http://www.djcxy.com/p/16732.html上一篇: 我是否从mysql注入安全?