PHP의 PDO 작업

Jun 05, 2018 pm 05:18 PM
pdo php

이 글은 주로 PHP의 PDO 연산을 소개하는데, 이는 특정 참고 가치가 있습니다. 이제는 모든 사람과 공유합니다. 도움이 필요한 친구들이 참고할 수 있습니다

PHP 데이터 객체
소개
설치/구성
요구 사항
설치
런타임 구성
리소스 유형
사전 정의된 상수
연결 및 연결 관리
트랜잭션 및 자동 커밋
준비된 문 및 저장 프로시저
오류 및 오류 처리
대형 객체(LOB)
PDO — PDO 클래스
PDO::beginTransaction — 트랜잭션 시작
PDO: :commit — 트랜잭션 커밋
PDO::__construct — 데이터베이스 연결을 나타내는 PDO 인스턴스 생성
PDO::errorCode — 데이터베이스 핸들의 마지막 작업과 관련된 SQLSTATE 가져오기
PDO::errorInfo — 관련된 확장 오류 정보 가져오기 데이터베이스 핸들의 마지막 작업
PDO::exec — SQL 문을 실행하고 영향을 받은 행 수 반환
PDO::getAttribute — 데이터베이스 연결 속성 검색
PDO::getAvailableDrivers — 사용 가능한 드라이버 배열 반환
PDO::inTransaction — 트랜잭션 내에 있는지 확인합니다.
PDO::lastInsertId — 마지막으로 삽입된 행의 ID 또는 시퀀스 값을 반환합니다.
PDO::prepare — 실행할 명령문을 준비하고 명령문 객체를 반환합니다.
PDO::query — 실행 결과 세트를 PDOStatement 객체로 반환하는 SQL 문
PDO::quote — 쿼리에 사용할 문자열을 인용합니다.
PDO::rollBack — 트랜잭션 롤백
PDO::setAttribute — 속성 설정
PDOStatement — PDOStatement 클래스
PDOStatement::bindColumn — 열을 PHP 변수에 바인딩
PDOStatement::bindParam — 매개변수를 지정된 변수 이름에 바인딩
PDOStatement::bindValue — 값을 매개변수에 바인딩
PDOStatement::closeCursor — 커서를 닫습니다. 명령문을 다시 실행할 수 있다는 것입니다.
PDOStatement::columnCount — 결과 집합의 열 수를 반환합니다.
PDOStatement::debugDumpParams — SQL 전처리 명령을 인쇄합니다.
PDOStatement::errorCode — 마지막 문 핸들 작업과 관련된 SQLSTATE를 가져옵니다.
PDOStatement::errorInfo — last 문 핸들 작업과 관련된 확장된 오류 정보
PDOStatement::execute — 준비된 문 실행
PDOStatement::fetch — 결과 집합에서 다음 행 가져오기
PDOStatement::fetchAll — 결과 집합의 모든 행을 포함하는 배열 반환
PDOStatement:: fetchColumn — 결과 세트의 다음 행에서 단일 열을 반환합니다.
PDOStatement::fetchObject — 다음 줄을 가져와서 객체로 반환합니다.
PDOStatement::getAttribute — 문 속성 검색
PDOStatement::getColumnMeta — 결과 집합의 열에 대한 메타데이터 반환
PDOStatement::nextRowset — 다중 행 집합 문 핸들에서 다음 행 집합으로 진행
PDOStatement::rowCount — 개수 반환 이전 SQL 문에 의해 영향을 받은 행
PDOStatement::setAttribute — 문 속성을 설정합니다.
PDOStatement::setFetchMode — 문에 대한 기본 가져오기 모드를 설정합니다.
PDOException — PDOException 예외 클래스
PDO 드라이버
CUBRID(PDO) — CUBRID 함수(PDO_CUBRID)
MS SQL Server(PDO) — Microsoft SQL Server 및 Sybase 함수(PDO_DBLIB)
Firebird(PDO) — Firebird 함수(PDO_FIREBIRD)
IBM (PDO) — IBM 함수(PDO_IBM)
Informix(PDO) — Informix 함수(PDO_INFORMIX)
MySQL(PDO) — MySQL 함수(PDO_MYSQL)
MS SQL Server(PDO) — Microsoft SQL Server 함수(PDO_SQLSRV)
Oracle(PDO) ) — Oracle 함수(PDO_OCI)
ODBC 및 DB2(PDO) — ODBC 및 DB2 함수(PDO_ODBC)
PostgreSQL(PDO) — PostgreSQL 함수(PDO_PGSQL)
SQLite(PDO) — SQLite 함수(PDO_SQLITE)
4D(PDO) — 4D 함수(PDO_4D)

