gpt4 book ai didi

用于计算返回 null 的 (MySql) 查询循环内各行的 PHP 函数

转载 作者:行者123 更新时间:2023-11-29 00:06:50 26 4
gpt4 key购买 nike

我想在查询循环中包含一个 php 函数,它只输出表中的所有行。

此函数将返回另一个查询,计算单个用户的行数,并将与第一个查询一起编码。

该函数有效,如果我回显 userId 变量,我就正确了,但出于某种原因,计数查询返回 null。

我需要一些帮助,谢谢!

<?php

include_once 'includes/db_connect.php';

$query = "SELECT * FROM UPLOADS";

//Creating resonse json array, with another array inside
$jsonResponse = array( "info" =>array() );

if($result = mysqli_query($mysqli, $query)) {
while($row = mysqli_fetch_assoc($result)){

$jsonRow = array(
'user' => $row['USER'],
'userId' => $row['USERID'],
'filename' => $row['FILENAME'],
'description' => $row['DESCRIPTION'],
'location' => $row['LOCATION'],
'address' => $row['ADDRESS'],
'likes' => $row['LIKES'],
'city' => $row['CITY'],
'lat' => $row['LAT'],
'lng' => $row['LNG'],
'countPost' => countUserPosts($row['USERID'])
);

//adding the $jsonRow array to the end of the "users" array as key/value
array_push($jsonResponse["info"], $jsonRow);
}

}

//encoding to json for the app
echo json_encode($jsonResponse);

function countUserPosts($userId){

$result = mysqli_query($mysqli, "SELECT count(*) FROM UPLOADS WHERE USERID = '$userId' ");
$row = mysqli_fetch_row($result);
$num = $row[0];

return $num;

}

?>

最佳答案

尝试在函数参数中注入(inject) mysqli 对象:

function countUserPosts($userId, $mysqli){
// ^ this one so it won't be out of scope.
$result = mysqli_query($mysqli, "SELECT count(*) FROM UPLOADS WHERE USERID = '$userId' ");
$row = mysqli_fetch_row($result);
$num = $row[0];

return $num;

}

关于用于计算返回 null 的 (MySql) 查询循环内各行的 PHP 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27100447/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com