PHP使用Inner Join编写语句中断

时间:2015-04-20 05:44:20

标签: php join mysqli inner-join

这是MySQLi扩展。我有两个表,sourcessource_categories。在sources中,有一个列存储源类别ID,它被称为source_category_id作为外键。在source_categories表中,source_category_id是主键,source_category_name包含实际的类别名称。非常基本。

我想INNER JOIN source_category_id两个表格INNER JOIN。我成功之前曾与Fatal error: Call to a member function bind_param() on a non-object合作过。但是,当我去测试页面时,我得到$sql = 'SELECT source_category_id, source_by, source_name, source_contact, source_category_name FROM sources INNER JOIN source_categories ON sources.source_category_id = source_categories.source_category_id WHERE source_type = ? ORDER BY source_name ASC'; $stmt = $conn->prepare($sql); $stmt->bind_param('s', $ps); $stmt->bind_result($source_category_id, $source_by, $source_name, $source_contact, $source_category_name); $stmt->execute(); $stmt->store_result(); $numRows = $stmt->num_rows;

准备好的语句只有一个占位符,如下所示,它来自一个包含查询字符串值的变量。

这不起作用:

INNER JOIN

但是,请忽略source_category_name代码以及$source_category_name$sql = 'SELECT source_category_id, source_by, source_name, source_contact FROM sources WHERE source_type = ? ORDER BY source_name ASC'; $stmt = $conn->prepare($sql); $stmt->bind_param('s', $ps); $stmt->bind_result($source_category_id, $source_by, $source_name, $source_contact); $stmt->execute(); $stmt->store_result(); $numRows = $stmt->num_rows; 来自各自的位置:

{{1}}

工作正常,但我也想要类别名称。

我显然错过了一些非常愚蠢的东西,或者我在某处正义地违反了语法,但是我疲惫的眼睛和伤脑无法找到问题。

非常感谢任何帮助。谢谢!

2 个答案:

答案 0 :(得分:0)

变化

$sql = 'SELECT source_category_id, source_by, source_name, source_contact, source_category_name
    FROM sources INNER JOIN source_categories
    ON sources.source_category_id = source_categories.source_category_id
    WHERE source_type = ?
    ORDER BY source_name ASC';

$sql = 'SELECT source_category_id, source_by, source_name, source_contact, source_category_name
    FROM sources INNER JOIN source_categories
    ON sources.source_category_id = source_categories.source_category_id
    WHERE sources.source_type = ?
    ORDER BY sources.source_name ASC';

答案 1 :(得分:0)

@Jack打了个头,非常感谢你的帮助。这是工作查询:

$sql = 'SELECT sources.source_category_id, sources.source_by, sources.source_name, sources.source_contact, source_categories.source_category_name
    FROM sources INNER JOIN source_categories
    ON sources.source_category_id = source_categories.source_category_id
    WHERE sources.source_type = ?
    ORDER BY sources.source_name ASC';
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $ps);    
$stmt->bind_result($source_category_id, $source_by, $source_name, $source_contact, $source_category_name);  
$stmt->execute();
$stmt->store_result();
$numRows = $stmt->num_rows;

再次,非常感谢!