PHP Array for Json

Asked

Viewed 835 times

0

I have this query, I need to display each column in an HTML div. Well, I need to return the data in a PHP array, pass this php array to a JS array to be able to manipulate and display them in their respective Divs, the query ta working perfectly, but how do I pass it to Jquery? I need to use Json, right? I tried using a Json Ncode, but it didn’t work.

    <?php

$equipe1 = $_POST['equipe1'];//Pega o Nome da equipe
$equipe2 = $_POST ['equipe2'];//Pega o Nome da equipe
$dificuldade = $_POST ['dificuldade'];//Define a dificuldade das perguntas que seram selecionadas
$rodada = $_POST ['rodada'];//Número de perguntas que serão retornadas

echo $equipe1;
echo $equipe2;

switch ($dificuldade) {
  case '1':
    $dificuldade = "Facil";
    break;
  case '2':
    $dificuldade = "Medio";
    break;
  case '3':
    $dificuldade = "Dificil";
    break;
}

switch ($rodada) {
  case '1':
    $rodada = "10";
    break;
  case '2':
    $rodada = "15";
    break;
  case '3':
    $rodada = "20";
    break;
}
    try{
     $conexao = new PDO ("mysql:host=localhost; dbname=teocratico; charset=utf8","root","");
     } catch (PDOException $erro){
       echo $erro->getmessage();
       //header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
     }


