Executing sql "Insert Command" on failed "Select Query&

Joined: 11/28/2008

OK, this should be extremely simple. In fact, I've done this before. Its just lost somewhere in a deep pocket of my mind.

This is what I'm trying to do. I have a form that submits values to a processing php file. wonderful... no problem there. But, I want the processing file to first check to see if an entry with those exact values has already been entered, and if not, continue with the insert command.

This is what I know,

The variables are passed to the php file though post,
php file grabs the post variables and creates normal variables out of them
a select command is run like this:

CODE
$q = mysql_query("SELECT relationship_id FROM `relationships` where relationship_child_id='".$relationship_child_id."' and relationship_child_type='".$relationship_child_type."' and relationship_parent_id='".$relationship_parent_id."' and relationship_parent_type='".$relationship_parent_type."' limit 1" ) or die(mysql_error());

How do I execute an insert (or anything) on a failed select?
The only thing I could think of was to use an if statement checking for a false value for the relationship_id

Help a brotha' out!

Thanks Guys!

Joined: 11/28/2008
See what the following does

See what the following does for you. You will need to edit the INSERT query with the correct information before testing it.

CODE
$q = "SELECT relationship_id FROM `relationships` where relationship_child_id='".$relationship_child_id."' and relationship_child_type='".$relationship_child_type."' and relationship_parent_id='".$relationship_parent_id."' and relationship_parent_type='".$relationship_parent_type."' limit 1";
$rs = mysql_query($q) or die(mysql_error());

if($id = mysql_fetch_assoc($rs))
{
    // information already exists so let the user know
}
else
{
    $q = "INSERT INTO `relationships` ....";
    $rs = mysql_query($q) or die(mysql_error());
}

After you execute the query, assuming it is executed, you have to fetch the data. In my example, $id with be null or it will have the value of relationship_id. If it's null or false, we know it doesn't exist, so we want to execute another query to insert the posted data.

Who can bring a charge to God's elect? It is God who justifies!

Joined: 11/28/2008
I do what Mathachew is

I do what Mathachew is describing, except that I check mysql_num_rows() rather than attempt to fetch a row. So my conditional line would look like this instead:

CODE
if(mysql_num_rows($rs) > 0)

Joined: 11/28/2008
I really don't even use

I really don't even use mysql_num_rows() so I didn't even think of it, but that would be a better conditional to use than trying to fetch the data.

Who can bring a charge to God's elect? It is God who justifies!

Joined: 11/28/2008
Thanks so much! That worked

Thanks so much! That worked quite nicely! You guys really saved me alot of time.