在mysql PDO中插入数据时出错

时间:2017-03-24 13:06:03

标签: php mysql

当我在创建函数

时尝试通过PDO将数据插入到mysql中时出错
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



<?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');  
?>
&#13;
&#13;
&#13;

谁将解决我的问题?我将非常感谢您的帮助

1 个答案:

答案 0 :(得分:1)

这不是您使用PDO插入数据的方式,您需要使用预准备语句。因此,引号不会有问题。

<?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');  
?>