这是MySQLi的扩展。我有两张表,sources
和source_categories
。在sources
中,有一列存储源类别id,称为source_category_id
,作为外键。在source_categories
表中,source_category_id
是主键,source_category_name
保存实际类别名称。相当基础。
我想source_category_id
上的两张表都INNER JOIN
。我以前曾成功地与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;
然而,从source_category_name
和$source_category_name
的相应位置省略INNER JOIN
代码,如下所示:
$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;
工作正常,但我也想要类别名称。
我显然错过了一些非常愚蠢的东西,或者我在某个地方理直气壮地违反了语法,但我疲惫的眼睛和受伤的大脑找不到问题所在。
如有任何帮助,我们将不胜感激。非常感谢。
更改
$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';
@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;
再次感谢!