<?php
Class SafePDO extends PDO {

        public static function exception_handler($exception) {
            // Output the exception details
            die(&#39;Uncaught exception: &#39;. $exception->getMessage());
        }      
          public function __construct($dsn, $username=&#39;&#39;, $password=&#39;&#39;, $driver_options=array()) {

            // Temporarily change the PHP exception handler while we . . .
            set_exception_handler(array(__CLASS__, &#39;exception_handler&#39;));            
            // . . . create a PDO object
            parent::__construct($dsn, $username, $password, $driver_options);            
            // Change the exception handler back to whatever it was before
            restore_exception_handler();
        }

}
?>
Para usarla hay que crear un archivo PHP llamado por ejemplo SafePDO con el contenido del archivo citado m??s arriba.

Y en cuando tengamos que conectar a nuestra base de datos:<?php 
    include_once(&#39;SafePDO.php&#39; );    
    $dsn = &#39;mysql:host=&#39;.DB_HOST.&#39;;dbname=&#39;.DB_NAME.&#39;;charset=utf8&#39;;    
    $opt = array(
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::MYSQL_ATTR_INIT_COMMAND => &#39;SET NAMES utf8&#39;
        );    
        $pdo = new SafePDO($dsn,DB_USER,DB_PASSWORD);?>[#2] matthew at button-mashers dot net [2014-05-07 23:31:23]

When using prepared statements there is no official PDO feature to show you the final query string that is submitted to a database complete with the parameters you passed.

Use this simple function for debugging. The values you are passing may not be what you expect.
<?php
//Sample query string$query = "UPDATE users SET name = :user_name WHERE id = :user_id";
//Sample parameters$params = [&#39;:user_name&#39; => &#39;foobear&#39;, &#39;:user_id&#39; => 1001];
function build_pdo_query($string, $array) {
    //Get the key lengths for each of the array elements.
    $keys = array_map(&#39;strlen&#39;, array_keys($array));    
    //Sort the array by string length so the longest strings are replaced first.
    array_multisort($keys, SORT_DESC, $array);    
    foreach($array as $k => $v) {        
    //Quote non-numeric values.
        $replacement = is_numeric($v) ? $v : "&#39;{$v}&#39;";        
        //Replace the needle.
        $string = str_replace($k, $replacement, $string);
    }    
    return $string;
}
echo build_pdo_query($query, $params);    
//UPDATE users SET name = &#39;foobear&#39; WHERE id = 1001?>[#3] Sbastien Gourmand [2013-07-08 10:19:25]

Merge the prepare() and execute() in one function like a sprintf().
And like sprintf, I choose to use unnamed args (?) ;)

you could still use old insecure query() ( not prepared ) with renamed function :)
<?php
class MyPDO extends PDO{

    const PARAM_host=&#39;localhost&#39;;    
    const PARAM_port=&#39;3306&#39;;    
    const PARAM_db_name=&#39;test&#39;;    
    const PARAM_user=&#39;root&#39;;    
    const PARAM_db_pass=&#39;&#39;;    
    public function __construct($options=null){
        parent::__construct(&#39;mysql:host=&#39;.MyPDO::PARAM_host.&#39;;port=&#39;.MyPDO::PARAM_port.&#39;;dbname=&#39;.MyPDO::PARAM_db_name,
MyPDO::PARAM_user,
MyPDO::PARAM_db_pass,$options);
    }    
    public function query($query){ 
    //secured query with prepare and execute
        $args = func_get_args();
        array_shift($args); 
        //first element is not an argument but the query itself, should removed

        $reponse = parent::prepare($query);        
        $reponse->execute($args);        
        return $reponse;

    }    
    public function insecureQuery($query){ 
    //you can use the old query at your risk ;) and should use secure quote() function with it
        return parent::query($query);
    }

}
$db = new MyPDO();$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$t1 = isset($_GET["t1"])?$_GET["t1"]:1; 
// need to be securised for injonction$t2 = isset($_GET["t2"])?$_GET["t2"]:2; 
// need to be securised for injonction$t3 = isset($_GET["t3"])?$_GET["t3"]:3; 
// need to be securised for injonction$ret = $db->query("SELECT * FROM table_test WHERE t1=? AND t2=? AND t3=?",$t1,$t2,$t3);
//$ret = $db->insecureQuery("SELECT * FROM table_test WHERE t1=".$db->quote($t1));
while ($o = $ret->fetch())
{    
echo $o->nom.PHP_EOL;
}
?>
[#4] lkmorlan at uwaterloo dot ca [2011-01-04 07:25:38]

You may also have to edit /etc/freetds.conf. Make sure the TDS version is recent, e.g., "tds version = 8.0".

[#5] lkmorlan at uwaterloo dot ca [2010-06-29 09:38:33]

This works to get UTF8 data from MSSQL:<?php$db = new PDO(&#39;dblib:host=your_hostname;dbname=your_db;charset=UTF-8&#39;, $user, $pass);?>[#6] jose at thezcompany dot com [2010-02-17 12:39:09]

I ran into a real annoying bug/feature when using PDO for SQL statements that use SQL user variables.  I was working on some logic for a Geo Proximity Search for an events-venues system (sharing is caring so it&#39;s below) and it just wouldn&#39;t take and the errors returned were garbage. The SQL was sound as I verified it.  So if you&#39;re having this issue, I hope this helps.  What you need to do is break apart the query into two...

From:
<?php
$sql="set @latitude=:lat;
set @longitude=:lon;
set @radius=20;

set @lng_min = @longitude - @radius/abs(cos(radians(@latitude))*69);
set @lng_max = @longitude + @radius/abs(cos(radians(@latitude))*69);
set @lat_min = @latitude - (@radius/69);
set @lat_max = @latitude + (@radius/69);

SELECT *,
3956 * 2 * ASIN(SQRT(POWER(SIN((@latitude - ABS(venue_lat)) * PI()/180 / 2),2) + COS(@latitude * PI()/180) * COS(ABS(venue_lat) * PI()/180) * POWER(SIN((@longitude - venue_lon) * PI()/180 / 2),2))) AS distance
FROM events LEFT JOIN venues ON venues.venue_id = events.venue_fk
WHERE (venue_lon BETWEEN @lng_min AND @lng_max)
AND (venue_lat BETWEEN @lat_min and @lat_max)
AND events.event_date >= CURDATE()
AND events.event_time >= CURTIME()
ORDER BY distance DESC;";$stmt = $this->_db->prepare($sql);$stmt->bindParam(&#39;:lat&#39;, $lat, PDO::PARAM_STR);$stmt->bindParam(&#39;:lon&#39;, $lon, PDO::PARAM_STR);$stmt->bindParam(&#39;:offset&#39;, $offset, PDO::PARAM_INT); 
$stmt->bindParam(&#39;:max&#39;, $max, PDO::PARAM_INT);$stmt->execute();?>  To:<?php$sql = "SET @latitude=:lat;
SET @longitude=:lon;
SET @radius=20;
SET @lng_min=@longitude - @radius/abs(cos(radians(@latitude))*69);
SET @lng_max=@longitude + @radius/abs(cos(radians(@latitude))*69);
SET @lat_min=@latitude - (@radius/69);
SET @lat_max=@latitude + (@radius/69);"; 

$this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);$stmt = $this->_db->prepare($sql);$stmt->bindParam(&#39;:lat&#39;, $lat, PDO::PARAM_STR);$stmt->bindParam(&#39;:lon&#39;, $lon, PDO::PARAM_STR);$stmt->execute();$sql = "SELECT *,
(3956 * 2 * ASIN(SQRT(POWER(SIN((@latitude - ABS(venue_lat)) * PI()/180 / 2),2) + COS(@latitude * PI()/180) * COS(ABS(venue_lat) * PI()/180) * POWER(SIN((@longitude - venue_lon) * PI()/180 / 2),2)))) AS distance
FROM events LEFT JOIN venues ON venues.venue_id = events.venue_fk
WHERE (venue_lon BETWEEN @lng_min AND @lng_max)
AND (venue_lat BETWEEN @lat_min and @lat_max)
AND events.event_date >= CURDATE()
AND events.event_time >= CURTIME()
ORDER BY distance DESC
LIMIT :offset,:max;";$stmt = $this->_db->prepare($sql); 
$stmt->bindParam(&#39;:offset&#39;, $offset, PDO::PARAM_INT); 
$stmt->bindParam(&#39;:max&#39;, $max, PDO::PARAM_INT);$stmt->execute();?>Hope this helps anyone out there!

[#7] paul dot maddox at gmail dot com [2009-08-27 05:54:14]

I decided to create a singleton wrapper for PDO that ensures only one instance is ever used.
It uses PHP 5.3.0&#39;s __callStatic functionality to pass on statically called methods to PDO.

This means you can just call it statically from anywhere without having to initiate or define the object.

Usage examples:<?php DB::exec("DELETE FROM Blah"); 

foreach( DB::query("SELECT * FROM Blah") as $row){ 
        print_r($row); 
} 
?>
Code:
<?php 
class DB { 

    private static $objInstance; 


    private function __construct() {}  


    private function __clone() {} 


    public static function getInstance(  ) { 

        if(!self::$objInstance){ 
            self::$objInstance = new PDO(DB_DSN, DB_USER, DB_PASS); 
            self::$objInstance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
        } 

        return self::$objInstance; 

    } # end method 


    final public static function __callStatic( $chrMethod, $arrArguments ) { 

        $objInstance = self::getInstance(); 

        return call_user_func_array(array($objInstance, $chrMethod), $arrArguments); 

    } # end method } 
?>
[#8] rijnzael at gmail dot com [2008-09-04 13:46:40]

If you plan on using prepared statements to issue a series of KILLs, think again.  PDO apparently does not support this, and will tell you, assuming you don&#39;t put any parameters in the statement (a situation in which it would be pointless to use prepared statements anyway).  If you do specify some ?-mark parameters, it will just spit out an error that doesn&#39;t help at all.

[#9] cmcculloh [2008-06-25 12:14:44]

It appears that PDO SQL statements can not make use of  comments. Or at least, when I was trying to use them with mine it was crashing without error and giving me a blank page (even though I surrounded with try catch block).

[#10] ob.php from daevel.fr [2007-12-30 12:57:48]

Be careful with PDO extends : if you use the smileaf&#39;s example, PDO will close the connection only at the end of the script, because of the "array( $this )" parameter used with the setAttribute() method.

Instead, I use only this :
    $this->setAttribute( PDO::ATTR_STATEMENT_CLASS, array( $this->statementClassName, array() ) );

And in prepare() and query() method you can populate the "dbh" if you really need it.

[#11] neonmandk at gmail dot com [2007-12-10 04:29:51]

If you will make a OBJ row from PDO you can use this eg.

$resKampange = $dbc->prepare( "SELECT * FROM Table LIMIT 1" );
$resKampange->execute();
$rowKampange = $resKampange->fetch( PDO::FETCH_OB );

echo $rowKampange->felt1;

Good lock :0)

[#12] Ostap [2007-12-03 02:08:04]

There is a book titled "Learning PHP Data Objects" written by Dennis Popel and published by Packt. There is a post with further links (ordering, reviews) at author&#39;s blog: http://www.onphp5.com/article/58

[#13] nospam dot list at unclassified dot de [2007-11-13 16:24:31]

When using persistent connections, pay attention not to leave the database connection in some kind of locked state. This can happen when you start a transaction by hand (i.e. not through the PDO->beginTransaction() method), possibly even acquire some locks (e.g. with "SELECT ... FOR UPDATE", "LOCK TABLES ..." or in SQLite with "BEGIN EXCLUSIVE TRANSACTION") and then your PHP script ends with a fatal error, unhandled exception or under other circumstances that lead to an unclean exit.

To use that database again, it may then be necessary to disable the persistence attribute to get a new database connection or restart the web server. (Persistent connections should not work with a PHP-CGI anyway.) It does not work (tested with PHP 5.2.3/WinXP and SQLite) to close a persistent database connection - it will not actually be closed but instead returned to PDO&#39;s connection pool.

The only thing you can do to resolve the lock as a regular user (I imagine) is to try and get all of your persistent connections in a single script and unlock the tables resp. end the transactions with the appropriate SQL statements ("UNLOCK TABLES" in MySQL, "ROLLBACK" for transactions). Should they fail, there is no problem, but one or some of them might succeed and thereby resolve your locking problem.

[#14] xorinox at vtxmail dot ch [2007-11-04 15:52:25]

I have seen a lot of user struggling with calling mysql procedures with in/out/inout parameters using bindParam. There seems to be a bug or missing feature within the mysql C api. This at least I could find out after reading a lot of posts at different places...

At the moment I workaround it like below. $con is a PDO object:
<?php
//in$proc = $con->prepare( "call proc_in( @i_param )" );
$con->query( "set @i_param = &#39;myValue&#39;" );
$proc->execute();
//out$proc = $con->prepare( "call proc_out( @o_param )" );
$proc->execute();$o_param = $con->query( "select @o_param" )->fetchColumn();
//inout$proc = $con->prepare( "call proc_inout( @io_param )" );
$con->query( "set @io_param = &#39;myValue&#39;" );$proc->execute();
$io_param = $con->query( "select @io_param" )->fetchColumn();
?>
[#15] Konstantin at Tokar dot ru [2007-10-16 08:34:21]

Example 5: 
<?php
try {  $dbh = new PDO(&#39;odbc:SAMPLE&#39;, &#39;db2inst1&#39;, &#39;ibmdb2&#39;,      array(PDO::ATTR_PERSISTENT => true));
....... 
} 
catch (Exception $e) {  
$dbh->rollBack();  
echo "Failed: " . $e->getMessage();
}
?> 
 We must change the last two lines to catch the error connecting to the database:

} catch (Exception $e) {
  echo "Failed: " . $e->getMessage();
  $dbh->rollBack();
}
?>

[#16] anton dot clarke at sonikmedia dot com [2007-09-02 12:12:59]

Not all PDO drivers return a LOB as a file stream; 
mysql 5 is one example. Therefore when streaming a mime typed object from the database you cannot use fpassthru.

The following is a modified example that works with a mysql database. (Tested FreeBSD v 6.2 with mysql 5.0.45 and php 5.2.3) 

<?php
ob_start();
$db = new PDO(&#39;mysql:host=localhost;dbname=<SOMEDB>&#39;, &#39;<USERNAME>&#39;, &#39;PASSWORD&#39;);
$stmt = $db->prepare("select contenttype, imagedata from images where id=?");
$stmt->execute(array($_GET[&#39;id&#39;]));
$stmt->bindColumn(1, $type, PDO::PARAM_STR, 256);
$stmt->bindColumn(2, $lob, PDO::PARAM_LOB);$stmt->fetch(PDO::FETCH_BOUND);
ob_clean();
header("Content-Type: $type");echo $lob; 
// fpassthru reports an error that $lob is not a stream so echo is used in place.ob_end_flush();
?>
Please note the inclusion of buffer control. I only needed this when using &#39;include&#39;,&#39;include_once&#39;,&#39;require&#39;, or &#39;require_once&#39; - my feeling is there is a subtle issue with those options as even an empty include file caused a buffer issue for me. === AND YES, I DID CHECK MY INCLUDE FILES DID NOT HAVE SPURIOUS WHITESPACE ETC OUTSIDE THE  <?php ?>  DELIMITERS! ===

[#17] metalim [2007-05-25 05:38:07]

From Oracle example:<?php$stmt->beginTransaction();$stmt->execute();$stmt->commit();?>PDOStatement has no beginTransaction(), nor commit(). Please fix documentation.

[#18] bart at mediawave dot nl [2007-05-23 07:57:00]

It seems MySQL doesn&#39;t support scrollable cursors. So unfortunately PDO::CURSOR_SCROLL wont work.

[#19] djlopez at gmx dot de [2007-03-12 05:04:53]

Note this:

Won&#39;t work:
$sth = $dbh->prepare(&#39;SELECT name, colour, calories FROM fruit WHERE ? < ?&#39;);THIS WORKS!
$sth = $dbh->prepare(&#39;SELECT name, colour, calories FROM fruit WHERE calories < ?&#39;);Parameters cannot be applied on column names!!

[#20] smileaf at smileaf dot org [2007-03-01 10:57:14]If you intend on extending PDOStatement and your using setAttribute(PDO::ATTR_STATEMENT_CLASS, ...)you must override the __construct() of your PDOStatement class.failure to do so will result in an error on any PDO::query() call.Warning: PDO::query() [function.PDO-query]: SQLSTATE[HY000]: General error: user-supplied statement does not accept constructor argumentsHere is a minimum PDO and PDOStatement class<?phpclass Database extends PDO {
    function __construct($dsn, $username="", $password="", $driver_options=array()) {
        parent::__construct($dsn,$username,$password, $driver_options);        
        $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array(&#39;DBStatement&#39;, array($this)));
    }
}class DBStatement extends PDOStatement {
    public $dbh;    
    protected function __construct($dbh) {
        $this->dbh = $dbh;
    }
}
?>
[#21] php at moechofe dot com [2007-02-17 11:52:59]Simple example to extends PDO
<?php
class connexion extends PDO{
  public $query = null;  
  public function prepare( $statement, $driver_options = array() )
  {
    $this->query = $statement;    
    return parent::prepare( $statement, $driver_options = array() );
  }  
  public function last_query()
  {
    return $this->query;
  }
}
class connexion_statement extends PDOStatement{
  protected $pdo;  protected function __construct($pdo)
  {
     $this->pdo = $pdo;
  }  
  // return first column of first row
  public function fetchFirst()
  {
    $row = $this->fetch( PDO::FETCH_NUM );    
    return $row[0];
  }  
  // real cast number
  public function fetch( $fetch_style = null, $cursor_orientation = null, $cursor_offset = null )
  {
    $row = parent::fetch( $fetch_style, $cursor_orientation, $cursor_offset );    
    if( is_array($row) )      
    foreach( $row as $key => $value )        
    if( strval(intval($value)) === $value )          
    $row[$key] = intval($value);        
    elseif( strval(floatval($value)) === $value )          
    $row[$key] = floatval($value);    return $row;
  }  
  // permit $prepare->execute( $arg1, $arg2, ... );
  public function execute( $args = null )
  {
    if( is_array( $args ) )      
    return parent::execute( $args );    else
    {      
    $args = func_get_args();      
    return eval( &#39;return parent::execute( $args );&#39; );
    }
  }  public function last_query()
  {
    return $this->pdo->last_query();
  }
}
$pdo = new connexion( ... );
$pdo->setAttribute( PDO::ATTR_STATEMENT_CLASS, array( &#39;connexion_statement&#39;, array($pdo) ) );
?>
[#22] webform at aouie dot website [2006-09-27 23:38:02]If you use $dbh = new PDO(&#39;pgsql:host=localhost;
dbname=test_basic01&#39;, $user, $pass); 
and you get the following error:PHP Fatal error:  Uncaught exception &#39;PDOException&#39; with message &#39;SQLSTATE[08006] [7] could not connect to server: Connection refused\n\tIs the server running on host "localhost" and accepting\n\tTCP/IP connections on port 5432?&#39;then as pointed out under pg_connect at: http://www.php.net/manual/en/function.pg-connect.php#38291 ******you should try to leave the host= and port= parts out of the connection string. This sounds strange, but this is an "option" of Postgre. If you have not activated the TCP/IP port in postgresql.conf then postgresql doesn&#39;t accept any incoming requests from an TCP/IP port. If you use host= in your connection string you are going to connect to Postgre via TCP/IP, so that&#39;s not going to work. If you leave the host= part out of your connection string you connect to Postgre via the Unix domain sockets, which is faster and more secure, but you can&#39;t connect with the database via any other PC as the localhost.******Sincerely,Aouie[#23] djlopez at gmx dot de [2006-08-30 14:56:04]Please note this:Won&#39;t work:$sth = $dbh->prepare(&#39;SELECT name, colour, calories FROM ?  WHERE calories < ?&#39;);THIS WORKS!
$sth = $dbh->prepare(&#39;SELECT name, colour, calories FROM fruit WHERE calories < ?&#39;);The parameter cannot be applied on table names!!

[#24] paulius_k at yahoo dot com [2006-07-25 08:42:58]If you need to get Output variable from MSSQL stored procedure, try this :-- PROCEDURECREATE PROCEDURE spReturn_Int @err int OUTPUT ASSET @err = 11GO$sth = $dbh->prepare("EXECUTE spReturn_Int ?");
$sth->bindParam(1, $return_value, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT);
$sth->execute();
print "procedure returned $return_value\n";

[#25] nicolas at serpe dot org [2006-05-21 12:36:29]

I use PDO with the ODBC driver to query stored procedures in a MS SQL Server 2005 Database under Windows XP Professional with IIS 5 and PHP 5.1.4. You may have the same problems with a different configuration.

I experienced 2 very time consuming errors:

1. The first one is when you return the result of a SELECT query, and you get the following clueless message:
>>> Fatal error: Uncaught exception &#39;PDOException&#39; with message &#39;SQLSTATE[24000]: Invalid cursor state: 0 [Microsoft][SQL Native Client]Invalid cursor state (SQLFetchScroll[0] at ext\pdo_odbc\odbc_stmt.c:372)&#39; in (YOUR_TRACE_HERE) <<<Your exact message may be different, the part to pay attention to is "Invalid cursor state".-> I found that I had this error because I didn&#39;t include "SET NOCOUNT ON" in the *body* of the stored procedure. By default the server returns a special piece of information along with the results, indicating how many rows were affected by the stored procedure, and that&#39;s not handled by PDO.

2. The second error I had was:
>>> Fatal error: Uncaught exception &#39;PDOException&#39; with message &#39;SQLSTATE[22003]: Numeric value out of range: 0 [Microsoft][SQL Native Client]Numeric value out of range (SQLFetchScroll[0] at ext\pdo_odbc\odbc_stmt.c:372)&#39; in (YOUR_TRACE_HERE) <<<Another meaningless error "Numeric value out of range"... -> I was actually returning a date datatype (datetime or smalldatetime) "as is", that is, without converting it to varchar before including it in the result set... I don&#39;t know if PDO is responsible for converting it to a PHP datatype, but it doesn&#39;t. Convert it before it reaches PHP.

[#26] pokojny at radlight dot com [2006-04-23 08:50:58]

I wanted to extend PDO class to store statistics of DB usage, and I faced some problems. I wanted to count number of created statements and number of their executings. So PDOStatement should have link to PDO that created it and stores the statistical info. The problem was that I didn&#39;t knew how PDO creates PDOStatement (constructor parameters and so on), so I have created these two classes:<?php

    class PDOp {
        protected $PDO;        
        public $numExecutes;        
        public $numStatements;        
        public function __construct($dsn, $user=NULL, $pass=NULL, $driver_options=NULL) {
            $this->PDO = new PDO($dsn, $user, $pass, $driver_options);            
            $this->numExecutes = 0;            
            $this->numStatements = 0;
        }        
        public function __call($func, $args) {
            return call_user_func_array(array(&$this->PDO, $func), $args);
        }        
        public function prepare() {
            $this->numStatements++;            
            $args = func_get_args();            
            $PDOS = call_user_func_array(array(&$this->PDO, &#39;prepare&#39;), $args);            
            return new PDOpStatement($this, $PDOS);
        }        public function query() {
            $this->numExecutes++;            
            $this->numStatements++;            
            $args = func_get_args();            
            $PDOS = call_user_func_array(array(&$this->PDO, &#39;query&#39;), $args);            
            return new PDOpStatement($this, $PDOS);
        }        
        public function exec() {
            $this->numExecutes++;            
            $args = func_get_args();            
            return call_user_func_array(array(&$this->PDO, &#39;exec&#39;), $args);
        }
    }    class PDOpStatement implements IteratorAggregate {
        protected $PDOS;        
        protected $PDOp;        
        public function __construct($PDOp, $PDOS) {
            $this->PDOp = $PDOp;            
            $this->PDOS = $PDOS;
        }        
        public function __call($func, $args) {
            return call_user_func_array(array(&$this->PDOS, $func), $args);
        }        
        public function bindColumn($column, &$param, $type=NULL) {
            if ($type === NULL)                
            $this->PDOS->bindColumn($column, $param);            
            else
                $this->PDOS->bindColumn($column, $param, $type);
        }        
        public function bindParam($column, &$param, $type=NULL) {
            if ($type === NULL)                
            $this->PDOS->bindParam($column, $param);            
            else
                $this->PDOS->bindParam($column, $param, $type);
        }        
        public function execute() {
            $this->PDOp->numExecutes++;            
            $args = func_get_args();            
            return call_user_func_array(array(&$this->PDOS, &#39;execute&#39;), $args);
        }        
        public function __get($property) {
            return $this->PDOS->$property;
        }        
        public function getIterator() {
            return $this->PDOS;
        }
   }
   ?>
   Classes have properties with original PDO and PDOStatement objects, which are providing the functionality to PDOp and PDOpStatement.
From outside, PDOp and PDOpStatement look like PDO and PDOStatement, but also are providing wanted info.

[#27] keyvez at hotmail dot com [2006-03-09 12:49:40]

PDO doesn&#39;t return OUTPUT params from mssql stored procedures<?php
    $Link = new PDO(&#39;mssql:host=sqlserver;dbname=database&#39;, &#39;username&#39;,&#39;password&#39;);    
    $ErrorCode = 0;    $Stmt = $Link->prepare(&#39;p_sel_all_termlength ?&#39;);    
    $Stmt->bindParam(1,$ErrorCode,PDO::PARAM_INT,4);    
    $Stmt->execute();    
    echo "Error = " . $ErrorCode . "\n";
    ?>
[#28] www.navin.biz [2006-02-19 10:16:04]

Below is an example of extending PDO & PDOStatement classes:<?phpclass Database extends PDO{
    function __construct()
    {
        parent::__construct(&#39;mysql:dbname=test;host=localhost&#39;, &#39;root&#39;, &#39;&#39;);        $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array(&#39;DBStatement&#39;, array($this)));
    }
}class DBStatement extends PDOStatement{
    public $dbh;    protected function __construct($dbh)
    {
        $this->dbh = $dbh;        $this->setFetchMode(PDO::FETCH_OBJ);
    }    public function foundRows()
    {
        $rows = $this->dbh->prepare(&#39;SELECT found_rows() AS rows&#39;, array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE));        $rows->execute();        $rowsCount = $rows->fetch(PDO::FETCH_OBJ)->rows;        $rows->closeCursor();        return $rowsCount;
    }
}?>
[#29] Dariusz Kielar [2006-02-12 22:50:42]

I found a nice pdo modification written in php called Open Power Driver. It has identical API with the original, but allows you to cache query results: http://www.openpb.net/opd.php

[#30] shaolin at adf dot nu [2006-02-07 18:18:50]

If your having problems re-compiling PHP with PDO as shared module try this.

--enable-pdo=shared
--with-pdo-mysql=shared,/usr/local/mysql
--with-sqlite=shared
--with-pdo-sqlite=shared

1. If PDO is built as a shared modules, all PDO drivers must also be
built as shared modules.
2. If ext/pdo_sqlite is built as a shared module, ext/sqlite must also
be built as a shared module.
3. In the extensions entries, if ext/pdo_sqlite is built as a shared
module, php.ini must specify pdo_sqlite first, followed by sqlite.

[#31] tomasz dot wasiluk at gmail dot com [2006-01-01 04:09:06]

Watch out for putting spaces in the DSN
mysql:host=localhost;dbname=test works
mysql: host = localhost; dbname=test works
mysql: host = localhost; dbname = test doesn&#39;t work...

[#32] Matthias Leuffen [2005-12-04 01:36:13]

Hi there,

because of ZDE 5.0 and other PHP-IDEs do not seem to support PDO from PHP5.1 in code-completion-database yet, I wrote a code-completion alias for the PDO class.
NOTE: This Class has no functionality and should be only included to your IDE-Project but NOT(!) to your application.<?phpclass PDO {const ERR_ALREADY_EXISTS = 0;const ERR_CANT_MAP = 0;const ERR_NOT_FOUND = 0;const ERR_SYNTAX = 0;const ERR_CONSTRAINT = 0;const ERR_MISMATCH = 0;const ERR_DISCONNECTED = 0;const ERR_NONE = 0;const ATTR_ERRMODE = 0;const ATTR_TIMEOUT = 0;const ATTR_AUTOCOMMIT = 0;const ATTR_PERSISTENT = 0;// Values for ATTR_ERRMODEconst ERRMODE_EXCEPTION = 0;const ERRMODE_WARNING = 0;const FETCH_ASSOC = 0;const FETCH_NUM = 0;const FETCH_OBJ = 0;public function __construct($uri, $user, $pass, $optsArr) {}public function prepare ($prepareString) {}public function query ($queryString) {}public function quote ($input) {}public function exec ($statement) {}public function lastInsertId() {}public function beginTransaction () {}public function commit () {}public function rollBack () {}public function errorCode () {}public function errorInfo () {}   
}class PDOStatement {public function bindValue ($no, $value) {}public function fetch () {}public function nextRowset () {}public function execute() {}public function errorCode () {}public function errorInfo () {}public function rowCount () {}public function setFetchMode ($mode) {}public function columnCount () {}
}

[#33] ng4rrjanbiah at rediffmail dot com [2005-03-15 22:53:49]Some useful links on PDO:1. PDO Wiki ( http://wiki.cc/php/PDO )2. Introducing PHP Data Objects ( http://netevil.org/downloads/Introducing-PDO.ppt ), [226 KB], Wez Furlong, 2004-09-243. The PHP 5 Data Object (PDO) Abstraction Layer and Oracle ( http://www.oracle.com/technology/pub/articles/php_experts/otn_pdo_oracle5.html ), [60.85 KB], Wez Furlong, 2004-07-284. PDO - Why it should not be part of core PHP! ( http://www.akbkhome.com/blog.php/View/55/ ), Critical review, [38.63 KB], Alan Knowles, 2004-10-22
로그인 후 복사

관련 권장 사항:

PHP는 pdo를 사용하여 액세스 데이터베이스에 연결하고 루프를 사용하여 데이터 작업을 표시합니다

위 내용은 PHP의 PDO 작업의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 채팅 명령 및 사용 방법
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Dec 24, 2024 pm 04:42 PM

PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 Dec 20, 2024 am 11:31 AM

VS Code라고도 알려진 Visual Studio Code는 모든 주요 운영 체제에서 사용할 수 있는 무료 소스 코드 편집기 또는 통합 개발 환경(IDE)입니다. 다양한 프로그래밍 언어에 대한 대규모 확장 모음을 통해 VS Code는

이전에 몰랐던 후회되는 PHP 함수 7가지 이전에 몰랐던 후회되는 PHP 함수 7가지 Nov 13, 2024 am 09:42 AM

숙련된 PHP 개발자라면 이미 그런 일을 해왔다는 느낌을 받을 것입니다. 귀하는 상당한 수의 애플리케이션을 개발하고, 수백만 줄의 코드를 디버깅하고, 여러 스크립트를 수정하여 작업을 수행했습니다.

PHP에서 HTML/XML을 어떻게 구문 분석하고 처리합니까? PHP에서 HTML/XML을 어떻게 구문 분석하고 처리합니까? Feb 07, 2025 am 11:57 AM

이 튜토리얼은 PHP를 사용하여 XML 문서를 효율적으로 처리하는 방법을 보여줍니다. XML (Extensible Markup Language)은 인간의 가독성과 기계 구문 분석을 위해 설계된 다목적 텍스트 기반 마크 업 언어입니다. 일반적으로 데이터 저장 AN에 사용됩니다

JWT (JSON Web Tokens) 및 PHP API의 사용 사례를 설명하십시오. JWT (JSON Web Tokens) 및 PHP API의 사용 사례를 설명하십시오. Apr 05, 2025 am 12:04 AM

JWT는 주로 신분증 인증 및 정보 교환을 위해 당사자간에 정보를 안전하게 전송하는 데 사용되는 JSON을 기반으로 한 개방형 표준입니다. 1. JWT는 헤더, 페이로드 및 서명의 세 부분으로 구성됩니다. 2. JWT의 작업 원칙에는 세 가지 단계가 포함됩니다. JWT 생성, JWT 확인 및 Parsing Payload. 3. PHP에서 인증에 JWT를 사용하면 JWT를 생성하고 확인할 수 있으며 사용자 역할 및 권한 정보가 고급 사용에 포함될 수 있습니다. 4. 일반적인 오류에는 서명 검증 실패, 토큰 만료 및 대형 페이로드가 포함됩니다. 디버깅 기술에는 디버깅 도구 및 로깅 사용이 포함됩니다. 5. 성능 최적화 및 모범 사례에는 적절한 시그니처 알고리즘 사용, 타당성 기간 설정 합리적,

문자열로 모음을 계산하는 PHP 프로그램 문자열로 모음을 계산하는 PHP 프로그램 Feb 07, 2025 pm 12:12 PM

문자열은 문자, 숫자 및 기호를 포함하여 일련의 문자입니다. 이 튜토리얼은 다른 방법을 사용하여 PHP의 주어진 문자열의 모음 수를 계산하는 방법을 배웁니다. 영어의 모음은 A, E, I, O, U이며 대문자 또는 소문자 일 수 있습니다. 모음이란 무엇입니까? 모음은 특정 발음을 나타내는 알파벳 문자입니다. 대문자와 소문자를 포함하여 영어에는 5 개의 모음이 있습니다. a, e, i, o, u 예 1 입력 : String = "Tutorialspoint" 출력 : 6 설명하다 문자열의 "Tutorialspoint"의 모음은 u, o, i, a, o, i입니다. 총 6 개의 위안이 있습니다

PHP에서 늦은 정적 결합을 설명하십시오 (정적 : :). PHP에서 늦은 정적 결합을 설명하십시오 (정적 : :). Apr 03, 2025 am 12:04 AM

정적 바인딩 (정적 : :)는 PHP에서 늦은 정적 바인딩 (LSB)을 구현하여 클래스를 정의하는 대신 정적 컨텍스트에서 호출 클래스를 참조 할 수 있습니다. 1) 구문 분석 프로세스는 런타임에 수행됩니다. 2) 상속 관계에서 통화 클래스를 찾아보십시오. 3) 성능 오버 헤드를 가져올 수 있습니다.

php magic 방법 (__construct, __destruct, __call, __get, __set 등)이란 무엇이며 사용 사례를 제공합니까? php magic 방법 (__construct, __destruct, __call, __get, __set 등)이란 무엇이며 사용 사례를 제공합니까? Apr 03, 2025 am 12:03 AM

PHP의 마법 방법은 무엇입니까? PHP의 마법 방법은 다음과 같습니다. 1. \ _ \ _ Construct, 객체를 초기화하는 데 사용됩니다. 2. \ _ \ _ 파괴, 자원을 정리하는 데 사용됩니다. 3. \ _ \ _ 호출, 존재하지 않는 메소드 호출을 처리하십시오. 4. \ _ \ _ get, 동적 속성 액세스를 구현하십시오. 5. \ _ \ _ Set, 동적 속성 설정을 구현하십시오. 이러한 방법은 특정 상황에서 자동으로 호출되어 코드 유연성과 효율성을 향상시킵니다.

See all articles