2014-11-10 2 views
1

Я использую PDO для подключения к моей базе данных, и я не знаю, какой метод лучше, чем другой для UPDATE, DELETE и INSERT, PDO :: exec или PDO :: excute. Что я должен использовать?PDO :: exec или PDO :: выполнить?

+2

Они очень разные. Если вам нужны динамические параметры, такие как 'DELETE FROM tbl WHERE col =: value', вам нужно использовать' prepare()/bindParam()/execute() '. Назначение 'exec()' является самым простым из статических запросов, таких как 'DELETE FROM tbl' –

+0

Не видя, какие запросы вы используете для' INSERT, UPDATE, DELETE', я предполагаю, что вы должны использовать ' prepare()/execute() ', так как большинство современных приложений должны выполнять эти инструкции на основе значений, вводимых пользователями. –

+0

и каково различие между возвращаемым значением? , который лучше знать, если Update, Insert, Delete не имеет ошибок? –

ответ

3

Хотя оба метода имеют схожую именование (EXEC, выполнение), они предназначены для использования в различных сценариях:

  1. exec используется, чтобы получить число изменяемых строк.

    /** 
    * (PHP 5 &gt;= 5.1.0, PECL pdo &gt;= 0.1.0)<br/> 
    * Execute an SQL statement and return the number of affected rows 
    * @link http://php.net/manual/en/pdo.exec.php 
    * @param string $statement <p> 
    * The SQL statement to prepare and execute. 
    * </p> 
    * <p> 
    * Data inside the query should be properly escaped. 
    * </p> 
    * @return int <b>PDO::exec</b> returns the number of rows that were modified 
    * or deleted by the SQL statement you issued. If no rows were affected, 
    * <b>PDO::exec</b> returns 0. 
    * </p> 
    * This function may 
    * return Boolean <b>FALSE</b>, but may also return a non-Boolean value which 
    * evaluates to <b>FALSE</b>. Please read the section on Booleans for more 
    * information. Use the === 
    * operator for testing the return value of this 
    * function. 
    * <p> 
    * The following example incorrectly relies on the return value of 
    * <b>PDO::exec</b>, wherein a statement that affected 0 rows 
    * results in a call to <b>die</b>: 
    * <code> 
    * $db->exec() or die(print_r($db->errorInfo(), true)); 
    * </code> 
    */ 
    public function exec ($statement) {} 
    

    Пример:

    $myQuery = "UPDATE users SET email = 'testing'"; 
    $affectedRows = $db->exec($myQuery); 
    
  2. execute используется, когда вы хотите передать массив параметров будет связывать в запросе.

    /** 
    * (PHP 5 &gt;= 5.1.0, PECL pdo &gt;= 0.1.0)<br/> 
    * Executes a prepared statement 
    * @link http://php.net/manual/en/pdostatement.execute.php 
    * @param array $input_parameters [optional] <p> 
    * An array of values with as many elements as there are bound 
    * parameters in the SQL statement being executed. 
    * All values are treated as <b>PDO::PARAM_STR</b>. 
    * </p> 
    * <p> 
    * You cannot bind multiple values to a single parameter; for example, 
    * you cannot bind two values to a single named parameter in an IN() 
    * clause. 
    * </p> 
    * <p> 
    * You cannot bind more values than specified; if more keys exist in 
    * <i>input_parameters</i> than in the SQL specified 
    * in the <b>PDO::prepare</b>, then the statement will 
    * fail and an error is emitted. 
    * </p> 
    * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure. 
    */ 
    public function execute (array $input_parameters = null) {} 
    

    Пример (конечно, это может быть UPDATE или DELETE запросов, а):

    $myQuery = 'SELECT * FROM users WHERE username = :username'; 
    $params = array(':username' => 'admin'); 
    $db->query($myQuery)->execute($params); 
    
  3. query она возвращает PDOStatement объект

    /** 
    * (PHP 5 &gt;= 5.1.0, PECL pdo &gt;= 0.2.0)<br/> 
    * Executes an SQL statement, returning a result set as a PDOStatement object 
    * @link http://php.net/manual/en/pdo.query.php 
    * @param string $statement <p> 
    * The SQL statement to prepare and execute. 
    * </p> 
    * <p> 
    * Data inside the query should be properly escaped. 
    * </p> 
    * @return PDOStatement <b>PDO::query</b> returns a PDOStatement object, or <b>FALSE</b> 
    * on failure. 
    */ 
    public function query ($statement) {} 
    

Для получения дополнительной информации вы можно посетить PHP Docs или в c ase вы используете PHPStorm, вы можете пойти по исходному коду класса PDO.php.

Смежные вопросы