$ _GET for MySQL查询导致未知列错误

时间:2013-05-08 22:48:25

标签: php mysql

我有一系列链接将信息传递给新页面以运行MySQL查询。这是源代码中的一个链接:

<a class="bloglink" href="parknews.php?tpf_news.park_id=5">

这是生成链接的代码:

<a class="bloglink" href="parknews.php?tpf_news.park_id=<?php echo $row2['park_id'];?>">
<?php echo $row2['name']; ?>
</a>

使用该信息的查询位于:

$park_id = $_GET['tpf_news.park_id'];
$sql = 'SELECT headline, story, DATE_FORMAT(date, "%d-%M-%Y") AS date, name
FROM tpf_news
INNER JOIN tpf_parks ON tpf_news.park_id = tpf_parks.park_id WHERE tpf_news.park_id = $park_id ORDER BY date DESC' ;

这会导致显示以下错误:

Error fetching news: SQLSTATE[42S22]: Column not found: 1054 Unknown column '$park_id' in 'where clause'

我无法理解为什么它不起作用。如果在查询中我将WHERE tpf_news.park_id = $park_id替换为WHERE tpf_news.park_id = 6(或任何其他数字),则可以正常使用。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您的单引号SQL。这意味着变量不会像您想象的那样显示。使用双引号。

为了对上帝的爱,我们准备好了陈述。

$sql = "SELECT headline, story, DATE_FORMAT(date, "%d-%M-%Y") AS date, name
FROM tpf_news
INNER JOIN tpf_parks ON tpf_news.park_id = tpf_parks.park_id WHERE tpf_news.park_id=$park_id ORDER BY date DESC" ;

$sql = 'SELECT headline, story, DATE_FORMAT(date, "%d-%M-%Y") AS date, name
FROM tpf_news
INNER JOIN tpf_parks ON tpf_news.park_id = tpf_parks.park_id WHERE tpf_news.park_id='.$park_id.' ORDER BY date DESC' ;

答案 1 :(得分:1)

当您的字符串在引号中时,您的变量不会被插值。所以你需要使用双引号:

$sql = "SELECT headline, story, DATE_FORMAT(date, '%d-%M-%Y') AS date, name
FROM tpf_news
INNER JOIN tpf_parks ON tpf_news.park_id = tpf_parks.park_id WHERE tpf_news.park_id = $park_id ORDER BY date DESC" ;

或者使用连接:

$sql = 'SELECT headline, story, DATE_FORMAT(date, "%d-%M-%Y") AS date, name
FROM tpf_news
INNER JOIN tpf_parks ON tpf_news.park_id = tpf_parks.park_id WHERE tpf_news.park_id =' .  $park_id .' ORDER BY date DESC' ;

仅供参考,您也可以SQL injections

开放