SQLSTATE[42S22]: Column not found: 1054 Unknown column '$value' in 'field list''

折月煮酒 提交于 2019-12-25 18:44:12

问题


try {
    $db = new PDO("mysql:host=$host;dbname=$dbname",$user,$password) ; 
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $formInfo = array('fname','lname','email','password','gender') ;
    $entry = array() ;
    foreach($formInfo as $data) {

     $entry[$data] = $_POST[$data]; 

     }
    //print_r($entry); 


    $salt = Hash::gen_salt() ;
    $sqlcollum = array(
                'First_name'=> $entry['fname'] ,
                'Last_name' => $entry['lname'] ,
                'email'     => $entry['email'] ,
                'password'  => Hash::gen_password($entry['password'],$salt) ,
                'salt'      => $salt,
                'gender'    => $entry['gender'] ,
                'date'      => date('Y-m-d H:i'),
                'groups'    => '1'
             ) ;
    $sqlKeys = array_keys($sqlcollum) ;
    $sqlValues = array_values($sqlcollum) ;
    $keys = "'".implode("','", $sqlKeys)."'" ;
    $value = "'".implode("','", $sqlValues)."'" ;
    //echo $keys."<br/>" ;
    //echo $value."<br/>" ;


    $db->beginTransaction() ;

    $insert = $db->query('INSERT INTO register ($keys) VALUES ($value)') ;

    if($insert) {
        echo "true" ;
    } else {
        $db->errorCode() ;
        echo "false" ;
    }
   $db->commit() ;


 } catch(PDOExpection $e) { 
    $db->rollback() ;
    die($e->getMessage()) ;
} 

Why do I get this error?

error::Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column '$value' in 'field list'' in register.php:46


回答1:


You can try this .

 $keys = implode(",",$sqlKeys) ;

this working .




回答2:


$insert = $db->query('INSERT INTO register ($keys) VALUES ($value)');

should be

$insert = $db->query("INSERT INTO register ('$keys') VALUES ('$value')");

or

$insert = $db->query('INSERT INTO register ('.$keys.') VALUES ('.$value.')');

or

$insert = $db->query(sprintf('INSERT INTO register (%s) VALUES (%s)', $keys, $value));

The reason your code isn't working is that for PHP $keys and $value inserted into the string as you have done, are simply a part of the string itself, so values aren't substituted with variable's ones.




回答3:


You have two issues in your code:

1) There is no need to add extra quotes when you use these in query as a string it this will cover.

Replace:

$keys = "'".implode("','", $sqlKeys)."'" ;
$value = "'".implode("','", $sqlValues)."'" ;

With:

$keys = implode("','", $sqlKeys);
$value = implode("','", $sqlValues); 

2) Use string variables into quotes:

$insert = $db->query("INSERT INTO register ('$keys') VALUES ('$value')") ;


来源:https://stackoverflow.com/questions/34630140/sqlstate42s22-column-not-found-1054-unknown-column-value-in-field-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!