SACHIN GAJBHIYE SACHIN GAJBHIYE - 4 months ago 13
JSON Question

database value are not displayed

here I'm trying to fetch database values through json object but it shows only first row of my database how to show entire database .What changes need to do in it.

<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"> </script>
</head>
<body>
<h3>Output: </h3>
<div id="output">this element will be accessed by jquery and this text replaced</div>

<script id="source" language="javascript" type="text/javascript">

$(function ()
{
$.ajax({
url: 'example.php',
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var uid = data[0]; //get id
var firstname = data[1]; //get name
var lastname = data[2];
var email = data[3];
var username = data[4];
var password = data[5];
$('#output').html("<b>uid: </b>"+uid+"<b> firstname: </b>"+firstname+"<b> lastname: </b>"+lastname+"<b> email: </b>"+email+"<b> username: </b>"+username+"<b> password: </b>"+password);
// $('#output').html("<b>uid: </b>"+uid+"<b> firstname: </b>"+firstname+"<b> lastname: </b>"+lastname+"<b> email: </b>"+email+"<b> username: </b>"+username+"<b> password: </b>"+password); //Set output element html

}
});
});
</script>
</body>
</html>


example.php file

<?php

// server info
$server = 'localhost';
$user = 'root';
$pass = '';
$db = 'ocean';

$connection = mysql_connect($server, $user, $pass) or die(mysql_error());
$database = mysql_select_db($db) or die(mysql_error());


$result = mysql_query("select * from oops"); //query

$array = mysql_fetch_row($result); //fetch result

echo json_encode($array);



?>


here is mine code which gives me first row as result of my database
.But I want to show full database as result what I shoud do in this code.

Answer

You should fetch all rows and collect it into array

$array = array();

while ($row = mysql_fetch_row($result)) {
    $array[] = $row;
}

echo json_encode($array);
Comments