【问题标题】:PHP SQL select uses only the first result of the array in IN statement [duplicate]PHP SQL select仅使用IN语句中数组的第一个结果[重复]
【发布时间】:2021-05-24 06:07:07
【问题描述】:

我正在尝试根据从我放入数组的表中选择的 ID 对列进行求和。出于某种原因,在 Where 子句中只使用了第一个 ID。当我回显变量时,所有的 id 都在那里。我做错了什么?

$counttheid = array();
$stmt3 = $mysqli->prepare("SELECT 
    id 
    FROM account
    WHERE  level <= '5' AND door = ? AND `group_name` = ? AND betaald = 'Yes'");
    $stmt3->bind_param("ss",$usernamesession,$groupname);
    $stmt3->execute();
    $result3 = $stmt3->get_result(); //only works when nd_mysli is set on the server!
    

    while ($rowid = $result3->fetch_assoc())
{
    $counttheid[] = $rowid['id'];
    $countid = implode(',', $counttheid); // contains all the ids !!


}

$sql = "SELECT SUM(mobcash) AS totalcash FROM account WHERE id IN (?)  
     ";
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param("i",$countid);
    $stmt->execute();
    $stmt->bind_result($row['totalcash']);
    while($stmt->fetch()) $sumcash = $row['totalcash'];

    echo $sumcash; // Somhow only the sum of the first ID of the array !!
    
    echo $countid;// all the ids from the array !!

【问题讨论】:

标签: php arrays mysqli


【解决方案1】:

不仅in,绑定参数的数量也需要匹配。

尝试使用此示例获取从whileexecute 的代码:

while ($rowid = $result3->fetch_assoc())
{
    $counttheid[] = $rowid['id'];
    // $countid = implode(',', $counttheid); // contains all the ids !!
}

$in = str_repeat('?,', count($counttheid) - 1) . '?';
$types = str_repeat('i', count($counttheid));
$sql = "SELECT SUM(mobcash) AS totalcash FROM account WHERE id IN ($in)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param($types, ...$counttheid);
$stmt->execute();

bind_param,带有...$counttheid的部分,...部分是argument unpacking operator

【讨论】:

  • 给我以下错误。未捕获的 mysqli_sql_exception:没有为准备好的语句中的参数提供数据
  • 试过这样:while ($rowid = $result3-&gt;fetch_assoc()) { $counttheid[] = $rowid['id']; $countid = implode(',', $counttheid); } $in = str_repeat('?,', count($counttheid) - 1) . '?'; $sql = "SELECT SUM(mobcash) AS totalcash FROM account WHERE id IN ($in)"; $stmt = $mysqli-&gt;prepare($sql); $types = str_repeat('s', count($counttheid)); $stmt-&gt;bind_param($types,...$counttheid); $stmt-&gt;execute(); $stmt-&gt;bind_result($row['totalcash']); while($stmt-&gt;fetch()) $sumcash = $row['totalcash'];
  • 我不确定我们可能有什么不同?试试这个PHPize 代码。先运行 SQL,再运行 PHP。
  • 好吧,在这个例子中,它就像你所希望的那样工作。数组是这样的 $counttheid = [1, 2, 3];但这是硬编码的,如何将 1,2,3 数组替换为表中选定的值?我想这就是它出错的地方......
  • 好的,我试图改变你的例子。请参阅下面的链接。我不明白的是,echo 怎么会显示 id 1、2、4、5 等。为了让它工作,我应该做 [1,2,3]。但是当我为包含 1,2,3,4,5 等的变量替换 [1,2,3] 时,在这种情况下它只需要第一个.. [link]phpize.online/…
猜你喜欢
  • 1970-01-01
  • 2017-02-17
  • 2022-12-31
  • 1970-01-01
  • 2019-08-20
  • 1970-01-01
  • 1970-01-01
  • 2014-12-21
  • 2021-07-09
相关资源
最近更新 更多