skip to Main Content
<?php
$server="localhost";
$user="root";
$pass="";
$dbname="expert";

$dsn="mysql:host=$server;dbname=$dbname";
try {
    $connect=new PDO($dsn,$user,$pass);
    $connect->exec("SET character_set_connection ='utf8mb4'");
    $connect->exec("SET NAMES ='UTF8'");
}
catch (PDOException $error){
    echo ("unable to connect".$error->getMessage());

}
?>

unable to connectSQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ” at line 1

image of error

2

Answers


  1. This Worked for me you can try this

       <?php
    
       $server="localhost";
       $user="root";
       $pass="";
    
       try {
          $connect=new PDO("mysql:host=$server;dbname=test_db",$user,$pass);
          $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
          $connect->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND , "SET NAMES utf8");
          $connect->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND , "SET character_set_connection =utf8mb4");
          echo "connected Successfully";
    
        }
        catch (PDOException $error){
        echo ("unable to connect".$error->getMessage());
    
        }
        ?>
    
    Login or Signup to reply.
  2. NAMES is not a variable, SET NAMES is a SQL command.

    According to the documentation of SET NAMES, the command requires a character set and optional a collation. Quotes are optional for the character set or collation clauses, e.g.

    SET NAMES utf8mb4
    

    However, you should avoid sending extra commands, since client can send the character set already during connection handshake.

    This can be done by specifying the character set in your DSN:

    $connect = new PDO("mysql:host=$server;dbname=test_db; charset=utf8mb4",$user,$pass);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search