Mysql error 1054 Unknown column

3

I'm doing a SQL that counts how many names in the table begin with any letter but an error is being returned:

  

Column not found: 1054 Unknown column 'A' in 'where clause'

For the following SQL:

SELECT COUNT(*) FROM author WHERE name LIKE 'A%';

Excuting directly on the MySQL console works fine, but when using PDO, error 1054 is returned.

$count = 'SELECT COUNT(*) FROM author WHERE name LIKE \'' . $consulta->letter . '%\'';
echo $count; //Resultado : SELECT COUNT(*) FROM author WHERE name LIKE 'A%'
$stmt = $conn->prepare($count);

Note: I am using PDO and Mysql .

    
asked by anonymous 27.04.2015 / 14:39

4 answers

2

I think the problem occurs because of the % sign, which can not be there. Try using bindParam , like this:

$letter = $consulta->letter . "%"

$stmt = $conn->prepare('SELECT COUNT(*) FROM author WHERE name LIKE :letter');
$stmt->bindParam(':letter', $letter, PDO::PARAM_STR);
    
27.04.2015 / 15:04
1

I would do it and it would work here:

$count = "SELECT COUNT(*) FROM author WHERE name LIKE '{$consulta->letter}%'";
    
27.04.2015 / 15:06
1
  

1054 Unknown column ' column name ' in local / clause

This error usually occurs when the column does not exist, was typed wrong, missing quotes in a value that ended up being interpreted as a column or in the worst case the table ended up corrupting.

The ideal is to use prepared statement and leave joker ( % or _ ) out of the sql statement and pass it on just at the time of bind.

$stmt = $conn->prepare('SELECT COUNT(*) FROM author WHERE name LIKE ?');
$stmt->execute(array('A%'));

Jokers :

% - Qualquer caracter em qualquer quantidade.
_ - Um único caracter.
    
27.04.2015 / 15:14
0

I was having the same problem and followed the response given by the user "bigwebguy" here at this link: Getting raw SQL query string from PDO prepared statements

So it is possible to identify which query and parameters are being executed. In my case it was necessary to use crase to work.

$user = DB::getInstance()->get('users', array("\' name\'", '=', "joao"));

/**
 * Replaces any parameter placeholders in a query with the value of that
 * parameter. Useful for debugging. Assumes anonymous parameters from 
 * $params are are in the same order as specified in $query
 *
 * @param string $query The sql query with parameter placeholders
 * @param array $params The array of substitution parameters
 * @return string The interpolated query
 */
public static function interpolateQuery($query, $params) {
    $keys = array();

    # build a regular expression for each parameter
    foreach ($params as $key => $value) {
        if (is_string($key)) {
            $keys[] = '/:'.$key.'/';
        } else {
            $keys[] = '/[?]/';
        }
    }

    $query = preg_replace($keys, $params, $query, 1, $count);

    #trigger_error('replaced '.$count.' keys');

    return $query;
}
    
28.09.2015 / 18:32