I have a problem with a simple SQL query:
SELECT a.idElemento, b.nombre, b.descripcion
FROM productos_elementos a
INNER JOIN elementos_adicionales b
ON a.idElementoAdicional=b.id_elemento_adicional
INNER JOIN precio_elemento c
ON a.idElemento=c.idElemento
WHERE a.idProducto = 1 AND c.idPolitica = 1
When I execute this query on my database, it returns:
IdElemento Nombre Descripcion
1 p1 p1_desc
2 p2 p2_desc
However my PHP code returns me this values:
IdElemento Nombre Descripcion
1 null null
2 null null
I don't know why that it's happening. Any ideas? This is the code:
//$query is a string with the querty: SELECT....
$result = $this->conn->query($query);
$aux = $result->fetchAll(PDO::FETCH_OBJ);
$results_to_send = json_encode($aux);
If I print the $variable $results_to_send at this moment, it is initialized to:
[{"idElemento":"1","nombre":null,"descripcion":null},{"idElemento":"2","nombre":null,"descripcion":null}]
I use the values in this piece of code:
foreach ($results_to_send as $key => $value){
...
echo $value->idElemento //It prints 1 or 2
...
echo $value->nombre //It is null
...}
UPDATE: Finally I have found the problem. I don't know how to resolve it yet, but it's a start.
The problem is the string stored in the database. Both columns have characters with accents. For example the first row is: (1,p1_náme, p1_désc). It returns (1, null, null)
If I change it for (1,p1_name, p1_desc), it returns (1,p1_name, p1_desc).
UDATE 2: Problem solved thanks to Andrew Mackrodt comment ^^
I had the same problem which was caused by non-matching charsets between PHP's MySQLI and MySQL Database. Not all charsets have the same characters which can cause PHP to return a null.
You can compare and set your charset by locating your database charset (in phpmyadmin or in a query like this) and set in PHP using $mysqli::set_charset("short_name") (http://php.net/manual/en/mysqli.set-charset.php)
If you'd like to see what charsets are available here's a list. http://dev.mysql.com/doc/refman/5.6/en/charset-charsets.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With