Fetching multiple data from MySQL using jquery ajax

I am trying to use $.post

to fetch multiple data from MySQL. I don't seem to be working. How can I get multiple data using jquery-ajax from MySQL?

PHP

$e = $_POST['stu'];
$sq ="SELECT physics, chemistry, agriculture FROM subjects WHERE student = :student";
$stmt = $getdb->prepare($sq);
$stmt->execute(array(':student'=>"123456"));
$rslt = $stmt->fetchAll();

$sd=array();
foreach($rslt as $val){
     $sd[] = $val; 
}
echo json_encode($sd);

      

jq:

$.post('my.php',
    {
      stu:"test"
    },
    function(data){
       $.each(data,function(ab){
         alert(ab.physics+" || "+ab.chemistry+" || "+item.agriculture);
       });
});

      

EDIT

console.log (data);

enter image description here

+3


source to share


2 answers


Let's say you want to return two arrays.
So from the PHP side:

echo json_encode(Array($first_array,$second_array), JSON_FORCE_OBJECT);

      



then from the js side:

function(data) {
      var my_obj = JSON.parse(data);
      var first_arr = my_obj[0];
      var second_arr = my_obj[1]; 
}

      

0


source


If you are trying to use this type of sintax, I suggest changing the php code to the following sintax

$e = $_POST['stu'];
$sq ="SELECT physics, chemistry, agriculture FROM subjects WHERE student = :student";
$stmt = $getdb->prepare($sq);
$stmt->execute(array(':student'=>"123456"));
$rslt = $stmt->fetchAll();

$sd=array();
foreach($rslt as $val){
  $sd[] = array("".$val.""=>$val); 
}
echo json_encode($sd);    Ho

      

And in jquery ajax I recommend the following



$.post('my.php',
{
  stu:"test"
},
function(data){
   var result = $.parseJSON(data);
   $.each(result,function(i, ab){
     console.log(ab.physics+" || "+ab.chemistry+" || "+item.agriculture);
   });
});

      

Hope this is helpful ...

0


source







All Articles