PHP和MYSQL:查询在具有值的列上返回null [英] PHP and MYSQL: Query returns null on column with values

查看:121
本文介绍了PHP和MYSQL:查询在具有值的列上返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的SQL查询问题:

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

但是我的PHP代码向我返回了以下值:

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);

如果此时我打印$ variable $ results_to_send,它将被初始化为:

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.

问题是存储在数据库中的字符串.两列均带有带重音符号的字符.例如,第一行是:(1,p1_náme,p1_désc).它返回(1,null,null)

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)

如果我将其更改为(1,p1_name,p1_desc),它将返回(1,p1_name,p1_desc).

If I change it for (1,p1_name, p1_desc), it returns (1,p1_name, p1_desc).

UDATE 2: 由于安德鲁·麦克罗德(Andrew Mackrodt)评论^^

UDATE 2: Problem solved thanks to Andrew Mackrodt comment ^^

推荐答案

我遇到了同样的问题,这是由于PHP的MySQLI和MySQL数据库之间的字符集不匹配而引起的.并非所有字符集都具有相同的字符,这可能导致PHP返回null.

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.

您可以通过查找数据库字符集(在phpmyadmin或类似

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)

如果您想查看可用的字符集,请使用以下列表. http://dev.mysql.com/doc/refman/5.6/zh-CN/charset-charsets.html

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

这篇关于PHP和MYSQL:查询在具有值的列上返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