-3

i have error when i try insert data into mysql by PDO when i create function

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sadas' in 'field list'' in /opt/lampp/htdocs/site1/admin/functions/function.php:13 Stack trace: #0 /opt/lampp/htdocs/site1/admin/functions/function.php(13): PDO->query('insert into sub...') #1 /opt/lampp/htdocs/site1/admin/functions/function.php(31): add_subject('sadas') #2 {main} thrown in /opt/lampp/htdocs/site1/admin/functions/function.php on line 13

code

<?php 
 try {
  $connection=new PDO('mysql:host=127.0.0.1;dbname=alshba7','root','987654alshba');
  $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch (PDOException $e) {
  die('there is problem');

}
 
 function add_subject ($title){
         global $connection;   
 $add=$connection->query("insert into sub (title) values($title)");
      if(isset($add)){ 
       echo 'Done';
      }
          } 
 add_subject ('sadas');  
?>

who will solve my problem ?? i will appreciate your help

Sirko
  • 72,589
  • 19
  • 149
  • 183
  • 1
    You’re not _really_ using PDO here ... not in the way you are supposed to, at least. By assembling the query string including the data in one go, you’re leaving yourself open to SQL injection here. Go read up on prepared statements. – CBroe Mar 24 '17 at 13:09
  • 3
    I'd change your db password also, consider this one leaked. – ʰᵈˑ Mar 24 '17 at 13:11

1 Answers1

1

That is not how you insert data using, PDO, you need to use prepared statements. So you won't have a problem with quotes.

<?php 
 try {
  $connection=new PDO('mysql:host=127.0.0.1;dbname=alshba7','root','987654alshba');
  $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch (PDOException $e) {
  die('there is problem');

}

 function add_subject ($title){
         global $connection;   
 $add=$connection->prepare("INSERT INTO sub (title) VALUES(?)");
    if($add->execute([$title])){

        echo "done";
    }

          } 
 add_subject ('sadas');  
?>
Masivuye Cokile
  • 4,754
  • 3
  • 19
  • 34