PHP Array for Json [duplicate]

0

I have this query, I need to display each column in an HTML div. Hi, I need to return the data in a PHP array, pass this php array to an array in JS to be able to manipulate and display them in their respective divs, the query is working perfectly, but how do I pass this to Jquery? I need to use Json, right? I tried using a Json encode, but it did not 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 /> ';
  }


?>
    
asked by anonymous 25.01.2017 / 18:24

1 answer

1

I'm going to enjoy that I've got my hand in the dough to explain to you.

When you have an array in php in this format (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 Bonifazio" ["cpf"] = > NULL   ["phone"] = > string (15) "" ["email"] = > string (28)   "[email protected]" ["password"] = > string (60)   "" ["gender"] = > string (1) "M" ["birthdate"] = > string (10)   "1991-12-04" ["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) "Brazil" ["street"] = > string (25) "" ["state"] = > string (2) "SP" ["city"] = > string (10) "Are   "" "" "" ["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 you change the return format by running: json_encode($array) you get:

  

{"id_customer": "1", "fk_customer_civilstatus": "1", "hashed_id": "xxxxxx", "name": "Marcelo   Bonifazio "," cpf ": null," phone ":" "," email ":" [email protected] "," password ":" "," gender ":" M "," birthdate " 12-04 "," id_google ": null," id_facebook ": null," avatar_url ": null," changekey ": null," last_access ":" 2017-01-25   "Updated_at": null, "userid": "7Z2PZ6", "id_address": "1", "postal_code": "00000-000", "country": " Brazil "," street ":" "," state ":" SP "," city ":" S \ u00e3o   Null, "total_price": "1490", "id_coupons": null, "creditcard": null, "total_price": " , "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   "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}

Make sure this second format is a json valid ( online tool that checks if a json is valid , throw the above string and test ).

Now in the part of client-side that requests this query you can put together a script that works with ajax like this:

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 alert(returnjson.id_customer); you will have printed the value that returned from your json .

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

In your case, you can work on 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));
    
25.01.2017 / 18:32