Jump to content

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


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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.