So i am posting some strings to my database. I want it to be able to check if it allready exist an id in my database with same name as the new one. In that case it should alert "notvalid". I have also experienced that in some cases it doesn't save the strings at all even though the id is different from the others. Don't know why that happens..
Here is my code
$.ajax({
type : "POST",
url : "saveid.php",
data: {"qid": id, "qtext1": text1, "qtext2": text2, "qtext3": text3, "allCounters": allCounters},
dataType: "json",
success: function(msg2){
if (msg2 = 'notvalid') {
alert(msg2);
}
if (msg2 = 'valid') {
alert(msg2);
}
}
});
<?php
if (isset($_POST['qid']) && isset($_POST['qtext1']) && isset($_POST['qtext2']) && isset($_POST['qtext3']) && isset($_POST['allCounters'])) {
$connection = @mysql_connect('localhost', 'root', '')
or die (mysql_error());
mysql_select_db('test', $connection)
or die (mysql_error());
$id=$_POST['qid'];
$text1=$_POST['qtext1'];
$text2=$_POST['qtext2'];
$text3=$_POST['qtext3'];
$allCounters=$_POST['allCounters'];
$result = mysql_query("SELECT * FROM code WHERE id ='$id' LIMIT 1");
if (mysql_fetch_row($result)) {
echo json_encode('notvalid');
} else {
$query = mysql_query("INSERT INTO code (id, text1, text2, text3, allCounters) VALUES ('$id','$text1','$text2','$text3','$allCounters')");
echo json_encode('valid');
}
}
?>
This is the first time i am working with PHP. I will appreciate if someone could explain why this doesn't work, how to make it work or any other tips. Thanks
if (mysqli_num_rows($result) > 0)MySQLi_instead ofMySQL_my version won't work otherwise. FYI:MySQL_is deprecated. So tryif (mysql_num_rows($result)>0)- and changeif (msg2 = 'notvalid')toif (msg2 == 'notvalid')andif (msg2 = 'valid')toif (msg2 == 'valid')if (!mysqli_query($connection,$result)) { // rest of your code