mrteeth mrteeth - 7 months ago 18
SQL Question

Undefined variable array

I get an error on line 15 that says "Undefined variable: row2". How can I resolve this?

$limit = 20;

$res1 = mysql_query('SELECT *
FROM contact
WHERE name = "Greg"');
$res2 = mysql_query('SELECT name
FROM contact c, passport p
ON c.idNum = p.iNum
WHERE date >= "2015-03-03" AND t< "2015-03-21');

if(!$res1 && !$res2) {
die('Query no valid: ' . mysql_error());
}
else {
while(($row1 = mysql_fetch_array($res1)) || ($row2 = mysql_fetch_array($res2))) {
$sub = $row1['num'] - $row2['num'];
if($sub <= $limit) {
echo '<br>row name is: ', $row2['name'];
}
}
}


What I'm trying to do is get a number from the first table (it only results to just Greg's row). Then subtract it with the numbers from the results of the second table. The result of this is placed into the sub variable and it's check to see if it's <= 20. If yes, it prints out the row. If not, it goes back to while loop to check another row. Am I going about the right way so far?

Answer

Note : Select all columns in your 2nd Query if num is already available in your columns so your problem will be solved then.!

Note : Try to replace || with && and you will be good to go.

By using || or OR as in conceptional language as I would say it.You are making the code like in a way that either and only one will pass but if you are passing both ones so then you should replace || with && so that's why your $row2 will be already created then so it will be available for more operation.!

$limit = 20;

$res1 = mysql_query('SELECT *
                        FROM contact
                        WHERE name = "Greg"');
$res2 = mysql_query('SELECT *
                        FROM contact c, passport p
                        ON c.idNum = p.iNum
                        WHERE date >= "2015-03-03" AND t< "2015-03-21');

if(!$res1 && !$res2) {
    die('Query no valid: ' . mysql_error());
}
else {
    while(($row1 = mysql_fetch_array($res1)) && ($row2 = mysql_fetch_array($res2))) {
        $sub = $row1['num'] - $row2['num'];
        if($sub <= $limit) {
            echo '<br>row name is: ', $row2['name'];
        }
    }
}