Search code examples
phpmysqlosticket

sql returning no results


The following code is returning no results where I use the variable in the code of $dep if I manually put the value in of 1 it returns the expected result. I have tried it with no quotes single quotes and double quotes. I have looked though loads of examples and I cannot see what I am doing wrong

$dep = 1;
    if (!$names) {
        $sql = "SELECT topic_id, topic_pid, ispublic, isactive, topic, dept_id FROM '.TOPIC_TABLE
            . ' WHERE dept_id='$dep' ORDER BY `sort`";
        $res = db_query($sql);

Solution

  • I'm pretty sure your error is related to wrong quotes used. In your code, you write

    $sql = "SELECT topic_id, topic_pid, ispublic, isactive, topic, dept_id FROM '.TOPIC_TABLE
            . ' WHERE dept_id='$dep' ORDER BY `sort`";
    

    After FROM, you are using single-quotes('), but your whole query has been enclosed into double-quotes("), so that creates the issue.

    It should be:

    $sql = "SELECT topic_id, topic_pid, ispublic, isactive, topic, dept_id FROM ".TOPIC_TABLE
            . " WHERE dept_id='$dep' ORDER BY `sort`";
    

    EDIT: Forgot to point out you should seriously use PDO or any other SQL Injection prevention methods. If, under any circumstance, your $dep variable could be sent via a public form, you could end up by having your DB dumped in the best case.