我正在尝试使用 html 和 php 制作一个表单来更新 mysql 数据库。数据库更新(自动增量)键,但不会将任何字符串添加到值中。我搜索过有类似问题的人,但因为他们的代码与我的不同,我无法理解它(我是 php 和 mysql 的菜鸟)我认为我的问题在于我使用 html 获取值的方式,但我可能是错误
<form action=submitform.php method=GET>
Name:<input type="text" name="cuName" size=20 maxlength=20><br>
Password:<input type="password" name="password" size=20 maxlength=45><br>
Account:<input type="text" name="account" size=20 maxlength=45><br>
Phone:<input type="tel" name="phone" size=10 maxlength=10><br>
Email:<input type="text" name="email" size=20 maxlength=45><br>
<input type=submit>
</form>
我的 php 是
<?php
mysql_connect(localhost, myUsername, "myPassword");
mysql_select_db(myDatabaseName);
mysql_query("INSERT INTO Customer (cuName, password,
account, phone, email)
Values('$cuName', '$password', '$account',
'$phone', '$email')");
echo $cuName ." thank you for reserving!";
print ($cuName);
?>
提前感谢您的帮助
最佳答案
您的代码依赖于 REGISTER_GLOBALS
来打开;出于安全原因,它通常被关闭。
您应该将 $cuName
替换为 $_GET['cuName']
以获取从表单发送的值。
此外,您应该转义任何进入数据库的值,否则您可能会面临 SQL 注入(inject)漏洞。
针对这两种情况清理代码,结果如下:
<?php
if (!mysql_connect(localhost, myUsername, "myPassword")) {
print 'There was an error connecting to the database'.mysql_error();
exit();
}
if (!mysql_select_db(myDatabaseName)) {
print 'Could not select db. The error was: '.mysql_error();
exit();
}
$query = "INSERT INTO Customer (`cuName`, `password`, `account`,`phone`,`email`)";
$query .= "VALUES (";
$query .= "'".mysql_real_escape_string($_GET['cuName'])."','";
$query .= mysql_real_escape_string($_GET['password'])."','";
$query .= mysql_real_escape_string($_GET['phone'])."','";
$query .= mysql_real_escape_string($_GET['email'])."'";
if (!mysql_query($query)) {
print 'There was an error inserting '.$query.'. Error was '.mysql_error();
} else {
echo $_GET['cuName']." thank you for reserving!";
}
print $_GET['cuName'];
?>
我还添加了一些错误检查。您应该始终检查依赖于外部系统(例如数据库)的函数的结果,因为您永远不知道数据库的状态是什么(它可能已关闭、无法工作等),因此您应该始终检查并打印任何错误消息.
关于php - 无法使用 html 和 php 更新 mysql 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11855249/