Jump to content

Query One Table For Data, If Empty Query Second Table - Is This Possible?


sintax63

Recommended Posts

I need this for two separate page: a login screen and just a general page. I am not sure if this is possible, but I want to run a variable (in this case "login") and if it can't find any matches from my first table, I want it to try a second table before it fails out.

 

My code thus far:

 

$query="SELECT * FROM table1 WHERE login='$id'";
$result=mysql_query($query);

if ($result) 
{ 

while( $row = mysql_fetch_assoc( $result ) ) {

$id		= $row["id"];
$login	= $row["login"];
$pass	= $row["pass"];
$email	= $row["email"];

}

} else {

$query="SELECT * FROM table2 WHERE login='$id'";
$result=mysql_query($query);

while( $row = mysql_fetch_assoc( $result ) ) {

$id		= $row["id"];
$login	= $row["login"];
$pass	= $row["pass"];
$email	= $row["email"];

}

}

 

Is this a possible thing to do and am I on the right track?

It will return data from the first table, but not from the second.

 

Meaning I enter an ID that isn't in the first table. I want it to realize that it's not there and proceed to try the second table. Instead it just returns the page with empty variables.

 

I have tried tweaking the code a bit to what is below... same results though.

 

$query	= "SELECT * FROM table1 WHERE login='$id'";
$result	= mysql_query($query);

if (empty($result)) { 

$query	= "SELECT * FROM table2 WHERE login='$id'";
$result	= mysql_query($query);

	while( $row = mysql_fetch_assoc( $result ) ) {

	$id		= $row["id"];
	$login	= $row["login"];
	$pass	= $row["pass"];
	$email	= $row["email"];

	echo "Table 2";

	}

} else {

while( $row = mysql_fetch_assoc( $result ) ) {

$id		= $row["id"];
$login	= $row["login"];
$pass	= $row["pass"];
$email	= $row["email"];

echo "Table 1";

}

}

 

I added those echo statements in there just so I could see what was happening. It pulls correctly from table 1 but doesn't try table 2 if it can't find the username / ID.

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.