通过ID过滤连接两列

时间:2014-03-23 14:08:53

标签: php mysql database


我需要从我的数据库中加入两列,并按postID过滤,以便我可以使用URL参数postid。下面的代码不起作用,但我不知道如何更改它。建议?

$colname_join = "-1";
if (isset($_GET['postID'])) {
  $colname_join = $_GET['postID'];
}

mysql_select_db($database_connection, $connection);
$query_join = sprintf("SELECT * FROM image inner join post on post.postimage = image.imagename WHERE postID = %s", GetSQLValueString($colname_join, "int"));
$join = mysql_query($query_join, $connection) or die(mysql_error());
$row_join = mysql_fetch_assoc($join);
$totalRows_join = mysql_num_rows($join);

3 个答案:

答案 0 :(得分:0)

$sql  = "SELECT *
        FROM image
        INNER JOIN post ON post.postimage = image.imagename
        WHERE postID = %s". GetSQLValueString($colname_join, "int")";

答案 1 :(得分:0)

我想你可能想看一下这篇文章:How can I prevent SQL injection in PHP?

$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

$stmt->execute(array('name' => $name));

foreach ($stmt as $row) {
    // do something with $row
}

所选答案将向您展示如何使用可变部分进行查询,以及安全地进行sql注入。

答案 2 :(得分:0)

我相信你在sql查询中有错误的列名postID

$query_join = sprintf("SELECT * FROM image inner join post on post.postimage = image.imagename WHERE postID = %s", GetSQLValueString($colname_join, "int"));

将其更改为表post中显示的右列名称,例如,如果它是post.id列:

$query_join = sprintf("SELECT * FROM image inner join post on post.postimage = image.imagename WHERE post.id = %s", GetSQLValueString($colname_join, "int"));