-2

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

<?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
 } 

?>

谢谢。

4

2 回答 2

4

您运行查询两次。

$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 用于数据库

于 2013-05-01T17:30:38.957 回答
-1

尝试删除此行:

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 语句之外

于 2013-05-01T17:35:29.297 回答