我测试了您的代码,发现您的提交按钮是问题之一,包括不正确地放置分号:
$query = "INSERT INTO scoreboard (name,percent) VALUES ('$getname','$percentage');"
应该读为:
$query = "INSERT INTO scoreboard (name,percent) VALUES ('$getname','$percentage')";
使用以下表格和 PHP 测试
<form method="post" action="">
<center>
<font color="green">Your name Max length is 15</font>
<input type="text" name="username" maxlength="15">
<input type="submit" name="submit" value="Submit">
</center>
</form>
<?php
if (isset($_POST['username']))
{
$link = mysqli_connect("myhost","myusername","mypw","mydatabase") or die("Error " . mysqli_error($link));
// $getname = $_POST['username'];
$getname = mysqli_real_escape_string($link,$_POST['username']);
$percentage = "10";
$query = ("INSERT INTO scoreboard (name,percent) VALUES ('$getname',$percentage)");
$result = mysqli_query($link, $query);
if(!$result){
printf("Error message: %s", mysqli_error($link));
}
else {
echo "Data properly inserted with the value of <b>$getname</b> and <b>$percentage</b>";
}
}
?>
注意:您最好使用下面的代码来检查该字段是否为空。否则,在没有任何内容的情况下单击提交按钮,将在 DB 中生成一个带有空白名称字段的条目。
if (empty($_POST['username'])) {
die("<div align='center'>Enter your name</div>");
}
else
{
// rest of code
另外,正如 Hanky 웃 Panky 所说,您应该像我的工作示例中那样清理变量:
$getname = mysqli_real_escape_string($link,$_POST['username']);
这是一个更安全(参数化)的方法,取自SO here的示例
快速说明:如果您要使用$percentage = 10;
而不是$percentage = "10";
那么你将需要使用$stmt->bind_param("si", $unsafe_variable,$percentage);
,否则你的百分比将被视为一个字符串,而不是一个整数,并且将被抛出一个错误。s
是为了string
和i
是为了integer
。
<form method="post" action="">
<center>
<font color="green">Your name Max length is 15</font>
<input type="text" name="username" maxlength="15">
<input type="submit" name="submit" value="Submit">
</center>
</form>
<?php
if (empty($_POST['username'])) {
die("<div align='center'>Enter your name</div>");
}
else
{
$mysqli = new mysqli("myhost","myusername","mypw","mydatabase");
// Check that connection was successful.
if($mysqli->connect_errno > 0) {
die('Connection failed [' . $mysqli->connect_error . ']');
}
$percentage = "10";
$unsafe_variable = $_POST["username"];
$stmt = $mysqli->prepare("INSERT INTO scoreboard (name,percent) VALUES (?,?)");
// TODO check that $stmt creation succeeded
// "s" means the database expects a string
$stmt->bind_param("ss", $unsafe_variable,$percentage);
$stmt->execute();
$stmt->close();
$mysqli->close();
echo "<div align='center'>Data written to DB</div>";
}
?>