Jump to content

Newbie with problems


enkidu72

Recommended Posts

Hello everybody ...
I'm quite new with this and I'm having some problems ...
That's what I'm trying to do :

$query="SELECT id,name,surname FROM autori WHERE surname='$surname_autor' ";
$result=mysql_query($query);
if (mysql_num_rows($result)) {
while($row = mysql_fetch_array( $result )){
$autorID=$row['id'];
if (($row['name']===$name_autor ) &&  ($row['surname']===$surname_autor )){
echo "Existing record with ID :$autorID <br>";
break ;
} else {
mysql_query("INSERT INTO autors(name,surname) VALUES
('$name_autor','$surname_autor')") or die(mysql_error());
$autorID=mysql_insert_id();
echo "Autor ID is :$autorID <br>";

}
}

}else{
mysql_query("INSERT INTO autors(name,surname) VALUES
('$name_autor','$surname_autor')") or die(mysql_error());
$autorID=mysql_insert_id();
echo "Autor ID is :$autorID <br>";
}


What i get is that if autor doesn't exist , I have a new record inserted .
If exists , it is inserted again twice !

Someone can help here ?
I'm sure it's a very silly thing but I'm trying to solve it since 2 days with no result :'-(


thx in advance

David



Link to comment
https://forums.phpfreaks.com/topic/20610-newbie-with-problems/
Share on other sites

I have a question, if you already have $surname_autor and $name_autor, why not just include them in the original sql statement and only add them if neither are a match?

[code]
$query="SELECT id, name, surname FROM autors WHERE name = '$name_autor' AND surname='$surname_autor'";
$result=mysql_query($query);
if (mysql_num_rows($result)) {
  $autorID=$row['id'];
  echo "Existing record with ID :$autorID
}
else {
  mysql_query("INSERT INTO autors (name, surname) VALUES ('$name_autor', '$surname_autor')") or die(mysql_error());
  $autorID=mysql_insert_id();
  echo "Autor ID is :$autorID
}
[/code]


Regards
Rich
Link to comment
https://forums.phpfreaks.com/topic/20610-newbie-with-problems/#findComment-90999
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.