0

I'm using the following code:

 try {
        $this->conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);
        $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(PDOException $e)
    {
        echo $e->getMessage();
    }    
 try {
        $stmt = $this->conn->prepare("SELECT id, name FROM images");
        if ($stmt->execute()) {
            if ($stmt->rowCount() > 0)
                return $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
        else
            return NULL;
    }
    catch(PDOException $e)
    {
        return $e->getMessage();
    }

The code perfectly works, but when I edit my query to:

$stmt = $this->conn->prepare("SELECT id, name, description FROM images");

I obtain an empty result.

Obviously the description field exists. Obviously I tested the new query with PHPMyAdmin.

I found that:

if ($stmt->rowCount() > 0)

is TRUE and I also tried to change the fetclAll to FETCH_BOTH.

Do you have any suggestions?

EDIT: OK, I FOUND THE PROBLEM:

In a record, in the column description there was a "è". If I delete the "è", all is perfectly working. Why this happening?

helloimyourmind
  • 874
  • 2
  • 13
  • 30

1 Answers1

0

The Problem was due to an accented letter in a record of the database.

The solution is the use of array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4") to set the character set of the connection to 'UTF-8 MultiByte 4' as follows:

  try {
        $this->conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"));
        $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      }
  catch(PDOException $e)
      {
        echo $e->getMessage();
      }

The reason this specific version of UTF-8 is used is explained here.

Community
  • 1
  • 1
helloimyourmind
  • 874
  • 2
  • 13
  • 30