从 PHP 程序调用时,PHP 存储过程(Mysql)不起作用 [英] PHP Store Procedure(Mysql) doesen't work when it's call from PHP program

查看:40
本文介绍了从 PHP 程序调用时,PHP 存储过程(Mysql)不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的托管中,我有一个存储过程(MySQL DBMS),它接收四个参数,当我在 Workbench 上运行并远程连接到我的托管时,它工作正常,我得到了结果(记录)

In my hosting, I have a Store Procedure(MySQL DBMS), it received four parameters, when I have run on Workbench with remote connection to my hosting, it's Works fine an I get the result (records)

call tabla_posiciones(1,1,7,5);

所以,我遇到了一个问题,因为在我的 PHP 程序中,存储过程不起作用,我使用了相同的用户,相同的参数并且 SP 没有获得记录,我总是将它的 0 放入 $contador 变量中,并且获取 Json 返回信息中的status => 1"项

So, I have a problem because in my PHP program the Stored Procedure doesn't work, I have used the same user, the same parameters and the SP has not gotten records, I always get it 0 into $contador variable and get it the "status => 1" ítem on Json return information

<?php
// Helper method to get a string description for an HTTP status code
// From http://www.gen-x-design.com/archives/create-a-rest-api-with-php/ 
function getStatusCodeMessage($status)
{
// these could be stored in a .ini file and loaded
// via parse_ini_file()... however, this will suffice
// for an example
$codes = Array(
    100 => 'Continue',
    101 => 'Switching Protocols',
    200 => 'OK',
    201 => 'Created',
    202 => 'Accepted',
    203 => 'Non-Authoritative Information',
    204 => 'No Content',
    205 => 'Reset Content',
    206 => 'Partial Content',
    300 => 'Multiple Choices',
    301 => 'Moved Permanently',
    302 => 'Found',
    303 => 'See Other',
    304 => 'Not Modified',
    305 => 'Use Proxy',
    306 => '(Unused)',
    307 => 'Temporary Redirect',
    400 => 'Bad Request',
    401 => 'Unauthorized',
    402 => 'Payment Required',
    403 => 'Forbidden',
    404 => 'Not Found',
    405 => 'Method Not Allowed',
    406 => 'Not Acceptable',
    407 => 'Proxy Authentication Required',
    408 => 'Request Timeout',
    409 => 'Conflict',
    410 => 'Gone',
    411 => 'Length Required',
    412 => 'Precondition Failed',
    413 => 'Request Entity Too Large',
    414 => 'Request-URI Too Long',
    415 => 'Unsupported Media Type',
    416 => 'Requested Range Not Satisfiable',
    417 => 'Expectation Failed',
    500 => 'Internal Server Error',
    501 => 'Not Implemented',
    502 => 'Bad Gateway',
    503 => 'Service Unavailable',
    504 => 'Gateway Timeout',
    505 => 'HTTP Version Not Supported'
);

return (isset($codes[$status])) ? $codes[$status] : '';
}

// Helper method to send a HTTP response code/message
function sendResponse($status = 200, $body = '', $content_type = 'text/html')
{
$status_header = 'HTTP/1.1 ' . $status . ' ' . getStatusCodeMessage($status);
header($status_header);
header('Content-type: ' . $content_type);
echo $body;
}


class RedeemAPI {
private $db;
// Constructor - open DB connection
function __construct() {
    $this->db = new mysqli('localhost', 'user', 'password', 'eschema');
   /* verificar la conexión */
   if (mysqli_connect_errno()) {
    printf("Conexión fallida: %s\n", mysqli_connect_error());
    exit();
  }
    $this->db->autocommit(FALSE);
    $this->db->query("SET NAMES 'utf8'");
}

// Destructor - close DB connection
function __destruct() {
    $this->db->close();
}
// Main method to redeem a code
function redeem() {
// Check for required parameters
if (isset($_POST["id_cliente"]) && isset($_POST["id_sucursal"]) && isset($_POST["id_torneo"]) && isset($_POST["id_jornada"])) {
    // Put parameters into local variables
    $cliente = $_POST["id_cliente"];
    $sucursal = $_POST["id_sucursal"];
    $torneo = $_POST["id_torneo"];
    $jornada = $_POST["id_jornada"];

    // Look up code in database
    $stmt = $this->db->prepare('CALL tabla_posiciones(?,?,?,?)') or die(mysqli_error($this->db));
    $stmt->bind_param("iiii", $cliente, $sucursal, $torneo, $jornada);
    $stmt->execute();        
    $stmt->bind_result($equ_nombre, $jj, $jg, $je, $jp, $gf, $ge, $dif, $puntos);              
    $arreglo = array() ;    
    $contador = 0;   
    while  ($stmt->fetch()) {
        $arreglo[$contador] = array("equ_nombre"=>$equ_nombre,"jj"=>$jj,"jg"=>$jg,"je"=>$je,"jp"=>$jp,"gf"=>$gf,"ge"=>$ge,"dif"=>$dif,"puntos"=>$puntos);
        $contador++;
    }        
    $stmt->close();
    // Bail if records doesn't exist
    if ($contador <= 0) {
        $cuantos = 0;
        $datos[$cuantos] = array("equ_nombre"=>"S/N");
        $return_array = array('Datos' => $datos,'status' => 1, 'mensaje' => 'No existen registros con los datos proporcionados');
        sendResponse(200, json_encode($return_array));
        return true;
    }
    $this->armarbol($arreglo);
    return true;
}
$return_array = array('status' => 1, 'mensaje' => 'Al parecer no se enviaron los parámetros necesarios');
        sendResponse(200, json_encode($return_array));
        return true;
  }

