简体   繁体   English

将2个sql值添加到数组中

[英]Adding 2 sql values into an array

i am quite new to php and I want to do two select Counts on a mysql column and put these into an array. 我对php很陌生,我想在mysql列上做两个选择计数,并将它们放入数组中。 The code i have is below however this does not work. 我的代码在下面,但是这不起作用。

// DB connection
  $link = mysqli_connect( "localhost", "username", "password", "CE_TRANSACTIONS" );

// Query users table
  $sql = "SELECT (SELECT COUNT(STATUS) FROM CE_TRANSACTIONS WHERE STATUS = 0),
  (SELECT COUNT(STATUS) FROM CE_TRANSACTIONS WHERE STATUS = 3);"

// Execute query
  $result = mysqli_query($link,$sql);

// Loop over all result rows
  $result_array = array();

     while($array = mysqli_fetch_assoc($result)) 
     {

        $result_array[] = $array[];
     }

// Write to JSON
   echo json_encode($result_array);

Hi thanks for the quick replies i am also getting the following error message PHP Parse error: syntax error, unexpected T_VARIABLE for the below line. 您好,感谢您的快速答复,我也收到以下错误消息PHP Parse错误:语法错误,下一行意外的T_VARIABLE。

  // Execute query
  $result = mysqli_query($link,$sql);

Change 更改

 $result_array[] = $array[];

to

 $result_array = $array;

You may also see performance boost by using the following query instead. 通过使用以下查询,您可能还会看到性能提升。

SELECT Sum(Case When Status = 0 Then 1 Else 0), 
       Sum(Case When Status = 3 Then 1 Else 0)
FROM   CE_TRANSACTIONS

I believe your problem is coming from $array[]; 我相信您的问题来自$array[];

What the [] is saying is 'Access the value at', but you're not accessing any index of the array. []的意思是“访问值at”,但您没有访问数组的任何索引。

What you want to do is: $result_array[] = $array 您要执行的操作是: $result_array[] = $array

The PHP Parse error: syntax error, unexpected T_VARIABLE is because your line PHP Parse error: syntax error, unexpected T_VARIABLE是因为您的行

 $sql = "SELECT (SELECT COUNT(STATUS) FROM CE_TRANSACTIONS WHERE STATUS = 0), (SELECT COUNT(STATUS) FROM CE_TRANSACTIONS WHERE STATUS = 3);" 

is missing a trailing ; 缺少尾随; .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM