Home  >  Q&A  >  body text

php - pdo向数据库插入数据失败?

错误代码:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'insert into admin (userid,password,collection) values ('John', 'Doe', 'jo')' at line 1

pdo代码:

$servername="localhost";
$user="root";
$psw="444444";
try{
            
            
            $con=new PDO("mysql:host=$servername;dbname:mydb",$user,$psw);
            $con->query("set names utf8");
            $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            
            if($con){
                
                $sql="use mydb insert into admin (userid,password,collection) values ('John', 'Doe', 'jo')";
                $con->exec($sql);

            }
            }
            catch(PDOException $e)
            {
                echo  $e->getMessage();
            }

报错信息说我sql有语法错误,但是我的sql语句在mysql执行时是可以插入数据的,而且有插入权限,请问为什么这里出错了?

某草草某草草2734 days ago770

reply all(4)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-16 13:00:00

    use mydbAdd a semicolon after it, because these are two sentences of sql

    reply
    0
  • 阿神

    阿神2017-05-16 13:00:00

    You have already specified the database when connecting, so there is no needuse mydb.

    reply
    0
  • 迷茫

    迷茫2017-05-16 13:00:00

    Is it because the symbols are not used well? Try this:
    $sql='use mydb insert into admin ("userid","password","collection") values ​​("John", "Doe", "jo" )';

    reply
    0
  • 高洛峰

    高洛峰2017-05-16 13:00:00

    use mydb does not need to be specified every time, just specify it once, and then SQL

    reply
    0
  • Cancelreply