2014-03-30 25 views
-1

我能夠完全寫入數據庫。問題是相同的信息不斷寫入,所以我創建了一個json文件,存儲每個對象的id,並寫了一些php來檢查id是否已經在文件中,如果不是,它會將整個對象寫入數據庫,將id寫入json文件。檢查json對象並寫入json文件可行,但不能寫入我的數據庫。任何幫助將不勝感激如果這種說法阻止我寫入數據庫

這是代碼。從if語句開始到fclose是我添加的代碼執行檢查,現在阻止我寫入數據庫。

<?php 

$host="xxxxxxxxxxxx"; // Host name 
$username="xxxxxxxxxxxx"; // Mysql username 
$password="xxxxxxxxxxxxxx"; // Mysql password 
$db_name="xxxxxxxxxxxxx"; // Database name 


$name= $_POST['postname']; 
$user= $_POST['postuser']; 
$status= $_POST['poststatus']; 
$id= $_POST['postid']; 
$img= $_POST['postimg']; 
//$id= $_POST['postid']; 

//file_put_contents("index.json", $id, FILE_APPEND); 
$list = file_get_contents('index.json'); 
$json = json_decode($list, true); 

if (in_array($id, $json)) { 
    echo "already exists"; 
} else{ 

array_push($json, $id); 
$file ="index.json"; 
$fh = fopen($file, 'w') or die("can't open file"); 
fwrite($fh, json_encode($json)); 
fclose($fh);  


// Connect to server and select database. 
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB"); 

$db_insert = mysql_query("INSERT INTO tweet(name, user, status, Img, tweetid) VALUES ('$name', '$user', '$status', '$img', '$id')"); 

} 

?> 
+1

爲什麼你將id存儲在一個單獨的文件中,而不是更高效的數據庫......?! – deceze

+0

這似乎是做你想做的事情:http://stackoverflow.com/questions/3164505/mysql-insert-record-if-not-exists-in-table - 不要使用此文件。如果兩個請求在第一個請求需要讀取和寫入文件的時間內發生,則會破壞文件... – Sumurai8

+0

另請參見:您的網站似乎易受sql注入的影響。 – Sumurai8

回答

2

只需在MySQL中聲明ID行爲UNIQUE即可。

ALTER IGNORE TABLE tweet ADD UNIQUE (tweetid); 
相關問題