user1745062 user1745062 - 9 days ago 5
MySQL Question

Multiple Tables Display in Rows

For some reason this is giving me an error?

$result = mysql_query("SELECT wpjb_job.*,
wpjb_category.*
FROM wpjb_job ,
wpjb_category
WHERE (is_filled='0' AND is_active='1')
AND wpjb_job.job_category = wpjb_category.id
AND job_country={$countryid}
ORDER BY wpjb_job.job_title") or die(mysql_error());


This is the error:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER BY wpjb_job.job_title' at line 6

as far as I can work out I have mySQL 5.1 on the server. The code still works but gives the error after the table.

I changed it to the following just to test. Now it is running fine however it prints the heading of the table twice, once in the beginning and then at the end. the change is on the $countryid, I now put it as '$countryid' this gives no errors

Below the code with the printing of the table

$joburl = "http://www.x.com/job/view/";
$result = mysql_query("SELECT wpjb_job.*,wpjb_category.*
FROM wpjb_job , wpjb_category
WHERE (is_filled='0' AND is_active='1')
AND wpjb_job.job_category = wpjb_category.id
AND job_country='$countryid'
ORDER BY job_title")
or die(mysql_error());

echo "<table border='1'>";
echo "<tr> <th>Job</th> <th>Company</th> <th>Industry</th> </tr>";

// keeps getting the next row until there are no more to get

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

// Print out the contents of each row into a table

echo "<tr><td>";
echo '<a href ="http://www.x.com/job/view/'.$row['job_slug'].'"> '.$row['job_title'].' </a>';
echo "</td><td>";
echo $row['company_name'];
echo "</td><td>";
echo $row['title'];
echo "</td></tr>";
}
echo "</table>";
}

Answer

Curly braces (complex syntax) are typically only used for evaluating array elements or object properties and other complex expressions ({$array[val]} or {$this->object}). You can drop them from your query. This may be causing your query to not interpreted depending on your PHP version and variable scope. You can check by doing an echo on your query string (echo "SELECT {$countryid}";).

Also, mysql_ functions are being deprecated, you should use either mysqli_ or PDO functions and bind parameters if you are passing variables that have been user generated.

Your query is also using implicit join syntax. You should practice explicit syntax when writing join queries (see below). Lastly, always use a column list rather than selecting all (SELECT *) to prevent unnecessary overhead.

SELECT a.col1, a.col2, b.col1
FROM wpjb_job a
INNER JOIN wpjb_category b ON b.id = a.job_category
WHERE (is_filled=0 AND is_active=1)
    AND a.job_country = $countryid
ORDER BY a.job_title