  function armarbol(array $general)
  {
$datos = array();  
//echo "Ingreso a function ";   
$cuantos = 0;  
foreach ($general as $reg)
{  

   $datos[$cuantos] = array("equ_nombre"=>$reg["equ_nombre"],"jj"=>$reg["jj"],"jg"=>$reg["jg"],"je"=>$reg["je"],"jp"=>$reg["jp"],"gf"=>$reg["gf"],"ge"=>$reg["ge"],"dif"=>$reg["dif"],"puntos"=>$reg["puntos"] );  
   $cuantos++;          
}   


$return_array = array('Datos' => $datos, 'status' => 0, 'mensaje' => '');
sendResponse(200, json_encode($return_array));
 } 
 }

// This is the first thing that gets called when this page is loaded
// Creates a new instance of the RedeemAPI class and calls the redeem method
$api = new RedeemAPI;
$api->redeem();

?>

存储过程代码....

CREATE DEFINER=`root`@`localhost` PROCEDURE `tabla_posiciones`(in par_cliente int, in par_sucursal int, in par_torneo int, in par_jornada int)
begin

  DECLARE vn_equipo INT;
  DECLARE vn_jornada INT;
  DECLARE vn_numjueg INT;
  DECLARE vn_equipo_vs INT;
  DECLARE vn_jj INT DEFAULT 0;
  DECLARE vn_marcador1 INT;
  DECLARE vn_marcador2 INT;
  DECLARE vn_jg INT DEFAULT 0;
  DECLARE vn_je INT DEFAULT 0;
  DECLARE vn_jp INT DEFAULT 0;
  DECLARE vn_gf INT DEFAULT 0;
  DECLARE vn_ge INT DEFAULT 0;
  DECLARE vn_puntos INT DEFAULT 0;
  DECLARE done INT DEFAULT 0;    
  /* Cursor de Tabla Temporal */
  DECLARE barre_temporal CURSOR FOR
     SELECT id_equipo
     FROM tabla_pos;
  /* Cursor para barrer los partidos */
  DECLARE barre_partidos CURSOR FOR
      SELECT a.id_jornada, a.id_juego
      FROM encuentro as a, calendario as b
      WHERE a.id_cliente = par_cliente AND a.id_sucursal = par_sucursal AND
            a.id_torneo  = par_torneo AND a.id_jornada <= par_jornada AND a.id_equipo = vn_equipo AND
            b.id_cliente = a.id_cliente AND b.id_sucursal = a.id_sucursal AND
            b.id_torneo = a.id_torneo AND b.id_jornada = a.id_jornada AND b.id_juego = a.id_juego AND
            b.cal_estatus = 1;

  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;

  DROP TEMPORARY TABLE IF EXISTS tabla_pos;

  CREATE TEMPORARY TABLE tabla_pos AS
   SELECT id_equipo,0 as jj,0 as jg,0 as je,0 as jp,0 as gf,0 as ge,0 as puntos, 0 goles, 0 diferencia, 0 num_juego, 0 adeudo
   FROM equipo
   WHERE id_cliente = par_cliente AND id_sucursal = par_sucursal AND id_torneo = par_torneo AND equ_estatus = 'A';

  SET SQL_SAFE_UPDATES=0;
  OPEN barre_temporal;
  read_loop: LOOP
    /* barre equipos de la temporal */
   FETCH barre_temporal INTO vn_equipo;
   If done THEN
     LEAVE read_loop;
  END IF;
  OPEN barre_partidos;
  read_partidos: LOOP
    /* Barre los partidos del equipo en curso */
    FETCH barre_partidos INTO vn_jornada, vn_numjueg;
    If done THEN
       LEAVE read_partidos;
    End If;
    /* Incrementa el contador de número de juegos */
    SET vn_jj = vn_jj + 1;
    /* Determina el equipo contrario */
    SET vn_equipo_vs = (SELECT id_equipo
                        FROM encuentro
                        WHERE id_equipo <>  vn_equipo and id_cliente = par_cliente and id_sucursal = par_sucursal and id_torneo = par_torneo and id_jornada = vn_jornada and id_juego = vn_numjueg) ;
    /* Determina Marcadores de ambos equipos */
    SET vn_marcador1 = (SELECT  IfNull(SUM(detalle_encuentro.denc_gol),0)
                        FROM detalle_encuentro
                        WHERE id_cliente = par_cliente AND
                              id_sucursal= par_sucursal AND
                              id_torneo  = par_torneo AND
                              id_jornada = vn_jornada AND
                              id_juego   = vn_numjueg AND
                              id_equipo  = vn_equipo);
    SET vn_marcador2 = (SELECT  IfNull(SUM(detalle_encuentro.denc_gol),0)
                        FROM detalle_encuentro
                        WHERE id_cliente = par_cliente AND
                              id_sucursal= par_sucursal AND
                              id_torneo  = par_torneo AND
                              id_jornada = vn_jornada AND
                              id_juego   = vn_numjueg AND
                              id_equipo  = vn_equipo_vs);
    IF vn_marcador1 = vn_marcador2 Then
       SET vn_je = vn_je + 1;
       SET vn_puntos = vn_puntos + 1;
    END IF;
    If vn_marcador1 > vn_marcador2 Then
       SET vn_jg = vn_jg + 1;
       SET vn_puntos = vn_puntos + 3;
    END IF;
    If vn_marcador2 > vn_marcador1 Then
       SET vn_jp = vn_jp + 1;
    END IF;
    SET vn_gf = vn_gf + vn_marcador1;
    SET vn_ge = vn_ge + vn_marcador2;
    /* Sólo si la jornada es igual a la del párametro de entrada, se graban los marcadores*/
    If vn_jornada = par_jornada Then
       UPDATE tabla_pos
       SET goles = vn_marcador1, num_juego = vn_numjueg
       WHERE id_equipo = vn_equipo;
       UPDATE tabla_pos
       SET goles = vn_marcador2, num_juego = vn_numjueg
       WHERE id_equipo = vn_equipo_vs;
    END IF;
    END LOOP;   
    CLOSE barre_partidos;
    UPDATE tabla_pos
    SET jj = vn_jj, jg = vn_jg, je = vn_je, jp = vn_jp, gf = vn_gf, ge = vn_ge, puntos = vn_puntos
    WHERE id_equipo = vn_equipo;
 SET vn_jj = 0;
    SET vn_je = 0;
 SET vn_puntos = 0;
    SET vn_jp = 0;
    SET vn_jg = 0;
    SET vn_gf = 0;
    SET vn_ge = 0;
    SET done = 0;
 END LOOP;
 CLOSE barre_temporal;
 SET vn_jornada = premio_jumex(par_cliente,par_sucursal,par_torneo);
 SELECT equipo.equ_nombre, tabla_pos.jj, tabla_pos.jg, tabla_pos.je,
     tabla_pos.jp, tabla_pos.gf, tabla_pos.ge, (tabla_pos.gf - tabla_pos.ge) as 'dif', tabla_pos.puntos
 FROM tabla_pos, equipo
 WHERE equipo.id_cliente = par_cliente AND equipo.id_sucursal = par_sucursal AND
    equipo.id_torneo = par_torneo AND equipo.id_equipo = tabla_pos.id_equipo
 ORDER BY 9 DESC,8 DESC;
 END

推荐答案

如果我从 http://php.net/manual/en/mysqli.quickstart.stored-procedures.php

你必须转型:

$stmt = $this->db->prepare('CALL tabla_posiciones(?,?,?,?)') or die(mysqli_error($this->db));
    $stmt->bind_param("iiii", $cliente, $sucursal, $torneo, $jornada);
    $stmt->execute(); 

类似于:

$stmt = $this->db->prepare('SET @par_cliente := ?');
$stmt->bind_param('i', $cliente);
$stmt->execute();

$stmt = $this->db->prepare('SET @par_sucursal := ?');
$stmt->bind_param('i', $sucursal);
$stmt->execute();

$stmt = $this->db->prepare('SET @par_torneo := ?');
$stmt->bind_param('i', $torneo);
$stmt->execute();

$stmt = $this->db->prepare('SET @par_jornada := ?');
$stmt->bind_param('i', $jornada);
$stmt->execute();

$result =  $this->db->query('CALL tabla_posiciones(@par_cliente,@par_sucursal,@par_torneo, @par_jornada)');

希望能帮到你

这篇关于从 PHP 程序调用时,PHP 存储过程(Mysql)不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