可以另一双眼睛检查我的php代码,看看为什么当有人提交东西到表单,它被显示两次


Can another pair of eyes check my php code to see why when someone submits something into the form, it gets displayed twice?

我正在学习如何制作一个显示提交内容的表单。当我提交信息到表单,信息显示两次,我不知道为什么。我的代码可能有很多错误,因为我仍然是一个新手。我仔细检查了每件事,看看为什么它会显示两次,但我似乎找不到问题。

<?php
$mysqli = new mysqli("localhost","root", "", "hits");
if(!$mysqli){
    die('Could not connect: ' . mysqli_connect_error());
}
$db_selected = mysqli_select_db($mysqli, "hits"); 
if(!$db_selected){
    die('can not use' . "hits" . ': ' . mysqli_connect_error());
}
$hit = $_POST['hit'];
$amount = $_POST['amount'];
$category = $_POST['category'];
$result = mysqli_query($mysqli, "INSERT into hit (hit, amount, category) VALUES ('$hit', '$amount', '$category')");
if(!mysqli_query($mysqli, "INSERT into hit (hit, amount, category) VALUES ('$hit', '$amount', '$category')")){
    die('Error: ' . mysql_Error());
}
$data = $mysqli->query("SELECT * FROM hit");
while($row = $data->fetch_assoc()) {
 Print "<tr>"; 
 Print "<th>Hit:</th> <td>".$row['hit'] . "</td> "; 
 Print "<th>Amount:</th> <td>".$row['amount'] . " </td>"; 
 Print "<th>Category:</th> <td>".$row['category'] . "</td></tr> ";
 Print "<br><br/>"; 
Print "</table>";
 // array_sum
 } 
?>

谢谢。

您运行两次查询。

$result = mysqli_query($mysqli, "INSERT into hit (hit, amount, category) VALUES ('$hit', '$amount', '$category')");
if(!mysqli_query($mysqli, "INSERT into hit (hit, amount, category) VALUES ('$hit', '$amount', '$category')")){
    die('Error: ' . mysql_Error());
}

我想你是说:

if( ! $result ){
    die('Error: ' . mysql_Error());
}

我将改变使用PDO数据库,尽管

尝试删除这一行:

while($row = $data->fetch_assoc()) {
 Print "<tr>"; 
 Print "<th>Hit:</th> <td>".$row['hit'] . "</td> "; 
 Print "<th>Amount:</th> <td>".$row['amount'] . " </td>"; 
 Print "<th>Category:</th> <td>".$row['category'] . "</td></tr> ";
 Print "<br><br/>"; 
Print "</table>"; // Remove This
 // array_sum
 } 

放在while语句之外