2013-07-22 2 views
-1

Я не могу понять, что не так с моим методом чтения (динамически подготовленный оператор с PDO). Может кто-нибудь указать мне в правильном направлении? Я не думаю, что я использую зарезервированные слова SQL. Возможно, я где-то пропустил цитаты или что-то еще? Я новичок в PDO.SQLSTATE [42000]: Ошибка синтаксиса или нарушение доступа: 1064 У вас есть ошибка в синтаксисе SQL

Это метод чтения:

public function read($select_col, $table_name, $where, $where_condition=null, $where_compare=null, $other=null){ 

     //This method will return false if the # of where key-value pairs don't match up with the # of $where_condition items. 
     //If it works, it will return a 1-dimensional array if only one row is found. If more than one row, then it will be a 2D array. 
     //  It will return an associative array. 

     //$select_col can be an array or a variable (words or just "*") 
     //$table_name is just $table_name (most likely the $table_name var given by object) 
     //$where is an associative array with keys as column names and values as the value for the test. 
     //  Code below will add ":" in front of key to make it a named parameter. 
     //$where_condition allows user to create other where conditions (ie. "<" or ">". It can be a single variable or an array) 
     //$other would be room for other stuff like "ASC LIMIT 1" 
     $errors = array(); 
     $sql = '"SELECT '; 

     //if $select_col is an array, then put commas after each item except for the last one 
     if(is_array($select_col)){ 
      $s_count = count($select_col); 
      for($s=0; $s<$s_count; $s++){ 
       $sql .= $select_col[$s]; 
       if($s<($s_count-1)){ 
        $sql .= ", "; 
       } 
      } 
     } else{ 
      $sql .= $select_col; 
     } 
     $sql .= " FROM " . $table_name; 

     //if $where values are given, then add them to sql. Named parameters are generated from the keys by adding ":" in front of each key 
     if(!empty($where)){ 
      $w_count = count($where); 
      //if there are $where_condition values, then make sure they match up to the number of $where key-value sets. 
      //If they don't match up, then return false and stop. 
      if(!empty($where_compare)){ 
       $wc_count = count($where_compare); 
       if($w_count!=$wc_count){ 
        return false; 
        $exit(); 
       } 
      } 
      $sql .= " WHERE "; 
      for($w=0; $w<$w_count; $w++){ 
       $sql .= key($where); 
       if(!empty($where_compare)){ 
        $sql .= " " . $where_compare[$w] . " "; 
       } else{ 
        $sql .= " = "; 
       } 
       $sql .= "':" . key($where) . "'"; 
       next($where); 
       if($w<($w_count-1)){ 
        if(empty($where_condition)){ 
         $errors[] = "WHERE condition(s) is/are missing (ie. AND, OR)"; 
        } else{ 
         $sql .= " " . $where_condition[$w] . " "; 
        } 
       } 
      } 
     } 
     //At this point, $where keys and named parameters are set up or it just skipped where section because there are no where values 
     if(!empty($other)){ 
      $sql .= " " . $other; 
     } 
     $sql .= '"'; 

     $stmt = $this->dbc->prepare($sql); 
     if(!$stmt){ 
      $errors[] = "Failed to prepare query. " . $this->dbc->errorInfo(); 
     } 
     foreach ($where as $key => $value) { 
      $named_param = "':" . $key . "'"; 
      if(is_numeric($value)){ 
       $type = "PDO::PARAM_INT"; 
      } else{ 
       $type = "PDO::PARAM_STR"; 
      } 
      $stmt->bindValue($named_param, $value, $type); 
     } 
     $execute = $stmt->execute(); 
     if(!$execute){ 
      $errors[] = "Query failed to execute. " . $this->dbc->errorInfo(); 
     } 
     $result = $stmt->fetchAll(PDO::FETCH_ASSOC); 
     //if just one row is returned, it returns a one-dimensional array. If more than one row, then it is a two-dimensional array. 
     if(!empty($errors)){ 
      return $errors; 
     } else{ 
      return $result; 
     } 
} 

Это метод аутентификации, который использует метод чтения:

public static function authenticate($username="", $pw=""){ 
    global $db; 

    $hashed_pw = self::encrypt_pw($username, $pw); 
    $where = array('username' => $username, 'pw' => $hashed_pw); 
    $where_condition = array("AND"); 

    $id = $db->read("user_id", "users", $where, $where_condition); 
    if(is_numeric($id) AND $id!=0){ 
     return true; 
    } else{ 
     return false; 
    } 
} 
+0

не "PDO :: PARAM_INT"; целое число, в то время как вы передаете это как строку. попробуйте изменить его на int и посмотрите, работает ли это – Satya

+0

. Код настроен так, что если он является числовым, тогда это будет PDO :: PARAM_INT, иначе это будет PDO :: PARAM_STR. Я все-таки пробовал, и это не сработало. Я действительно поставил этот раздел в коде, чтобы убедиться, что он решил проблему, поэтому проблема существовала до ввода условного значения для PDO :: PARAM_INT/PDO :: PARAM_STR. Спасибо за предложение, хотя –

ответ

0

Почему вы должны " в $sql = '"SELECT '; и $sql .= '"';?

$sql уже является строкой, если это то, что вы пытаетесь сделать. То, что вы сделали, добавило " литералов до и после фактического запроса select. Удаление их должно решить вашу проблему.

+0

Похоже, в этом была проблема. Благодаря!!! –

+0

@ JR, Добро пожаловать. Рад, что вы его работали. – vee

0
$sql = '"SELECT '; 

Вы добавляете дополнительную двойную кавычку в запрос. Это не нужно. Измените эту строку на:

$sql = 'SELECT'; 

Это должно решить проблему.

+0

Да, вы и вино верны. Благодаря! –

+0

@ JR: добро пожаловать. Рад, что смог помочь! –

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

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