我需要从我的 SQL 数据库中选择类别 ID。
我有一个变量 $product_id
,对于每个产品 id,我需要使用 PHP 选择表中的三行。
如果我执行"SELECT * FROM table_name WHERE Product_id='$prodid'";
,我只会得到顶部的那个。
如何选择包含相同 product_id
的所有三个 category_id
?
最佳答案
我想您正在使用 PHP 的 mysql 函数,这是正确的吗?我认为您的查询实际上返回了所有三行,但您没有获取所有三行。
$sql = "SELECT * FROM table_name WHERE product_id='$prodid'";
$r = mysql_query($sql, $conn); //where $conn is your connection
$x = mysql_fetch_SOMETHING($r); //where something is array, assoc, object, etc.
获取函数一次仅给出一行。你说需要三个,所以需要执行三次。
$x[0] = mysql_fetch_assoc($r);
$x[1] = mysql_fetch_assoc($r);
$x[2] = mysql_fetch_assoc($r);
或者这样会更好
while($curRow = mysql_fetch_assoc($r)) //this returns false when its out of rows, returns false
{
$categoryIds[] = $curRow['category_id'];
}
如果这不起作用,那么您的查询实际上只返回一行,我们需要查看您的表/字段,也许还有示例数据。
关于php - 从 MYSQL 中选择几行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4481970/