-1

I was able to succsess fully write to a database. The problem was the same information kept getting written so I created a json file that stored the id of each object and wrote some php to check if the id was already in the file and if not it would write the whole object to a database and just write the id to the json file. The checking of the json object and writing to the json file work but not the writing to my database. Any help would be much appreciated

Here is the code. From the beginning of the if statement to fclose is the code i added to perform the check that now stops me from writing to a databse.

<?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
    Why are you storing the id in a separate file instead of the much more efficient database...?! – deceze Mar 30 '14 at 16:50
  • This seems to do what you want to do: http://stackoverflow.com/questions/3164505/mysql-insert-record-if-not-exists-in-table - Do not use files for this. If two requests happen within the time the first request requires to read and write the file, you corrupt the file... – Sumurai8 Mar 30 '14 at 16:59
  • Also: Your site seems vulnerable to sql injection. – Sumurai8 Mar 30 '14 at 17:01

1 Answers1

2

Just declare the ID row as UNIQUE in MySQL.

ALTER IGNORE TABLE tweet ADD UNIQUE (tweetid);
Johann Bauer
  • 2,337
  • 22
  • 40