0
 try {
     $db = new PDO("mysql:host=$host;dbname=$dbname",$user,$password) ;

     $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


     $sqlcollum = array(
                 'First_name'=> 'gaurav',
                 'Last_name' => 'sundaram',

              ) ;
     $Keys = array_keys($sqlcollum) ;
     $Valuess = array_values($sqlcollum) ;
     $Valuess = "'".implode("'", $Valuess)."'" ;


     $db->beginTransaction() ;
    $insert = $db->prepare('INSERT INTO register ($Keys) VALUES ($Valuess)') ;
    $insert->execute() ;
;
    if($insert) {
        echo "true" ;
    } else {
        $db->errorCode() ;
        echo "false" ;
    }
   $db->commit() ;


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

}

error is SQLSTATE[42S22]: Column not found: 1054 Unknown column '$Valuess' in 'field list'' in try2.php:31. how shpuld i type insert statement correctly

gaurav
  • 1,281
  • 1
  • 13
  • 25
  • put insert query in double quote (") – Chetan Ameta Jan 06 '16 at 11:56
  • 2
    Possible duplicate of: http://stackoverflow.com/questions/34630140/sqlstate42s22-column-not-found-1054-unknown-column-value-in-field-list/34630192#34630192 – DonCallisto Jan 06 '16 at 11:56
  • @DonCallisto there are no correct answer – gaurav Jan 06 '16 at 12:02
  • @gaurav Use double quotes `"` to pass variables. Also, look into using prepared statements (or you'll risk [SQL-injection](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)). – Qirel Jan 06 '16 at 12:04
  • @Qirel after double quotes error SQLSTATE[42000]: Syntax error or access violation: – gaurav Jan 06 '16 at 12:05
  • What does `echo "INSERT INTO register ($Keys) VALUES ($Valuess)";` produce? (It might be that your variables produce an invalid query) – Qirel Jan 06 '16 at 12:08

2 Answers2

0

Use bindParam instead - an example from the PHP docs:

<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>
Sandeep Bansal
  • 6,280
  • 17
  • 84
  • 126
0

Just use the string inside ""

$dbh->prepare("INSERT INTO register ($Keys) VALUES ($Valuess)")

Because inside '' variable behave like string but inside "" variables values are fetched.

Also change

 $Valuess = "'".implode("','", $Valuess)."'" ;

Values must be imploded with comma like 'gaurav','sundaram'

Vegeta
  • 1,319
  • 7
  • 17