Foros del Web » Programando para Internet » PHP »

[SOLUCIONADO] Error en consulta a la b.d con PHP y PDO

Estas en el tema de Error en consulta a la b.d con PHP y PDO en el foro de PHP en Foros del Web. Hola gente, Tengo la siguiente consulta que me funciona muy bien en el sql-server @import url("http://static.forosdelweb.com/clientscript/vbulletin_css/geshi.css"); Código SQL: Ver original SELECT CONVERT ( VARCHAR ( ...
  #1 (permalink)  
Antiguo 10/01/2014, 10:51
Avatar de adryan310  
Fecha de Ingreso: septiembre-2012
Mensajes: 450
Antigüedad: 11 años, 7 meses
Puntos: 3
Pregunta Error en consulta a la b.d con PHP y PDO

Hola gente,

Tengo la siguiente consulta que me funciona muy bien en el sql-server
Código SQL:
Ver original
  1. SELECT CONVERT(VARCHAR(8), G.[GradedDate] , 108) AS 'Time',
  2.   CONVERT(VARCHAR(MAX),G.[VisitorNumber]) + '/' + CONVERT(VARCHAR(MAX),G.[HomeNumber]) AS 'NumGame', G.[VisitorTeam] + ' @ ' +G.[HomeTeam] AS 'Teams',
  3.   P.[PeriodDescription], CONVERT(VARCHAR(MAX),G.[VisitorScore]) + ' - ' + CONVERT(VARCHAR(MAX),G.[HomeScore]) AS 'Score', COUNT(*) AS 'Tickets',
  4.   SUM(H.[RiskAmount]) AS 'Risk'
  5. FROM WAGERHEADER H, WAGERDETAIL D, GAME G, PERIOD P
  6. WHERE H.[IdWager] = D.[IdWager] AND
  7.       D.[IdGame]  = G.[IdGame]  AND
  8.       H.[SettledDate] >= CONVERT(datetime,('2014-01-10 00:00:01')) AND
  9.       H.[SettledDate] <= CONVERT(datetime,('2014-01-10 23:59:59')) AND
  10.       D.[IdSport] = P.[IdSport] AND
  11.       D.[Period]  = P.[NumberOfPeriod] AND
  12.       H.[IdAgent] = 7
  13. GROUP BY G.[GradedDate], G.[VisitorNumber], G.[VisitorTeam], G.[HomeNumber], G.[HomeTeam], P.[PeriodDescription], G.[VisitorScore], G.[HomeScore]
Pero cuando la realizo desde el php me da este error:

PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[24000]: Invalid cursor state: 0 [FreeTDS][SQL Server]Invalid cursor state (SQLExecute[0] at /build/php5-UepG4H/php5-5.3.3/ext/pdo_odbc/odbc_stmt.c:254)' in /var/www/gradingticker/v1/class/search.php:48\nStack trace:\n#0 /var/www/gradingticker/v1/class/search.php(48): PDO->query('SELECT CONVERT(...')\n#1 {main}\n thrown in /var/www/gradingticker/v1/class/search.php on line 48, referer: http://gradingticker.evenreal.com/index.php

Este es mi codigo PHP:
Código PHP:
Ver original
  1. $yesterday = date('Y-m-d')." 00:00:01";
  2.                $today     = date('Y-m-d')." 23:59:59";
  3.                
  4.                $strQueryGames = "SELECT CONVERT(VARCHAR(8), G.[GradedDate] , 108) AS 'Time',
  5.                                         CONVERT(VARCHAR(MAX),G.[VisitorNumber]) + '/' + CONVERT(VARCHAR(MAX),G.[HomeNumber]) AS 'NumGame', G.[VisitorTeam] + ' @ ' +G.[HomeTeam] AS 'Teams', P.[PeriodDescription],
  6.                                         CONVERT(VARCHAR(MAX),G.[VisitorScore]) + ' - ' + CONVERT(VARCHAR(MAX),G.[HomeScore]) AS 'Score', COUNT(*) AS 'Tickets',
  7.                                         SUM(H.[RiskAmount]) AS 'Risk'
  8.                                 FROM WAGERHEADER H, WAGERDETAIL D, GAME G, PERIOD P
  9.                                  WHERE H.[IdWager] = D.[IdWager] AND
  10.                                        D.[IdGame]  = G.[IdGame]  AND
  11.                                        H.[SettledDate] >= CONVERT(datetime,('".$yesterday."')) AND
  12.                                        H.[SettledDate] <= CONVERT(datetime,('".$today."')) AND
  13.                                        D.[IdSport] = P.[IdSport] AND
  14.                                        D.[Period]  = P.[NumberOfPeriod] AND
  15.                                        H.[IdAgent] = ".$IdAgent."
  16.                                  GROUP BY G.[GradedDate], G.[VisitorNumber], G.[VisitorTeam], G.[HomeNumber], G.[HomeTeam], P.[PeriodDescription], G.[VisitorScore], G.[HomeScore]";
  17.                
  18.                error_log("class->search.php->strQueryGames = ".$strQueryGames);
  19.                $strDataGames = $strConnect->query( $strQueryGames );   
  20.                
  21.                while($dataGames = $strDataGames->fetch(PDO::FETCH_ASSOC)){
  22.                      $response  = "<tr>";
  23.                      $response .= "<td>".$dataGames['Time']."</td>";
  24.                      $response .= "<td>".$dataGames['NumGame']."</td>";
  25.                      $response .= "<td>".$dataGames['Teams']."</td>";
  26.                      $response .= "<td>".$dataGames['PeriodDescription']."</td>";
  27.                      $response .= "<td>".$dataGames['Score']."</td>";
  28.                      $response .= "<td>".$dataGames['Tickets']."</td>";
  29.                      $response .= "<td>".$dataGames['Risk']."</td>";
  30.                      $response .= "<td>-275</td>";
  31.                      $response .= "<td>-17517</td>";
  32.                      $response .= "<td><a href='#' rel='".$_POST['value']."' onClick='openInfoAgent(this);'>".$_POST['value']."</a></td>";
  33.                      $response .= "</tr>"; 
  34.                }
Alguna ayudita con este error?
  #2 (permalink)  
Antiguo 10/01/2014, 11:01
Avatar de luis010182  
Fecha de Ingreso: julio-2009
Ubicación: Argentina - Capital Federal
Mensajes: 382
Antigüedad: 14 años, 9 meses
Puntos: 27
Respuesta: Error en consulta a la b.d con PHP y PDO

esta usando funciones especificas de sql server
por ejemplo el CONVERT() en mysql http://dev.mysql.com/doc/refman/5.0/...t-convert.html
para ver mejor los errores deberias usar un cliente mysql, ya que no son errores PHP sino de sintasis SQL_
  #3 (permalink)  
Antiguo 10/01/2014, 11:03
Avatar de adryan310  
Fecha de Ingreso: septiembre-2012
Mensajes: 450
Antigüedad: 11 años, 7 meses
Puntos: 3
Pregunta Respuesta: Error en consulta a la b.d con PHP y PDO

Amigo gracias por tu respuesta, pero entonces la pregunta es... puedo o no usar el convert en las consultas desde php ?

Nota: estoy usando SQL-SERVER.
  #4 (permalink)  
Antiguo 10/01/2014, 11:10
Avatar de gnzsoloyo
Moderador criollo
 
Fecha de Ingreso: noviembre-2007
Ubicación: Actualmente en Buenos Aires (el enemigo ancestral)
Mensajes: 23.324
Antigüedad: 16 años, 4 meses
Puntos: 2658
Respuesta: Error en consulta a la b.d con PHP y PDO

Cita:
PHP Fatal error: Uncaught exception 'PDOException'
Básicamente se está dando una excepción que no has capturado.
Antes de avanzar, usa un buen manejo de excepciones, que pDO lo tiene, y de esa forma al menos podrás recuperar el error de ejecución que se está presentando.
Por lo demás, San Google responde:
Cita:
SQLSTATE[24000]:
No cursor was open on the StatementHandle. (This is returned only by an ODBC 3.x driver.)
__________________
¿A quién le enseñan sus aciertos?, si yo aprendo de mis errores constantemente...
"El problema es la interfase silla-teclado." (Gillermo Luque)
  #5 (permalink)  
Antiguo 10/01/2014, 11:12
Avatar de luis010182  
Fecha de Ingreso: julio-2009
Ubicación: Argentina - Capital Federal
Mensajes: 382
Antigüedad: 14 años, 9 meses
Puntos: 27
Respuesta: Error en consulta a la b.d con PHP y PDO

Cita:
Iniciado por adryan310 Ver Mensaje
Amigo gracias por tu respuesta, pero entonces la pregunta es... puedo o no usar el convert en las consultas desde php ?

Nota: estoy usando SQL-SERVER.
Si pero siempre respetando la sintasis de SQL de la base de datos que estes usando.
Lo unico que haces en PHP es armar un string(SQL), que envias a la base. La base de datos es la que se encarga de interpretar la sintaxis.
Las distintas bases de datos tiene funciones o forma de sintaxis especificas, junto al SQL generico.
  #6 (permalink)  
Antiguo 10/01/2014, 11:32
Avatar de adryan310  
Fecha de Ingreso: septiembre-2012
Mensajes: 450
Antigüedad: 11 años, 7 meses
Puntos: 3
Pregunta Respuesta: Error en consulta a la b.d con PHP y PDO

Entiendo amigo pues esa consulta primero la probe en SQL-SERVER y me funciono bien, pero cuando la ejecute desde mi PHP no me funko y no tengo idea del por que ya que soy algo nuevo en PHP y estoy practicando para aprender mas sobre esto. Agrege lo siguiente para ver la exception pero me imprime el mismo error que puse en rojo al inicio del post...

PHP:
Código PHP:
 try{
               
$strDataGames $strConnect->query$strQueryGames );    
               
               while(
$dataGames $strDataGames->fetch(PDO::FETCH_ASSOC)){
                     
$response  "<tr>";
                     
$response .= "<td>".$dataGames['Time']."</td>";
                     
$response .= "<td>".$dataGames['NumGame']."</td>";
                     
$response .= "<td>".$dataGames['Teams']."</td>";
                     
$response .= "<td>".$dataGames['PeriodDescription']."</td>";
                     
$response .= "<td>".$dataGames['Score']."</td>";
                     
$response .= "<td>".$dataGames['Tickets']."</td>";
                     
$response .= "<td>".$dataGames['Risk']."</td>";
                     
$response .= "<td>-275</td>";
                     
$response .= "<td>-17517</td>";
                     
$response .= "<td><a href='#' rel='".$_POST['value']."' onClick='openInfoAgent(this);'>".$_POST['value']."</a></td>";
                     
$response .= "</tr>";    
               }
            }catch(
PDOException $e){
                
error_log("class->search.php->PDOException = ".$e);
            } 
  #7 (permalink)  
Antiguo 10/01/2014, 12:48
Avatar de luis010182  
Fecha de Ingreso: julio-2009
Ubicación: Argentina - Capital Federal
Mensajes: 382
Antigüedad: 14 años, 9 meses
Puntos: 27
Respuesta: Error en consulta a la b.d con PHP y PDO

listo, vos ejecutas lo mismo en sql server y funcion, pero cuando lo haces desde PHP no funciona.
Si es eso solo tenes que hacer un echo de $strQueryGames y el copia el sql y lo ejecutas en sql server. Ahi vas a ver el error.

Es con la unica consulta que tenes problemas? Hiciste otra mas sencilla y funcionaba?
  #8 (permalink)  
Antiguo 10/01/2014, 13:46
Avatar de adryan310  
Fecha de Ingreso: septiembre-2012
Mensajes: 450
Antigüedad: 11 años, 7 meses
Puntos: 3
Pregunta Respuesta: Error en consulta a la b.d con PHP y PDO

Amigo ya vi cual es el error mira:

Tengo este codigo que me valida que el agente a buscar exista:
Código PHP:
$strQueryAgent "SELECT COUNT(*) AS 'CantRows', A.[IdAgent] FROM AGENT A WHERE A.[Agent] = '".$_POST['value']."' GROUP BY A.[IdAgent]";

$strDataAgent $strConnect->query$strQueryAgent );    
  
      
$dataAgent    $strDataAgent->fetch(PDO::FETCH_ASSOC);
      
$numRows      $dataAgent['CantRows'];
     
$IdAgent      $dataAgent['IdAgent']; 
Despues de eso yo hago la busqueda de todos los datos que deseo:
Código PHP:
if ($numRows 0) { 
     
$conn->close(); // libero la conexion           
               
$yesterday date('Y-m-d')." 00:00:01";
               
$today     date('Y-m-d')." 23:59:59";
                 
               
$strQueryGames "SELECT CONVERT(VARCHAR(8), G.[GradedDate] , 108) AS 'Time', 
                                        CONVERT(VARCHAR(MAX),G.[VisitorNumber]) + '/' + CONVERT(VARCHAR(MAX),G.[HomeNumber]) AS 'NumGame', G.[VisitorTeam] + ' @ ' +G.[HomeTeam] AS 'Teams', P.[PeriodDescription],
                                        CONVERT(VARCHAR(MAX),G.[VisitorScore]) + ' - ' + CONVERT(VARCHAR(MAX),G.[HomeScore]) AS 'Score', COUNT(*) AS 'Tickets',
                                        SUM(H.[RiskAmount]) AS 'Risk'
                                 FROM WAGERHEADER H, WAGERDETAIL D, GAME G, PERIOD P
                                 WHERE H.[IdWager] = D.[IdWager] AND 
                                       D.[IdGame]  = G.[IdGame]  AND 
                                       H.[SettledDate] >= CONVERT(datetime,('"
.$yesterday."')) AND 
                                       H.[SettledDate] <= CONVERT(datetime,('"
.$today."')) AND
                                       D.[IdSport] = P.[IdSport] AND
                                       D.[Period]  = P.[NumberOfPeriod] AND 
                                       H.[IdAgent] = 7 "
.
                                 GROUP BY G.[GradedDate], G.[VisitorNumber], G.[HomeNumber], G.[VisitorTeam], G.[HomeNumber], G.[HomeTeam], P.[PeriodDescription], G.[VisitorScore], G.[HomeScore]"
;
               
               
//error_log("class->search.php->strQueryGames = ".$strQueryGames);
            
try{
               
$strDataGames $strConnect->query$strQueryGames );    
               
               while(
$dataGames $strDataGames->fetch(PDO::FETCH_ASSOC)){
                     
$response  "<tr>";
                     
$response .= "<td>".$dataGames['Time']."</td>";
                     
$response .= "<td>".$dataGames['NumGame']."</td>";
                     
$response .= "<td>".$dataGames['Teams']."</td>";
                     
$response .= "<td>".$dataGames['PeriodDescription']."</td>";
                     
$response .= "<td>".$dataGames['Score']."</td>";
                     
$response .= "<td>".$dataGames['Tickets']."</td>";
                     
$response .= "<td>$".$dataGames['Risk']."</td>";
                     
$response .= "<td>-275</td>";
                     
$response .= "<td>-17517</td>";
                     
$response .= "<td><a href='#' rel='".$_POST['value']."' onClick='openInfoAgent(this);'>".$_POST['value']."</a></td>";
                     
$response .= "</tr>";    
               }
            }catch(
PDOException $e){
                
error_log("class->search.php->PDOException = ".$e);
            }
    }else{
                     
$response  "<tr>";
                     
$response .= "<td colspan='10'><span class='alert-no-data'>No data to display</span></td>";
                     
$response .= "</tr>";    
          }
                        
$conn->close();
     
                echo 
$response
El problema es que cuando hago la primera consulta esta queda en ejecucion y debo cerrarla pero aun asi me sigue dando error si quito la primera consulta la segunda funciona bien pero debo de validar lo primero entonces no se xq el error persiste si ya libere la conexion ?
  #9 (permalink)  
Antiguo 10/01/2014, 14:06
Avatar de adryan310  
Fecha de Ingreso: septiembre-2012
Mensajes: 450
Antigüedad: 11 años, 7 meses
Puntos: 3
De acuerdo Respuesta: Error en consulta a la b.d con PHP y PDO

Investigando un poco descubri que con este comando se libera la consulta anterior y podemos proceder sin problemas a ejecutar la consulta siguiente...
Código PHP:
$strQueryAgent "SELECT COUNT(*) AS 'CantRows', A.[IdAgent] FROM AGENT A WHERE A.[Agent] = '".$_POST['value']."' GROUP BY A.[IdAgent]"

$strDataAgent $strConnect->query$strQueryAgent );     
   
      
$dataAgent    $strDataAgent->fetch(PDO::FETCH_ASSOC); 
      
$numRows      $dataAgent['CantRows']; 
      
$IdAgent      $dataAgent['IdAgent'];
      
$strDataAgent->closeCursor(); 
Espero que a alguien que se encuentre en mi misma situacion les pueda ayudar esto

Etiquetas: pdo, select, sql
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 06:31.