$consulta = $conexao -> query ("SELECT id_pergunta, pergunta, resposta, desafio FROM perguntas
           where dificuldade ='$dificuldade' ORDER BY rand() LIMIT $rodada ");

// Mostrando a Consulta
$consulta->fetch(PDO::FETCH_ASSOC);
   while($row = $consulta->fetch(PDO::FETCH_ASSOC)) {
    echo  $row['id_pergunta']. ' - '. $row['pergunta'] . ' - ' . $row['resposta'] .' - '. $row ['desafio'].' <BR /> ';
  }


?>
  • Do $Sponse = $query->fetchAll(PDO::FETCH_ASSOC) and then $json = json_enconde($reponse) that will work. Then just echo the $json variable and use Javascript.

  • I admit that I had not searched haha, this question can be considered duplicated from this one: http://answall.com/questions/117739/como-converter-array-de-objetos-php-para-json. which is already duplicated from this one: http://answall.com/questions/97415/converter-object-in-json-no-php

1 answer

1


I’m gonna take advantage of the fact that I got my hands full to explain to you.

When you have an array in php in this format (by executing a var_dump($array) on the server):

Object(stdClass)#6394 (59) { ["id_customer"]=> string(1) "1" ["fk_customer_civilstatus"]=> string(1) "1" ["hashed_id"]=> string(6) "xxxxxx" ["name"]=> string(17) "Marcelo" ["Cpf"]=> NULL ["phone"]=> string(15) "" ["email"]=> string(28) "[email protected]" ["password"]=> string(60) "" ["gender"]=> string(1) "M" ["birthdate"]=> string(10) "0000-00-00" ["id_google"]=> NULL ["id_facebook"]=> NULL ["avatar_url"]=> NULL ["changekey"]=> NULL ["last_access"]=> string(19) "2017-01-25 02:45:17" ["created_at"]=> NULL ["updated_at"]=> NULL ["idusuario"]=> string(6) "xxxxxx" ["id_address"]=> string(1) "1" ["postal_code"]=> string(9) "00000-000" ["country"]=> string(6) "Brasil" ["street"]=> string(25) "" ["state"]=> string(2) "SP" ["city"]=> string(10) "São Paulo" ["number"]=> string(2) "99" ["District"]=> string(12) "" ["Complement"]=> string(0) "" ["id_creditcard"]=> NULL ["creditcard"]=> NULL ["total_price"]=> string(4) "1490" ["id_coupons"]=> NULL ["coupon_name"]=> NULL ["coupon_code"]=> NULL ["Discount"]=> NULL ["duration_months"]=> NULL ["start_date"]=> NULL ["end_date"]=> NULL ["id_sales_order_item"]=> string(1) "1" ["fk_sales_order"]=> string(1) "1" ["fk_product"]=> string(2) "22" ["contract_sl_id"]=> NULL ["fk_sales_order_item_status"]=> string(1) "1" ["fk_sales_order_item_cancellation"]=> NULL ["fk_shipping"]=> NULL ["original_unit_price"]=> string(4) "1490" ["final_unit_price"]=> string(4) "1490" ["trial_start"]=> string(19) "0000-00-00 00:00:00" ["trial_end"]=> string(19) "0000-00-00 00:00:00" ["active_from"]=> NULL ["active_until"]=> NULL ["id_subscription_status_type"]=> string(1) "3" ["status"]=> string(9) "frozen" ["id_payment_method"]=> NULL ["method"]=> NULL ["id_sales_order_item_cancellation"]=> NULL ["request_date"]=> NULL ["cancellation_date"]=> NULL ["Reason"]=> NULL }

When changing the return format running: json_encode($array) you get:

{"id_customer":"1","fk_customer_civilstatus":"1","hashed_id":"xxxxxx","name":"Marcelo","cpf":null,"phone":"","email":"[email protected]","password":"","gender":"M","birthdate":"0000-00-00","id_google":null,"id_facebook":null,"avatar_url":null,"changekey":null,"last_access":"2017-01-25 02:45:17","created_at":null,"updated_at":null,"idusuario":"7Z2PZ6","id_address":"1","postal_code":"00000-000","country":"Brasil","street":"","state":"SP","city":"S u00e3o Paulo","number":"99","district":"","complement":"","id_creditcard":null,"creditcard":null,"total_price":"1490","id_coupons":null,"coupon_name":null,"coupon_code":null,"discount":null,"duration_months":null,"start_date":null,"end_date":null,"id_sales_order_item":"1","fk_sales_order":"1","fk_product":"22","contract_sl_id":null,"fk_sales_order_item_status":"1","fk_sales_order_item_cancellation":null,"fk_shipping":null,"original_unit_price":"1490","final_unit_price":"1490","trial_start":"0000-00-00 00:00:00","trial_end":"0000-00-00 00:00:00","active_from":null,"active_until":null,"id_subscription_status_type":"3","status":frozen","id_payment_method":null,"method":null,"id_sales_order_item_cancellation":null,"request_date":null,"cancellation_date":null,"Reason":null}

Check that this second format is a json valid (online tool that checks whether a json is valid, play the above string and test).

Now on the part of client-side that requests this query you can assemble a script that works with ajax thus:

jQuery.ajax({
  url: "/api/user/",
  type: "POST",
  data: data,
  success: function(returnjson) {
    alert(returnjson.id_customer);
  },
  error: function(returnjson) {
    if (returnjson.status == 500) {
      alert("Erro interno do servidor, tente novamente ou entre em contato com o suporte técnico.");
    } else {
      alert(returnjson.responseJSON.msg);
    }
  }
});

Within the alert(returnjson.id_customer); you will have printed the value returned from your json.

Remember that on the server it is also important to define the header correct: header('Content-Type: application/json');


In your case you can work your page php as follows:

header('Content-Type: application/json');
$equipe1 = $_POST['equipe1'];//Pega o Nome da equipe
$equipe2 = $_POST ['equipe2'];//Pega o Nome da equipe
$dificuldade = $_POST ['dificuldade'];//Define a dificuldade das perguntas que seram selecionadas
$rodada = $_POST ['rodada'];//Número de perguntas que serão retornadas
switch ($dificuldade) {
    case '1':
    $dificuldade = "Facil";
    break;
    case '2':
    $dificuldade = "Medio";
    break;
    case '3':
    $dificuldade = "Dificil";
    break;
}
switch ($rodada) {
    case '1':
    $rodada = "10";
    break;
    case '2':
    $rodada = "15";
    break;
    case '3':
    $rodada = "20";
    break;
}
try{
    $conexao = new PDO ("mysql:host=localhost; dbname=teocratico; charset=utf8","root","");
} catch (PDOException $erro){
    echo $erro->getmessage();
    //header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
}
$consulta = $conexao->query ("SELECT id_pergunta, pergunta, resposta, desafio FROM perguntas
where dificuldade ='$dificuldade' ORDER BY rand() LIMIT $rodada ");
// Mostrando a Consulta
$db_data = $consulta->fetch(PDO::FETCH_ASSOC);
die(json_encode($db_data));
  • At the moment I’m at work, as soon as I get home I’ll take a look, Thank you very much. @marcelobonifazio

  • Just one thing, because there’s a "die" there?

  • @Tiagosilveira die ensures that the script will die there, in case it has any more run below, it will not arrive

  • See that also the echo that had at the beginning, if there is any "trash" that is not in the format expected by json, the ajax simply will not interpret as a format json valid

  • not rolling kkk type, I put the json Ncode, it returns me that { "queryString": "SELECT id_question, question, answer, challenge FROM questions r nwhere difficulty ='Facil' ORDER BY Rand() LIMIT 10 " }, ironically is a valid json, but not with query data kkk

  • @Checkbox for what is not scrolling and query, not json_encode :)

  • I updated the code, see if now goes

  • IT WORKED, MAN, YOU ARE THE BEST kkkk

Show 4 more comments

Browser other questions tagged

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