Home » Php » php mysql select not working on field "name"

php mysql select not working on field "name"

Posted by: admin February 25, 2020 Leave a comment

Questions:

I know it’s strange but I have a select that returns null if the field named name is used. If I remove it then it works, and I already changed the data in the table. If I make a direct query to mysql it works. There might be something in the contents but I can’t see anything strange.

Any suggestion that could help me investigate is welcome 🙁

class go { 
   function Query($sql){

       $results = $this->db->query($sql);

       if (mysqli_num_rows($results)<1){    
           throw new Exception('No Results');       
       }    

       $out = array();

       while ($r = $results->fetch_object()){       
           $out[] = $r;  
       } 

       return json_encode($out);    

       $out = null;
    }
}

$client = new go;

//not working
$sql = "select name from books limit 10"; 
$sql = "select name,description from books limit 10";
$sql = "select * from books limit 10";

// works!
$sql = "select description from books limit 10"; 

$data = $client->Query( $sql );

UPDATE

I found that the problem comes out due to some latin accented characters like ó ñ é

How to&Answers:

DBMS some reserved keywords. Name is a reserved name in MYsQL. Change the name to another column name, maybe name1. I think that should work.Check list of reserved keywords for mysql https://dev.mysql.com/doc/refman/8.0/en/keywords.html#keywords-8-0-detailed-N.

Answer:

Update

Try setting the charset when initialising the connection to your mySQL server usg set_charset() method. I use the following charset:

$this->db->set_charset('utf8mb4');

This may resolve your issue.

Answer:

Solved with
mysqli_set_charset($db, “utf8”);