【问题标题】:Dynamically change Offset in php sql statement [duplicate]在php sql语句中动态更改偏移量[重复]
【发布时间】:2014-05-24 18:32:02
【问题描述】:

我有以下查询,我想运行整个表,以便一个接一个地给我表的每个值。我需要它在另一个查询中使用特定的行值。

for ($qoffset=0; $qoffset<=5; $qoffset++) {
$result = mysqli_query($con,"select nf865_virtuemart_products.product_sku  from nf865_virtuemart_products order by product_sku asc limit 1 offset '".$qoffset."';");
  echo "offset='$qoffset' <br>";
    while($row = mysqli_fetch_array($result,MYSQLI_BOTH)) {
        echo $row[0];
        echo "<br>";
    }

我得到的是“警告:mysqli_fetch_array() 期望参数 1 是 mysqli_result,给定的布尔值”

结果我似乎得到了一个布尔值(假),如果放置一个数字而不是一个变量,查询就可以正常工作。

请问有什么帮助吗?

进一步的sql:

mysqli_query($con,"Insert  Ignore Into nf865_virtuemart_product_medias(virtuemart_product_id,virtuemart_media_id,ordering) VALUES (
(Select nf865_virtuemart_products.virtuemart_product_id from nf865_virtuemart_products where nf865_virtuemart_products.product_sku LIKE '0100100'),
(Select nf865_virtuemart_medias.virtuemart_media_id from nf865_virtuemart_medias 
where  nf865_virtuemart_medias.file_url LIKE '%0100100 b.jpg' or nf865_virtuemart_medias.file_url LIKE %0100100 B.jpg'),2)");

我尝试过但还没有成功:

$query1 = mysqli_query($con,"Select nf865_virtuemart_products.virtuemart_product_id from nf865_virtuemart_products where nf865_virtuemart_products.product_sku LIKE '".$product_id."'");

它需要像这样的“$变量”,因为它没有返回任何内容。

【问题讨论】:

  • 在使用它之前检查mysqli_query(实际上是大多数mysqli_函数)的返回值是个好主意,以防出现错误。例如:if ($result) { // process data } else { // handle error }
  • 根据the documentation,如果查询失败,mysqli_query 返回false。所以你应该有一个 if 子句,就像 pwaring 建议的那样。

标签: php mysql sql limit offset


【解决方案1】:

删除偏移量周围的单引号。

$result = mysqli_query($con,"select nf865_virtuemart_products.product_sku  from nf865_virtuemart_products order by product_sku asc limit 1 offset ".$qoffset);

您还应该检查错误:

if ($result == false){
    // you should have some logging method to log this error so you can check on it and return false to the calling function. I am using `die` here so you can at least see the error
    die("Sql Error: " . mysqli_error($con));
}

【讨论】:

  • 和偏移后的分号没用
  • 确实如此,但这不会产生错误。谢谢,我会删除它。
  • 当然可以,但是我写的没用,在错误使用时会执行一些错误
  • 大声谢谢!此外,如果您可以进一步帮助我,我需要在此查询中使用此输出(将 0100100 替换为上述查询结果 - 请参阅原始帖子更新),我尝试按照您在此中向我展示的方式进行操作但我猜我用引号弄错了
  • 最好将此答案标记为正确(如果正确),然后发布新问题。但是,要回答您的新问题,INSERT...SELECT 的格式应为 INSERT INTO table (col1, col2, ..., coln) SELECT col1, col2, ..., coln FROM table2 WHERE condition
猜你喜欢
  • 2010-09-13
  • 2013-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-23
  • 2017-05-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多