Hi guys,

Iam trying to make some code to check if author of the book is already exist on its authors table or not

so if he already exist : get his id number
if not exist : insert it to authors table then get its id number

i try something like this but its not work

$checkauthor = mysql_query("SELECT COUNT(*) FROM authors WHERE name='$author'")or sqlerr(__FILE__, __LINE__);
$resulto = mysql_fetch_row($checkauthor);
$result = $resulto['0'];
if($result >0)
  {
  $authorid=$result;
  }
else
  {
    mysql_query("INSERT INTO authors (name) VALUES ($author)");
    
  $newauthorp= mysql_query("SELECT id FROM authors WHERE name=".sqlesc($artrist)." LIMIT 1") or sqlerr(__FILE__, __LINE__);
  $newauthor = mysql_fetch_row($newauthorp);

What if 2 people (authors) have the same name ? :S Its never a good thing to query the table on fields like name.
But anyway, you can do it this way (but I don't recommend it :) )

$query = "select * from authors where name='".$author."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ) {
//an entry for this name exists in the table
$row = mysql_fetch_array($result);
$id = $row['id'];
} else {
$query = "insert into authors (name) value ('".$author."')";
mysql_query($query);
$id = last_insert_id(); //get the last inserted id from an auto increment field
}
echo "ID is: ".$id;

Again, there can be more than 1 person with the same name.

thanx thats help me alot :)

You are welcome! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.