php - PHP在函数中返回一个数组
问题描述
我是 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);
该函数工作到将打印结果的程度,该结果基本上是数组的各种计数。但是,我需要在其他地方的表中使用返回,但 var-dump 只返回 NULL。
解决方案
As all the comment above - you are using $counter
as if it global variable - if that is the case you can add global $counter
at the begin of the function else if you want to use as return value you can add it to the function argument.
Option 1 - use global variable
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);
Option 2 - use return value
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);
I strongly recommend the second option to avoid using global...
推荐阅读
- python - QTableWidget.scrollToItem 功能问题
- amazon-web-services - 是否可以将我的组织红移数据卸载到我的组织外部的 s3 存储桶?
- python - 从 Django values() 获取外键值
- android - SingleChildScrollView 在 Column 内不起作用
- r - 无法在 for 循环内的 ggplot2 中使用 facet
- c# - c# 如何使用不同的签名来处理抽象工厂(?)
- assembly - 要求用户输入三个数字(每个是一个字节) A、B 和 C 将数字相加并将总和存储在变量 D 中输出总和
- python - 如何更好地分隔地块?
- css - 我不能将 flexbox 用于可触摸的不透明度/可按压。如何将这两个元素连续对齐?
- attachment - 无法通过包@waves/waves-transactions 在 Waves 比特币中附加交易消息