从MySQL存储过程获取PHP输出值和记录集

时间:2018-02-03 13:38:43

标签: php mysql stored-procedures mysqli

我在MySQL中有以下程序

# needs import os

@client.event
async def on_message(message): 
    fileName = "{0}.txt".format(message.author.id) 

    if os.path.exists(fileName):
        with open(fileName, "r") as readFile:
            data = int(readFile.read())
    else:
        data = 0

    with open(fileName, "w") as writeFile:
        writeFile.write(str(data+1))

在phpMyAdmin中,该过程将记录集和总和返回到totalValue。

我面临的问题是用PHP获取所有这些信息。我能够获取记录集或totalValue参数,但不能同时获取两者。这是我尝试使用mysqli函数的不同变体的代码:

CREATE PROCEDURE `getCustomerData`(
IN customerId INT(11),
OUT totalValue INT(11)
)

BEGIN
  SELECT id,name,category,quantity,price,tax,total FROM product WHERE 
  customer_Id = customerId;
  SELECT SUM(total) INTO totalValue FROM product WHERE customer_Id = 
  customerId;
END

我添加了mysqli_more_results函数来测试是否有更多信息可以获取并且它总是返回true。 mysqli_use_result不适用于输出值。

我还补充说:

$query = "CALL getCustomerData('".$customerId."',@totalValue);";
$query.= "SELECT @totalValue";

if(mysqli_multi_query($dblink,$query)){
  $values = array();

  do{
     if($result = mysqli_use_result($dblink)){
        while($this->row = mysqli_fetch_assoc($result)){
           $values[] =  $this->row;                    
        }

        mysqli_free_result($result);
      }else{
           throw new \Exception(mysqli_error($dblink));
      }

      if(!mysqli_more_results($dblink)){
         $values['test'] = "No more results found";
      }
   }while (mysqli_next_result($dblink));

   return $values;
 }
 else{
     throw new \Exception(mysqli_error($dblink));
 }

记录集获取后,没有do-while循环,但没有运气...... 在这部分我得到了一个

if(mysqli_next_result($dblink)){
   $select = mysqli_query($dblink, 'SELECT @totalValue');
   $result = mysqli_fetch_assoc($select);
   $values['totalValue'] = $result['@totalValue'];
}

是否有可能在PHP中获得这种混合(记录集+输出值)?如果是这样,任何人都可以在这里说清楚。

谢谢,

1 个答案:

答案 0 :(得分:0)

为什么要将OUT参数用于第二个结果集?

从过程返回两个结果集会更容易。这样,两个结果集都将以相同的方式处理。

CREATE PROCEDURE `getCustomerData`(
customerId INT(11)
)
BEGIN
  SELECT id,name,category,quantity,price,tax,total 
  FROM product 
  WHERE customer_Id = customerId;

  SELECT SUM(total) as totalValue 
  FROM product 
  WHERE customer_Id = customerId;
END

您可以从PHP调用该过程:

$query = "CALL getCustomerData(".intval($customerId).")";

if (mysqli_multi_query($dblink,$query)){
  $values = array();
  do {
    $result_set = array();
    if ($result = mysqli_store_result($dblink)) {
      while($row = mysqli_fetch_assoc($result)) {
        $result_set[] = $row;                    
      }
      $values[] = $result_set;
      mysqli_free_result($result);
    }
  } while (mysqli_more_results($dblink) && mysqli_next_result($dblink));

  return $values;
}
else{
 throw new Exception(mysqli_error($dblink));
}