我是编码的初学者,想要在html中创建一个与MySQL连接的表单。之后,我希望能够自动填写表格。我的意思是,例如,如果我输入代码,我希望用户名和连接到MySQL代码的密码自动填写表单。我的HTML代码和PHP代码在单独的文件中。现在我使用:
<FORM name="form" method="post" action="code.php">
将php文件与html文件连接。我使用提交按钮将数据发送到MySQL。我已经考虑过一个按钮来填充数据,但尚未对其进行测试。我还想出了如何从MySQL获取数据:
<?php
//init
$server = 'localhost';
$user = 'root';
$db = 'database';
$con = mysqli_connect($server, $user);
if(!$con) {
die('Could not connect: ' . mysqli_error());
}
mysqli_select_db($con, $db);
$query = "SELECT * FROM TEST";
$retval = mysqli_query($con, $query);
if(!retval) {
echo ' Error: Data input failed!' . mysqli_error($con);
}
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
echo "User : {$row['Username']} <br> ".
"Code : {$row['Code']} <br> ".
"Password : {$row['Password']} <br> ";
}
mysqli_close($con);
?>
但是,我不知道如何将获取的数据连接到html表单。如果您有任何想法,请随时与我分享。
--- CODE.PHP ---
<?php
//init
$server= 'localhost';
$user = 'root';
$db = 'database';
//input
$username = $_POST['username'];
$code = $_POST['code'];
$password = $_POST['password'];
$con = mysqli_connect($server, $user);
if(!$con) {
echo 'No connection!';
}
if(!mysqli_select_db($con, $db)) {
echo ' No database!';
}
$query = "INSERT INTO TEST (Username, Code, Password) VALUES ('$username', '$code', '$password')";
if(!mysqli_query($con, $query)) {
echo ' Error: Data input failed! ' . mysqli_error($con);
} else {
echo ' Data input successful!';
}
?>
答案 0 :(得分:0)
您可以在用于从数据库中获取的while循环中回显表单及其变量
修改强>
<?php
....
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
//echo "User : {$row['Username']} <br> ".
//"Code : {$row['Code']} <br> ".
//"Password : {$row['Password']} <br> ";
//Probably better this way
$name = $row['Username'];
$code = $row['code'];
$password = $row['password'];
echo '<form action="" method="post">
<input type="text" name="yourname" value="'.$name.'"<br>
<input type="text" name="yourname" value="'.$code.'"<br>
<input type="text" name="yourname" value="'.$password.'"<br>
</form>';
}
....
?>
如果您尝试访问其他文件中的每个变量,请将其存储在表单文件中的$_SESSION
和session_start()
中。这取决于您的网站工作流程。
<?php
....
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
//echo "User : {$row['Username']} <br> ".
//"Code : {$row['Code']} <br> ".
//"Password : {$row['Password']} <br> ";
//Probably better this way
$name = $row['Username'];
$code = $row['code'];
$password = $row['password'];
$_SESSION['password'] = $password;
$_SESSION['code'] = $code;
$_SESSION['Username'] = $Username;
}
....
?>
您的表单文件
<?php
//Start session at the top of page
session_start();
$password = $_SESSION['password'];
$code = $_SESSION['code'];
$Username = $_SESSION['Username'];
echo '<form action="" method="post">
<input type="text" name="yourname" value="'.$Username.'"<br>
<input type="text" name="yourname" value="'.$code.'"<br>
<input type="text" name="yourname" value="'.$password.'"<br>
</form>';
?>