PHP mysql PDO更新查询,错误:bindParam()在非对象上

时间:2015-02-14 02:07:55

标签: php mysql pdo

我是使用PHP PDO查询的新手,我正在尝试更新数据库中的数据,但它给了我这个错误:

致命错误:在非对象

上调用成员函数bindParam()

我遇到问题的代码如下:

$db = new PDO('mysql:dbname='.$mysql_database.';host='.$mysql_host.';charset=utf8', $mysql_user, $mysql_password);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

        $mu_query = $db->prepare('UPDATE profile SET music= :mus WHERE user_number= :user');
        $mu_query->bindParam(':mus', $music, PDO::PARAM_STR);
      $mu_query->bindParam(':user', $uid, PDO::PARAM_INT);
      $mu_query->execute();

错误指向的行是第一个bindParam语句

1 个答案:

答案 0 :(得分:1)

我会打开错误记录,$ mu_query可能因前一次失败而为null或false,因此请尝试使用var_dump()。我一段时间写了下面的函数,使PDO查询变得容易。它支持将凭证作为参数传递或使用常量。

/**
 * Quick function for running PDO queries
 * @param $query the query to pass
 * @param $params pass as array, $param => $val,
 * @Param $returnInsertID set to true to have the id of the row inserted returned
 *      Binding params required when using binary data, and recommended for security
 *      a bound param is called in query as :param (Ex SELECT * FROM table WHERE field = :param)
 *      If a SELECT COUNT is passed, the return value is the number of rows
 */

function PDO_query($query, $params = null, $returnInsertID = false, $dbCredentials = false, $debug = false) {
    global $dbTime;
    global $totalDBCalls;
    $timeStart = microtime(true);
// Try to connect
    if (is_array($dbCredentials)){
        try {
            extract($dbCredentials);
            $socketString = isset($dbUnixSocket) ? "unix_socket=$dbUnixSocket" : '';

            $dbHost = (!isset($dbUnixSocket) AND (!defined('DB_UNIX_SOCKET') OR !DB_UNIX_SOCKET)) ? $dbHost : 'localhost';
            $dbPortString = (isset($dbPort) AND $dbPort) ? "port=$dbPort;" : '';

            $dbh = new PDO("mysql:host=" . $dbHost . ";$dbPortString"."dbname=" . $dbName.';' . $socketString , $dbUser, $dbPass, array(PDO::ATTR_PERSISTENT => true));
        } catch (Exception $e) {
          echo "Failed: " . $e->getMessage().'<br />';
          return false;
        }
    }
    else {
        try {
            $socketString = defined('DB_UNIX_SOCKET') ? "unix_socket=".DB_UNIX_SOCKET : '';
            $dbHost = (!isset($dbUnixSocket) AND (!defined('DB_UNIX_SOCKET') OR !DB_UNIX_SOCKET)) ? DB_HOST_BASE : 'localhost';
            $dbPortString = (defined('DB_PORT') AND DB_PORT) ? "port=".DB_PORT.';' : '';

            $dbh = new PDO("mysql:host=" . $dbHost . ";$dbPortString"."dbname=" . DB_NAME.';' . $socketString , DB_USER, DB_PASS, array(PDO::ATTR_PERSISTENT => true));
        } catch (Exception $e) {
          echo "Failed: " . $e->getMessage() .'<br />';
          return false;
        }
    }

// Try to run queries
    try {
      $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $dbh->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
      $dbh->beginTransaction();

    // Debugging, if set
      if ($debug) {
          echo '<br>PDO Params<br>';
          print_r($params);
          echo '<br>PDO Query<br>';
          echo $query;
      }

      // Query
        $stmt = $dbh->prepare($query);
        if (is_array($params)){
            foreach($params as $param => $val){
                if (strpos("$query ", ":$param ") !== false OR strpos($query, ":$param\n") !== false
                     OR strpos($query, ":$param\r\n") !== false  OR strpos($query, ":$param\r") !== false
                        OR strpos($query, ":$param,") !== false OR strpos($query, ":$param)") !== false){
                    if (! is_array($val)){
                     // This MUST absoutely stay here, or else PDO will freak out, (it uses pass by referrence).
                        $$val = $val;
                     // End Do NOT Touch
                        $stmt->bindParam($param, $$val);
                        $boundParams[] = $param;
                    }
                    else{
                        echo 'A param passed to PDO_query was an array (must be string or int)';
                    }
                }
            }
        }

   // Commit
        $stmt->execute();
        $lastInsertID = $dbh->lastInsertID();
        $dbh->commit();

        $dbTime += microtime(true) - $timeStart;
        $totalDBCalls++;
   // Return results if select
        if (substr($query, 0, 6) == 'SELECT' OR substr($query, 0, 4) == 'SHOW') return $stmt->fetchAll(PDO::FETCH_ASSOC);
        else if ($returnInsertID == true) return $lastInsertID;
        else return true;

    } catch (Exception $e) {
          $dbh->rollBack();
          echo '<br>Failed: ' . $e->getMessage();
          echo '<br />';
          echo "<br>Query $query<br>";
          print_r('PDO Params');
          print_r(@$params);
          print_r('Bound Params');
          print_r(@$boundParams);
          foreach($params as $param => $val){
              if (strpos($query, $param) === false) echo $param;
          }
          echo '<br>PDO Failed';
          return false;
    }

    unset($dbh);
    unset($stmt);
}