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

问题描述 投票:-1回答:1

我正在准备一份准备好的陈述的练习表。我准备好的陈述经过但我对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>
php mysqli prepared-statement
1个回答
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 } ?>
© www.soinside.com 2019 - 2024. All rights reserved.