PHP PDO SQL将两个字符串连接在一起

时间:2018-09-30 19:52:55

标签: php mysql sql pdo

我试图在一个prepare语句(表名和列是动态的)中将两个字符串连接在一起,但是我得到了

Uncaught PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'exp.$getSkill' in 'field list'

我的代码是:

$query = $db->prepare('SELECT members.*, exp.*, lvl.*, exp.$getSkill AS exp_skill, lvl.$getSkill AS level_skill FROM members INNER JOIN exp ON members.id = exp.member_id INNER JOIN lvl ON members.id = lvl.member_id ORDER BY lvl.$getSkill DESC, exp.$getSkill DESC');   
            $query->execute();
            $row = $query->fetch();

有没有办法可以加入exp。和$ getSkill正确?

2 个答案:

答案 0 :(得分:0)

变量不会在带单引号的字符串内求值。您需要使用双引号,并用花括号({})来包围名称:

$query = $db->prepare("SELECT members.*, exp.*, lvl.*, exp.${getSkill} AS exp_skill, lvl.$getSkill AS level_skill FROM members INNER JOIN exp ON members.id = exp.member_id INNER JOIN lvl ON members.id = lvl.member_id ORDER BY lvl.$getSkill DESC, exp.$getSkill DESC");

必填项:
在SQL查询中使用字符串连接可能会使您的代码受到SQL Ijection攻击。如果您打算使用这种技术,请非常

答案 1 :(得分:0)

尝试这样的事情:

$query = 'SELECT members.*, 
                 exp.*,            
                 lvl.*, 
                 exp.'.$getSkill.' AS exp_skill, 
                 lvl.$getSkill AS level_skill 
            FROM members 
               INNER JOIN exp ON members.id = exp.member_id 
               INNER JOIN lvl ON members.id = lvl.member_id 
           ORDER BY lvl.$getSkill DESC, exp.$getSkill DESC';

$query = $db->prepare($query);   
        $query->execute();
        $row = $query->fetch();