“致命错误:未捕获错误:在”问题中调用字符串上的成员函数bindParam()

时间:2017-11-22 09:06:55

标签: php pdo

问题: “致命错误:未捕获错误:在C:\ Users \ Robert \ Webdev_old \ UniServerZ \ www \ PDO_DB \ PDO_DB \ admin.php中调用字符串上的成员函数bindParam():58堆栈跟踪:#0 {main}抛出第58行的C:\ Users \ Robert \ Webdev_old \ UniServerZ \ www \ PDO_DB \ PDO_DB \ admin.php“

当我尝试填写表单并将其发送到数据库时出现。我希望所有存储在名为“db_test”的mysql数据库中的文本都带有一个名为“image_gallery”的表,结构如下:

id picName shopName displayStartDate displayEndDate uploadDate uploadPath picFile

以下是整个代码。

    <?php 
    //require_once("inc/pdo.inc.php");
    //print_r(PDO::getAvailableDrivers());
    // error_reporting(E_ALL);
    // ini_set('display_errors', 1);
    error_reporting(E_ERROR);

    if(isset($_POST["submit"]))
    {
      $dsn = 'mysql:host=localhost; dbname=db_test;';
      $user = 'root';
      $pass = 'r00t';

    // Connection in a try/catch block
    try {
          $DBH = new PDO($dsn, $user, $pass);
          $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        } 
        catch(PDOException $e) {
          echo "Bummer! Somethin' went apeshit!";
          file_put_contents('PDOErrors.txt', $e->getTraceAsString(), FILE_APPEND);
        };


      // // initialize empty  variables partly to avoid indexing issues
      // $DBH = "";
      // $picName = "";
      // $shopName = "";
      // $displayStartDate = "";
      // $displayEndDate = "";
      // $date = "";
      // $uploadPath = "";
      // $picFile = "";
      // $delay = "";   

    try {

       // prepare sql and bind parameters
       $STH = new stdClass();
       $STH = $DBH->prepare->query = ("INSERT INTO image_gallery ( picName, shopName, displayStartDate, displayEndDate, uploadDate, uploadPath, picFile, delay )
 VALUES (:picName,:shopName,:displayStartDate,:displayEndDate,:uploadDate,:uploadPath,:picFile,:delay)"
                                                );

       $STH->bindParam(':picName',          $picName);
       $STH->bindParam(':shopName',         $shopName);
       $STH->bindParam(':displayStartDate', $displayStartDate);
       $STH->bindParam(':displayEndDate',   $displayEndDate);
       $STH->bindParam(':uploadDate',       $uploadDate);
       $STH->bindParam(':uploadPath',       $uploadPath);
       $STH->bindParam(':picFile',          $picFile);
       $STH->bindParam(':delay',            $delay);

       $picName          = $_POST['picName'];
       $shopName         = $_POST['shopName'];
       $displayStartDate = $_POST['displayStartDate'];
       $displayEndDate   = $_POST['displayEndDate'];
       $uploadDate       = $_POST['uploadDate'];
       $uploadPath       = $_POST['uploadPath'];
       $picFile          = $_POST['picFile'];
       $delay            = $_POST['delay'];

        // run query
        $STH->execute();

    } catch (Exception $e) {
            echo "I'm sorry, I'm afraid I can't do that).";
    }
    if (!$mysqli->execute()) {
        print_r($mysqli->error_list);
    }
?>

HTML表单:

  <form action="_admin.php" METHOD="POST">
  <div class="row">
    <div class="columns small-6 large-6">
      <div class="medium-6 small-12 cell  ">
        <label>Bildnamn med kort beskrivning
          <input type="text" name="picName" placeholder="Wella Conditioner 500ml">
        </label>
      </div>
        <br>
       <div class="medium-6 small-12 cell ">
        <label>Butik där bild ska visas

      <fieldset class="medium-6 small-12 cell">
          <input name="shopName" type="checkbox"><label for="checkbox1">Alla</label>
          <input name="shopName" type="checkbox"><label for="checkbox2">Malmö</label>
          <input name="shopName" type="checkbox"><label for="checkbox3">3</label>
          <input name="shopName" type="checkbox"><label for="checkbox1">4</label>
          <input name="shopName" type="checkbox"><label for="checkbox2">5</label>
          <input name="shopName" type="checkbox"><label for="checkbox3">6</label>
        </fieldset>     
      </label>
      </div>
        <br>

       <div class="medium-6 small-12 cell ">
        <label>Startdatum för bildens visning
          <input type="text" name="displayStartDate">
        </label>
      </div>
      <br>

      <div class="medium-6 small-12 cell ">
        <label>Slutdatum för bildens visning
          <input type="text" name="displayEndDate">
        </label>
      </div>
      <br>


      <div class="medium-6 small-12 cell ">
        <label>Antal sekunder bilden ska visas
          <input type="number" name="delay">
        </label>
      </div>
      <br>


      <input type="hidden" name="uploadPath">
      <input type="hidden" name="uploadDate">
      <input type="submit" name="submit" value="Ladda upp &#x27a4;" class="sub-style">

    </div>
  </div>
</form>

我在90年代后期编写了很多PHP代码,但是自从它开启和关闭以来,我一直生锈。 非常感谢任何帮助。提前谢谢大家!

1 个答案:

答案 0 :(得分:0)

  • 阅读您正在使用的EACH功能的php.net文档。在这种情况下,主要问题在于$STH = $DBH->prepare->query = ("...");行,正如@YourCommonSense已经向您展示的那样。
  • 因此,要么只使用PDO::query,要么PDO::prepare后跟PDOStatement::execute。不要混合它们。
  • 另一个问题:$STH = new stdClass();。它毫无用处。
  • 此外,您无法在方法调用后定义传递给PDOStatement::bindParam的变量。
  • 此外:$mysqli->execute()$mysqli->error_list与mysqli连接相关。您应该决定使用PDO或mysqli,但不能同时使用两者。
  • 阅读@YourCommonSense推荐的材料以及有关该主题的其他材料,例如PDO Tutorial for MySQL Developers
  • 您不需要 try-catch 块用于基本数据库操作。让PHP引擎抛出错误/异常,并按照herehere的说明相应地处理它们。
  • 不要使用PDO::setAttribute。在创建PDO实例时,将特定于驱动程序的连接选项作为数组传递。

下面的代码向您展示了如何将它们组合在一起。

祝你好运。

<?php

// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'db_test');
define('USERNAME', 'root');
define('PASSWORD', 'r00t');
define('CHARSET', 'utf8');

// Error reporting.
error_reporting(E_ALL);
ini_set('display_errors', 1); // SET IT TO 0 ON A LIVE SERVER!

/*
 * Create a PDO instance as db connection to db.
 * 
 * @link http://php.net/manual/en/class.pdo.php
 * @link http://php.net/manual/en/pdo.constants.php
 * @link http://php.net/manual/en/pdo.error-handling.php
 * @link http://php.net/manual/en/pdo.connections.php
 */
$connection = new PDO(
        sprintf('mysql:host=%s;port=%s;dbname=%s;charset=%s', HOST, PORT, DATABASE, CHARSET)
        , USERNAME
        , PASSWORD
        , [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => FALSE,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]
);

if (isset($_POST['submit'])) {
    $picName = $_POST['picName'];
    $shopName = $_POST['shopName'];
    $displayStartDate = $_POST['displayStartDate'];
    $displayEndDate = $_POST['displayEndDate'];
    $uploadDate = $_POST['uploadDate'];
    $uploadPath = $_POST['uploadPath'];
    $picFile = $_POST['picFile'];
    $delay = $_POST['delay'];

    /*
     * The SQL statement to be prepared. Notice the so-called named markers.
     * They will be replaced later with the corresponding values from the
     * bindings array when using PDOStatement::bindValue.
     * 
     * When using named markers, the bindings array will be an associative
     * array, with the key names corresponding to the named markers from
     * the sql statement.
     * 
     * You can also use question mark markers. In this case, the bindings 
     * array will be an indexed array, with keys beginning from 1 (not 0).
     * Each array key corresponds to the position of the marker in the sql 
     * statement.
     * 
     * @link http://php.net/manual/en/mysqli.prepare.php
     */
    $sql = 'INSERT INTO image_gallery (
                picName,
                shopName,
                displayStartDate,
                displayEndDate,
                uploadDate,
                uploadPath,
                picFile,
                delay
            ) VALUES (
                :picName,
                :shopName,
                :displayStartDate,
                :displayEndDate,
                :uploadDate,
                :uploadPath,
                :picFile,
                :delay
            )';

    /*
     * The bindings array, mapping the named markers from the sql
     * statement to the corresponding values. It will be directly 
     * passed as argument to the PDOStatement::execute method.
     * 
     * @link http://php.net/manual/en/pdostatement.execute.php
     */
    $bindings = [
        ':picName' => $picName,
        ':shopName' => $shopName,
        ':displayStartDate' => $displayStartDate,
        ':displayEndDate' => $displayEndDate,
        ':uploadDate' => $uploadDate,
        ':uploadPath' => $uploadPath,
        ':picFile' => $picFile,
        ':delay' => $delay,
    ];

    /*
     * Prepare the sql statement for execution and return a statement object.
     * 
     * @link http://php.net/manual/en/pdo.prepare.php
     */
    $statement = $connection->prepare($sql);

    /*
     * Execute the prepared statement. Because the bindings array
     * is directly passed as argument, there is no need to use any
     * binding method for each sql statement's marker (like
     * PDOStatement::bindParam or PDOStatement::bindValue).
     * 
     * @link http://php.net/manual/en/pdostatement.execute.php
     */
    $executed = $statement->execute($bindings);

    /*
     * Close the prepared statement.
     * 
     * @link http://php.net/manual/en/pdo.connections.php Example #3 Closing a connection.
     */
    $statement = NULL;
}