I'm querying my database using ajax (jquery) but the data I'm getting back is proving difficult to deal with. I did notice that others have posted similar issues and identified the PHP code (specifically how data is being allocated to the array) as being the issue. However I couldn't find a solution. The contents of my returned data (when I transform the returned data into a string) looks like this:
[{"id":"1","userName":"admin","userPassword":"admin","userEmail":"admin@admin.com","userRegistrationIP":"","registrationDateTime":"2015-05-28 21:22:54","userLastLogin":"2015-05-28 21:22:54"}]
I'd really like to be able to pull an individual element from the returned data, such as the userLastLogin field.
My ajax query:
$.ajax({
url: 'authenticate2.php',
type: 'POST',
dataType: 'JSON',
data: {
username: $('#username').val(),
},
success: function (res) {
$('#resultBox').text(res);
}
});
My PHP below:
<?php
$con = mysqli_connect('127.0.0.1','root','','db1');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"db1");
$sql="SELECT * FROM Users WHERE userName = 'admin'";
$result = mysqli_query($con,$sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
mysqli_close($con);
?>