我是PHP MySqli的新手,这是我的第一个项目。 我试图通过放置在数组中从函数返回值。
function riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to){
global $connection;
$sql = "SELECT ".$id." FROM ".$datatable." WHERE ".$id1." BETWEEN '".$date_from."' AND '".$date_to."' AND ".$id." = '".$type."'";
if ($result = mysqli_query($connection,$sql)) {
$count = 0;
while ($row = mysqli_fetch_array($result)) {
$count = ++ $count;
}
echo "<br>".$type.": " . $count;
$counter[$type] = $count;
return $counter;
}
$type = 'RIDDOR - Major Injury';
riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to);
var_dump($counter);
该函数工作到可以打印结果的程度,该结果基本上是数组的各种计数。但是,我需要在其他表中使用return,但是var-dump只会返回NULL。
答案 0 :(得分:1)
就像上面的所有注释一样,您正在使用$counter
就像它是全局变量一样-如果是这种情况,则可以在函数开头添加global $counter
,否则要用作返回值值,可以将其添加到函数参数中。
选项1-使用全局变量
function riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to){
global $connection;
global $counter;
$sql = "SELECT ".$id." FROM ".$datatable." WHERE ".$id1." BETWEEN '".$date_from."' AND '".$date_to."' AND ".$id." = '".$type."'";
if ($result = mysqli_query($connection,$sql)) {
$count = mysqli_num_rows($result);
echo "<br>".$type.": " . $count;
$counter[$type] = $count;
}
}
$type = 'RIDDOR - Major Injury';
riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to);
var_dump($counter);
选项2-使用返回值
function riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to){
global $connection;
$sql = "SELECT ".$id." FROM ".$datatable." WHERE ".$id1." BETWEEN '".$date_from."' AND '".$date_to."' AND ".$id." = '".$type."'";
if ($result = mysqli_query($connection,$sql)) {
$count = mysqli_num_rows($result);
echo "<br>".$type.": " . $count;
return $count;
}
}
$type = 'RIDDOR - Major Injury';
$counter[$type] = riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to);
var_dump($counter);
我强烈推荐第二个选项,以避免使用全局...
答案 1 :(得分:0)
您的代码应如下所示。不用在php中计数,您可以在查询中计数。
function riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to){
global $connection; global $counter;
$sql = "SELECT COUNT(".$id.") as cnt FROM ".$datatable." WHERE ".$id1." BETWEEN '".$date_from."' AND '".$date_to."' AND ".$id." = '".$type."'";
$count = 0;
if($result = mysqli_query($connection,$sql)) {
if ($row = mysqli_fetch_assoc($result)) {
$count = $row['cnt'];
}
}
$counter[$type] = $count;
}
$type = 'RIDDOR - Major Injury';
riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to);
var_dump($counter);
答案 2 :(得分:0)
您似乎正在使用昂贵的方法。通过一些功能,您可以轻松获取查询行数。
function riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to){
global $connection;
$sql = "SELECT ".$id." FROM ".$datatable." WHERE ".$id1." BETWEEN '".$date_from."' AND '".$date_to."' AND ".$id." = '".$type."'";
$result = mysqli_query($connection,$sql)
return mysqli_num_rows($result);
}
$type = 'RIDDOR - Major Injury';
$counter = riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to);
var_dump($counter);