正确的语法,仍然给出错误

时间:2013-02-11 22:00:23

标签: php sql syntax-error

我无法让这个工作。 mySQL语句在我直接插入时工作,并且$ dbc是正确的,因为它在脚本中先前提取。

我可以帮忙吗?

//gets the username from the users table by looking for given id
function findUserNameFromID($userID){
   global $dbc;
   $getUser_query = 'SELECT username FROM forum_users WHERE userID ='.$userID;
   echo $getUser_query;
   //Errors on this line:
   $results = mysqli_query($dbc, $getUser_query) or die("Error: ".mysqli_error($dbc));
   $row = mysqli_fetch_array($results);
   return $row['username'];
}

编辑:忘记错误: 错误:SQL语法中有错误;查看与您的MySQL服务器版本对应的手册,以便在“>”附近使用正确的语法在第1行

编辑:这是完整页面代码:                                                                        

    //gets the username from the users table by looking for given id
    function findUserNameFromID($userID){
        global $dbc;
        $getUser_query = 'SELECT username FROM forum_users WHERE userID ='.$userID;
        echo $getUser_query;
        $results = mysqli_query($dbc, $getUser_query) or die("Error: ".mysqli_error($dbc)." ".__LINE__);
        $row = mysqli_fetch_array($results);
        return $row['username'];
    }

    function findUserIDFromName($username){
        global $dbc;
        $getUser_query = "SELECT userID FROM forum_users WHERE username = $username";
        $results = mysqli_query($dbc, $getUser_query);
        $row = mysqli_fetch_array($results);
        return $row['userID'];
    }

    $getThreads_query = "SELECT * FROM forum_threads ORDER BY lastTime, id";

    $results = mysqli_query($dbc, $getThreads_query);

    // show the data
    while ($row = mysqli_fetch_array($results))
    {
       echo "<p>";
       echo $row['title']."<br />";
       echo "Created by ".findUserNameFromID($row['creatorUserID']."<br />");
       //echo "Created on ".$row['createDate'];
       echo "</p>";

    }

    mysqli_close($dbc);

    ?>
    </body>
</html>

2 个答案:

答案 0 :(得分:0)

首先,您应该使用绑定变量,而不是像这样在SQL中嵌入参数(有关原因,请参阅http://bobby-tables.com/)。

您在问题中输入的错误消息与查询不匹配,除非$ userID包含“&gt;”,这意味着您的消息或您的断言$ userID是一个整数是不正确的。

答案 1 :(得分:0)

我发现了错误。

echo "Created by ".findUserNameFromID($row['creatorUserID']."<br />");中的右括号位置错误导致"<br />"包含在$userID中。

自我注意:检查括号的位置。