1

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();
1
  • 4
    You are using mysqli_query, but then mysql_fetch_.... fix that! Commented Jul 18, 2013 at 10:21

3 Answers 3

1

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the adjustments. But now I'm getting a 500 error from the server instead of an empty array.
I'm also trying to figure out why the jquery code only works when uploaded to my webserver, it doesn't work when i debug it in Adobe Edge Animate
@user1422136 this is most likely to security. If you have a local server installed such as WAMP or XAMPP try opening the files from localhost to overcome this.
0

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.

Comments

0
$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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.