PHP that returns null table fields that are neither empty nor null in MySQL

1

I have a table "payment_forms" and I made an API to get all these forms of payment, but even the database is correct, it informs that the "name" field is null in return, see:

[{"nome":"Dinheiro"},{"nome":"Cheque"},{"nome":null},{"nome":null}]

And it is not "null" and only these two appear.

Follow my PHP:

PHP:

    <?php


header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');

include 'database.php';

//$cod_fornecedor=$_GET['cod_fornecedor'];


$query="SELECT
   nome
FROM
   formas_pagamento
ORDER BY
   cod_forma_pagamento ASC";


$result=$con->query($query);

$row_cnt = mysqli_num_rows($result);
if ($result->num_rows > 0) 
{
    $count=0;
    echo "[";
    while($row = $result->fetch_assoc()) 
    {
            $count++;
            echo json_encode($row);

            if($count!=$row_cnt)
            {
                    echo ",";
            }


    }
    echo "]";
}
else
{
echo "error";
}

?>

What's wrong?

    
asked by anonymous 09.02.2017 / 17:32

5 answers

0

I solved using json_encode (utf8ize ($ row));

Here is the complete new PHP:

   $rest_api = array();
function utf8ize($d) {
    if (is_array($d)) {
        foreach ($d as $k => $v) {
            $d[$k] = utf8ize($v);
        }
    } else if (is_string ($d)) {
        return utf8_encode($d);
    }
    return $d;
}

/** connect to mysql **/
$mysql = new mysqli($config["host"], $config["user"], $config["pass"], $config["dbase"]);
if (mysqli_connect_errno()){
    die(mysqli_connect_error());
}


$query="SELECT nome FROM formas_pagamento ORDER BY cod_forma_pagamento ASC";

$result = $mysql->query($query);
//$result=$con->query($query);



if ($result->num_rows > 0) 
{
    $count=0;
    echo "[";
    while($row = $result->fetch_assoc()) 
    {
            $count++;

            echo json_encode(utf8ize($row));

            if($count!=$row_cnt)
            {
                    echo ",";
            }


    }
    echo "]";
}
else
{
echo "error";
}

?>
    
10.02.2017 / 12:40
3

There are functions that already associate the results, you do not have to go through it manually and reinvent the wheel, at the risk of creating errors. Use the mysqli_fetch_all function:

$query = "SELECT nome FROM formas_pagamento ORDER BY cod_forma_pagamento ASC";

$result = $con->query($query);

$resultArray = $result->fetch_all(MYSQLI_ASSOC);

echo json_encode($resultArray);
    
10.02.2017 / 13:22
2

Why complicate and "invite" mistakes? There is a much easier way to do this (untested code):

$output = [];
while($row = $result->fetch_assoc()) 
{
  $output[] = $row;
}
echo json_encode($output);
    
09.02.2017 / 20:31
1

You can do in a more simplified way that will work perfectly:

$query="SELECT
   nome
FROM
   formas_pagamento
ORDER BY
   cod_forma_pagamento ASC";

$arr = [];
foreach ($con->query($query, PDO::FETCH_ASSOC) as $row) {
    $arr[] = $row;
}

echo json_encode($arr);

If you have any questions, please visit link

    
10.02.2017 / 02:55
1

json_encode requires UTF-8, this is probably already the format of your bank, but you may not have specified this in the connection, as I explain in this answer:

If it's OOP:

$mysqli = new mysqli('HOST', 'usuario', 'senha', 'banco');

if ($mysqli->connect_error) {
    printf('Erro de conexão: %s', $mysqli->connect_errno);
    exit;
}

/*
 * compatibilidade para to 5.2.9 e 5.3.0.
 */
if (mysqli_connect_error()) {
    printf('Erro de conexão: %s', mysqli_connect_error());
    exit;
}

//Define para UTF-8
if (false === $mysqli->set_charset('utf8')) {
    printf('Error ao usar utf8: %s', $mysqli->error);
    exit;
}

With procedural mysqli:

<?php
$link = mysqli_connect('HOST', 'usuario', 'senha', 'banco');

if (mysqli_connect_error()) {
    printf('Erro de conexão: %s', mysqli_connect_error());
    exit;
}

//Define para UTF-8
if (!mysqli_set_charset($link, 'utf8')) {
    printf('Error ao usar utf8: %s', mysqli_error($link));
    exit;
}

It is not necessary to use utf8_encode in a recursive way, as you did in your answer, just understand what UTF-8 is and know how to apply it, the answer that I linkei shows step by step.

    
10.02.2017 / 15:04