Pick arrays with php space

Asked

Viewed 173 times

1

I have a php code that picked up information from two different columns of the same table in a local database, but the code doesn’t seem to work when one of the columns has information with space, for example: "Romeo Juliet" but if it is written: "Romeo Juliet" the code works, can anyone help me? Follows the code:

<?php 

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "teste";

$conn = new mysqli ($servername,$username,$password,$dbname);

if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sql1 = "SELECT abbreviation,image FROM je";

$result1 = $conn->query($sql1);
$i=0;
$resultado = array(array(),array());
while ($row = $result1->fetch_assoc()){
    $resultado[$i]["imagem"] = $row["image"];
    $resultado[$i]["abrevia"] = $row["abbreviation"];
    $i++;
}


echo json_encode($resultado);

?>
  • I believe your problem is with accents or special characters, try this way: json_encode( $result, JSON_UNESCAPED_UNICODE );

  • 1

    Could you display the result to check? In principle, it is not to happen what was described in the code shown. The error could be in the data, or in their verification. Taking advantage, in this line it is worth mentioning that you are creating an array with 2 empty arrays that will not help you at all: $resultado = array(array(),array()); (if you give a print_r in the generated array, you may understand better)

1 answer

0

Every entry in json_encode() All string must be encoded as UTF-8. So, to solve your problem, just format the entry with utf8_encode:

<?php 

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "teste";

$conn = new mysqli ($servername,$username,$password,$dbname);

if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sql1 = "SELECT abbreviation,image FROM je";

$result1 = $conn->query($sql1);
$i=0;
$resultado = array(array(),array());
while ($row = $result1->fetch_assoc()){
    //$resultado[$i]["imagem"] = $row["image"];
    //$resultado[$i]["abrevia"] = $row["abbreviation"];
    $resultado[$i]["imagem"] = utf8_encode( $row["image"] );
    $resultado[$i]["abrevia"] = utf8_encode( $row["abbreviation"]);
    $i++;
}


echo json_encode($resultado);

?>

On my server worked properly.

If this answer has been helpful, I will be happy to choose this answer or mark it as useful (+1).

I hope I’ve helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.