-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')");
}
?>
为什么你将id存储在一个单独的文件中,而不是更高效的数据库......?! – deceze
这似乎是做你想做的事情:http://stackoverflow.com/questions/3164505/mysql-insert-record-if-not-exists-in-table - 不要使用此文件。如果两个请求在第一个请求需要读取和写入文件的时间内发生,则会破坏文件... – Sumurai8
另请参见:您的网站似乎易受sql注入的影响。 – Sumurai8