如何将准备好的语句输入放入数据库

时间:2019-03-18 09:33:21

标签: php mysqli prepared-statement

我正在准备一份准备好的陈述的练习表格。我准备的语句会通过,但我在html表单上的输入却不会。只有Anton和Tanya出现在我的数据库中,但没有出现在我的数据库中。

<?php

$mysqli = new mysqli("127.0.0.1:3307", "root", "", "test");

if (mysqli_connect_error()) { echo mysqli_connect_error(); exit; }

// The (?,?,?) below are parameter markers used for variable binding
$sql = "INSERT INTO people (username, gender, country) VALUES (?,?,?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("sss", $u, $g, $c); // bind variables

$u = 'Anton';
$g = 'm';
$c = 'Sweden';
$stmt->execute(); // execute the prepared statement

$u = 'Tanya';
$g = 'f';
$c = 'Serbia';
$stmt->execute(); // execute the prepared statement again

$stmt->close(); // close the prepared statement
$mysqli->close(); // close the database connection
?>

<!DOCTYPE html>
<html>
<head>
 <title>Form site</title>
</head>
<body>
<form method="post" action="people.php">
Username : <input type="text" name="username"><br><br>
Gender : <input type="gender" name="gender"><br><br>
Country : <input type ="country" name = "Country"><br><br> 


<input type="submit" value="Submit">
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您需要使用$ _POST ['parameter_name']来收集变量。 试试这个代码

<?php

$mysqli = new mysqli("localhost", "root", "", "test");

if (mysqli_connect_error()) { echo mysqli_connect_error(); exit; }

// The (?,?,?) below are parameter markers used for variable binding

if(isset($_POST['submit'])){

$sql = "INSERT INTO people (username, gender, country) VALUES (?,?,?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("sss", $u, $g, $c); // bind variables

$u = $_POST['username'];
$g = $_POST['gender'];
$c = $_POST['country'];
$result=$stmt->execute(); // execute the prepared statement


echo "New records created successfully "; 

$stmt->close(); // close the prepared statement
$mysqli->close(); // close the database connection
}else{

?>

<!DOCTYPE html>
<html>
<head>
 <title>Form site</title>
</head>
<body>
<form method="post" action="people.php">

Username : <input type="text" name="username"><br><br>
Gender : <input type="text" name="gender"><br><br>
Country : <input type ="text" name = "country"><br><br> 


<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>

<?php } ?>