2013-05-01 29 views
-2

我正在學習如何製作一個顯示提交內容的表單。當我向表單提交信息時,信息顯示兩次,我不知道爲什麼。我的代碼可能有很多錯誤,因爲我仍然是一個noob這個。我仔細檢查了一切,看看它爲什麼顯示兩次,我似乎無法找到問題。另一雙眼睛可以檢查我的php代碼,看看爲什麼當某人向表單中提交了某些內容時,它會顯示兩次?

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

?> 

謝謝。

+0

問計一雙眼睛外面是絕對是一個「太本地化問題」的情況。無論如何,程序員應該運行代碼,而不是*監視它。 – 2013-05-01 17:30:40

+1

您正在執行兩次INSERT查詢...而且您的代碼也非常脆弱,永遠不會將從遠程接收的值插入數據庫,而無需檢查/清理/清理! – fvu 2013-05-01 17:30:49

+0

你插入了兩次,所以它正在顯示兩次 – Afsar 2013-05-01 17:30:53

回答

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 for databases though

+0

它沒有運行兩次!嗨只是定義變量不執行它 – Memolition 2013-05-01 17:33:24

+3

@Memolition真的嗎? – 2013-05-01 17:34:39

+0

從[手冊](http://php.net/manual/en/mysqli.query.php)的@Memolition:mysqli_query - **對數據庫執行**查詢 - 強調我的。 – fvu 2013-05-01 17:35:11

-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語句

+0

感謝您的回覆。我實際上首先將它放在支架之外,然後放在裏面,因爲我認爲這是最初的問題。它不是,但我會把它放回外面。 – lin 2013-05-01 17:52:40

相關問題