Kenapuc Kenapuc - 2 months ago 11
MySQL Question

Incomprehensible MySQL error in PHP (table doesn't exist, union query)

I'm still getting mysql error in my PHP script.

Problematic code:

$mquery = mysql_query("SELECT m.`id`, m.`name`, NULL AS `type`, NULL AS `code`, 0 AS `cat` FROM `menu` m UNION ALL SELECT l.`id`, l.`name`, l.`type`, l.`code`, l.`cat` FROM `lines` l UNION ALL SELECT s.`id`, s.`name`, s.`site`, s.`site`, s.`cat` FROM `sites` s ORDER BY `name` ASC");
if(!$mquery) { echo mysql_error(); die(); }
while($mdata = mysql_fetch_assoc($mquery)) { ... }


When i put this query into PhpMyAdmin - all is OK, i will get result. When I put this query into MySQL Workbench - all is OK, i will get result.

AND NOW: When I run script with parameter (http://domain/index.php?site=ABC) - ALL IS OK. When I run script without parameter (http://domain/index.php) - I get mysql error on this query: "Table 'test.menu' doesn't exist".

What "test.menu"?! Where is "test"? I don't want any "test", I have no "test" in my query. And why is it related on parameter in url? It's not dynamically generated query. Where is problem?

Sorry for my english

Solved, script structure:

$mydb = mysql_connect(...);
mysql_select_db(..., $mydb);
mysql_set_charset('utf8', $mydb);

function newMenu($db)
{
$mquery = mysql_query("...", $db);
if(!$mquery) { echo mysql_error(); die(); }
while($mdata = mysql_fetch_assoc($mquery) { ... }
}

myMenu($mydb);


But what i don't understand is: Why is it working without "$db" when parameter 'site' is in url?

Answer Source

Please check your mysql configuration in PHP. I am pretty sure you are using database name as 'test' because you've copied the code from somewhere. Change it to the actual name of your database and it will work.

The second parameter of mysql_query must be a connection variable.

 <?php  
 $con = mysql_connect("localhost", "root", "mypass") or  
 die("Could not connect: " . mysql_error());  
 mysql_select_db("tutorials");  
 $result = mysql_query("select * from tutorials");  
 echo "<h2>Here is a list of the topics:</h2>";  
 while ($row = mysql_fetch_array($result)) {  
   echo $row['name']."<br />";  
 }  
mysql_close($con);  
?>