Problem when creating a json with a MYSQL query

0

PHP

function ConectarBD(){
   $conexion = mysqli_connect("localhost", "root", "", "adbsense");
    if($conexion){
        echo 'La conexión de la base de datos se ha hecho satisfactoriamente ';
    }else{
        echo 'Ha sucedido un error inesperado en la conexión de la base de datos ';
    }
    return $conexion;
}

function desconectarBD($conexion){

    $close = mysqli_close($conexion);

    if($close){
        echo 'La desconexión de la base de datos se ha hecho satisfactoriamente ';
    }else{
        echo 'Ha sucedido un error inesperado en la desconexión de la base de datos ';
    }

    return $close;
}

function getArraySQL(){
    //Creamos la conexión con la función anterior
    $conexion = ConectarBD();
    $sql = "SELECT post_name, post_content, post_modified from wp_posts where substring(post_modified,1,10) = curdate() and post_status='publish'";
    //generamos la consulta
    $result = mysqli_query($conexion, $sql);
    $rawdata = array(); //creamos un array

    //guardamos en un array multidimensional todos los datos de la consulta
    $i=0;

    while($row = mysqli_fetch_array($result))
    {
        $rawdata[$i] = $row;
        $i++;
    }

    desconectarBD($conexion); //desconectamos la base de datos

    return $rawdata; //devolvemos el array
}
$json = json_encode(getArraySQL());
print_r(json_encode(getArraySQL()));
console.log($jsonConsulta);

The problem is that I do not print the JSON and I do not know if it is bringing the correct rows. What I did wrong, apart from being born xD

    
asked by Ernesto Emmanuel Yah Lopez 20.07.2017 в 18:28
source

1 answer

0

Assuming that the json is correctly formed, you need to tell it the contents of the file.

header("Content-Type: application/json; charset=UTF-8");
echo json_encode(getArraySQL());

If it still fails, you should bear in mind that the json_encode () function requires that the data be in UTF-8 format, if it does not give an error. If they are not, you must change it:

utf8_encode($string);

I have assumed that you have checked that you bring the data of the database without problems, and that the problem is the creation of the json. I hope it serves you.

    
answered by 20.07.2017 / 18:46
source