PHP Else If dB Echo Changeup

Hello everyone,

Here’s something I haven’t figured out and it’s making me scratch my head!

I have two databases and have content in both and use data from one or the other. My idea is to echo the first dB and then say “If that’s empty use the info that’s in the other dB instead”.

For instance:
If Field “content_one” in dB XYZ contains data, then use it.
If Field “content_one” in dB XYZ doesn’t contain date then go to dB ZYY and look in field “content_zyy” and use that.

Anyone have a hint on how I can go about this?

Thank you,
RB

Assuming you are using mysql_* functions, you can use mysql_num_rows() to determine if you got any results back. If you didn’t, you can execute another query to your 2nd database.

http://us.php.net/manual/en/function.mysql-num-rows.php

There’s a perfect example in the manual:


$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);

$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);

if ($num_rows == 0) {
  //no results so...
  //execute 2nd query
}

I’m not sure if I understand you correctly but I’ll give it a shot. This is untested and is still based off the example from the manual:


$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);

$id = 1;

$result = mysql_query("SELECT * FROM table1 WHERE id=$id", $link);
$num_rows = mysql_num_rows($result);

if ($num_rows == 0) {
  mysql_select_db("database2", $link); //new database ie database2

  $result = mysql_query("SELECT * FROM table1 WHERE id=$id", $link);
}

while ($row = mysql_fetch_assoc($result)) {
    //do something with your data...
}

You should alter this and tailor it to your needs.

Cerium

Thank you for your help!

I just realized that the script has to reference an ID such as a common item number and I’m not sure how would the script look with both dB queries in place.

Can you update your example so I can understand better? Also, can I just close the dB call in a second mySQL close connection statement?

Thank you very much,
RB