svdotbe
svdotbe

Reputation: 168

Passing Data MySQL -> PHP -> JSON

I'm trying to make a php web service that can get data from a MySQL DB on my webspace at school, and parse the data to JSON. Then I call this php function from jQuery, but it seems php returns an empty array.

Here is the php code:

    <?php



// Create connection
$con=mysqli_connect("mysqlstudent","sylvainvansteela","zei8quea0eeP","sylvainvansteela");

if (mysqli_connect_errno($con))
 {

 echo "Failed to connect to MySQL: " . mysqli_connect_error();

 } else {

$mysqlstring = "SELECT * FROM customers";

$result = mysqli_query($con,$mysqlstring);
$rows = array();

while($r = mysql_fetch_array($result)) {
  $rows["id"] = $r[0];
  $rows["email"] = $r[1];
}


header("Content-type: application/json");
echo json_encode($rows);

}


?>

And here is the jQuery code:

function getCustomers(){

    var url = 'http://student.howest.be/sylvain.vansteelandt/fedex/server/getcustomers.php';

    $.getJSON(url,function(data){

    if(data){
        alert(data);
        console.log(data.length);
    } else {
        alert('error');
    }



});

};

getCustomers();

Upvotes: 1

Views: 1082

Answers (3)

Allen Chak
Allen Chak

Reputation: 1950

$rows = array();
while($r = mysqli_fetch_array($result)) {
    $row = array();
    $row['id'] = $r[0];
    $row['email'] = $r[1];
    array_push($rows, $row);
}
echo json_encode($rows);

// OR simplify
$rows = array();
while($r = mysqli_fetch_array($result)) {
    array_push($rows, array('id'=>$r[0], 'email'=>$r[1]));
}
echo json_encode($rows);

Upvotes: 0

Code Lღver
Code Lღver

Reputation: 15603

You need to make change here:

$inc = 0;
while($r = mysqli_fetch_array($result)) { //here you are using the mysql it should be mysqli
  $rows[$inc]["id"] = $r[0];
  $rows[$inc]["email"] = $r[1];
  $inc++;
}

If it is possible then use the mysqli_fetch_assoc.

Upvotes: 0

Yotam Omer
Yotam Omer

Reputation: 15356

I would recommend changing the following part of you PHP:

$rows = array();

$i = 0; // add this
while($r = mysqli_fetch_array($result)) { // mysqli!
  $rows[$i]["id"] = $r[0];
  $rows[$i]["email"] = $r[1];
  $i++; // don't forget to increment
}

Upvotes: 1

Related Questions