Fetching from mysql and storing in an array in php? - php

$query= "Select * from std";
$res= mysqli_query($con, $query);
$idArray=array();
$i=0;
while ($row = mysqli_fetch_array($res)) {
$idArray[$i]=htmlentities($row["id"]);
$i++;
}
for($j=0;$j<=$i;$j++){
echo $idArray[j]."asd<br>";
}
In output it shows only "asd" 5 times as i have five records but i does not showing the id's of those records,
Thanks in advance,

You're missing a dollar sign on the echo-row:
echo $idArray[j]."asd<br>";
Should be
echo $idArray[$j]."asd<br>";

try this
$query= "Select * from std";
$res= mysqli_query($con, $query);
$idArray=array();
while ($row = mysqli_fetch_array($res)) {
$idArray[] =htmlentities($row["id"]);
}
for($j=0;$j<sizeof($idArray);$j++){
echo $idArray[$j]."asd<br>";
}

You have to get count of $idArray and pass it to for loop
for($j=0;$j<count($idArray);$j++){
echo $idArray[$j]."asd<br>";
}
But why are you using different for loop .... you could echo in while loop.

<?php
$db = mysql_connect('localhost','root','');
mysql_select_db('test_db',$db);
$data = array();
$query = mysql_query("SELECT * FROM test_table");
while($row = mysql_fetch_object($query) ) {
$data[] = $row;
}
print_r($data);
?>
Example Taken From :
http://arjun.net.in/displaying-mysql-table-records-in-unordered-list-format-using-php/

Related

mySQL to JSON Object only returns first row

these lines of code :
$sql ="SELECT * FROM parcours";
$r = mysqli_query($con,$sql);
$result = array();
while($res = mysqli_fetch_array($r)){
$result[] = $res;
}
echo json_encode(array("result"=>$result));
returns me only the first row of my DB request.
How can I get all of it ?
I think you need to use mysqli_fetch_assoc :
while($res = mysqli_fetch_assoc($r)){
$result[] = $res;
}
and then :
echo json_encode(array($result));

how to give a unique variable name for each result?

I want to give each output a unique variable name so I can use it anyway I want Any help?
<?php
$sql = "SELECT * FROM db";
$result = mysqli_query($con, $sql);
while($row= mysqli_fetch_assoc($result)) {
$var = $row['field_name'];
echo $var."<br>";
// Outputs name1 name2 etc.,
}
?>
<?php
$sql = "SELECT * FROM db";
$result = mysqli_query($con, $sql);
$var = array();
while($row= mysqli_fetch_assoc($result)) {
$var['name1'] = $row['field_name_1'];
$var['name2'] = $row['field_name_2'];
}
echo $var['name1']." ".$var['name2'];
?>
Is this what you are looking for?
You'll want to store them in an array, unless you want to go to the trouble of creating dynamic variable names.
<?php
$names = array();
$sql = "SELECT * FROM db";
$result = mysqli_query($con, $sql);
while($row= mysqli_fetch_assoc($result)) {
$var = $row['field_name'];
echo $var."<br>";
// Outputs name1 name2 etc.,
$names[] = $var;
}
echo $names[0];
echo $names[1];
// etc.
As Sahil said in comments extract() is a good option.
extract($row)
$row is an associative array. This function treats keys as variable names and values as variable values.For each key/value pair it will create a variable in the current symbol table
Read more about extract() here
<?php
$sql = "SELECT * FROM db";
$result = mysqli_query($con, $sql);
while($row= mysqli_fetch_assoc($result)) {
extract($row);
//now you can echo each value using its field name
echo $fieldname1;
echo $fieldname2;
}
?>

how to encode json from array push?

i had this php code :
<?php
include "../mainmenu/koneksi.php";
// Start with the list of animals
$sql = "SELECT * FROM data_binatang";
$rows = array();
$res = mysql_query($sql);
for($i=0; $i<mysql_num_rows($res); ++$i){
$row1 = mysql_fetch_assoc($res);
$id_binatang = $row1['id_binatang'];
$sql = "SELECT * FROM data_waktu_vaksinasi WHERE id_binatang = $id_binatang AND (status_vaksin = 'belum' OR status_vaksin IS NULL) ORDER BY tanggal_vaksin ASC LIMIT 1";
$res2 = mysql_query($sql);
$row2 = mysql_fetch_assoc($res2);
$arr[$id_binatang] = array();
array_push($arr[$id_binatang], $row1['nama_binatang'], $row1['id_user'], $row1['jenis_binatang'], $row1['ras_binatang'], $row1['foto_binatang'], $row2['nama_vaksin'], $row2['id_data_waktu_vaksinasi'], $row2['status_vaksin'], $row2['tanggal_vaksin'], $row2['tanggal_datang']);
}
echo "RESULT:";
echo "<table border=1><tr><th>id binatang</th><th>nama binatang</th><th>id user</th><th>jenis binatang</th><th>ras binatang</th><th>foto binatang</th><th>nama vaksin</th><th>id data waktu vaksin</th><th>status vaksin</th><th>tanggal vaksin</th><th>tanggal datang</th></tr>";
foreach($arr as $key => $val){
echo "<tr><td>$key</td><td>".implode("</td><td>", $val)."</td></tr><br>";
}
?>
and here's the result
now i want to generate the table into json, but i don't know what to put inside the json encode, i tried:
echo '{"data_vaksinasi_menu":'.json_encode($arr[$id_binatang]).'}';
but instead it gave me null
Try this:
echo json_encode(array('data_vaksinasi_menu' => $arr));

Convert mysql select results to json (array of arrays)

I need to encode a table content to JSON in order to insert it into a file.
The output has to be as following :
{
"name1":[{"id":"11","name":"name1","k1":"foo","k2":"bar"}],
"name2":[{"id":"12","name":"name2","k1":"foo","k2":"bar"}],
}
Indeed, each JSON "line" corresponds to the content of the mysql row and the name of each JSON array is the name of the 'name' column.
The only thing I could manage for the moment is this :
$return_arr = array();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
$index = 0;
while ($row = mysql_fetch_assoc($result)) {
$return_arr[$index] = $row;
$index++;
}
echo json_encode($return_arr);
And here is the output I get :
[
{"id":"11","name":"name1","k1":"foo","k2":"bar"},
{"id":"12","name":"name2","k1":"foo","k2":"bar"},
]
Thanks a lot !!!
UPDATED
Working code :
$return_arr = array();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$return_arr[ $row['nom_appart'] ][] = $row;
}
echo json_encode($return_arr);
}
You were close. I noticed you want final output to be an object not an array, because the outer brackets are {} not []. So you need a different object type, and you need to use each row's name as the key for storing that row.
$return_obj = new stdClass();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$name = $row['name'];
$return_obj->$name = [$row]; // for PHP < 5.4 use array($row)
}
echo json_encode($return_obj);
This loop is enough, to create the desired JSON:
$return_arr = array();
while ($row = mysql_fetch_assoc($result)) {
$return_arr[$row['name']][] = $row; #or $return_arr[$row['name']] = [$row];
}
echo json_encode($return_arr);
I was working on it a lot of time and Create mash/mysql-json-serializer package.
https://github.com/AndreyMashukov/mysql-json-serializer
You can select Json_array of json_objects and etc. It support ManyToMany, oneToMany, manyToOne relations
SELECT JSON_ARRAYAGG(JSON_OBJECT('id',est_res.est_id,'name',est_res.est_name,'advert_groups',(SELECT JSON_ARRAYAGG(JSON_OBJECT('id',adg.adg_id,'name',adg.adg_name)) FROM advert_group adg INNER JOIN estate est_2 ON est_2.est_id = adg.adg_estate WHERE est_2.est_id = est_res.est_id))) FROM (SELECT * FROM estate est LIMIT 1 OFFSET 2) est_res
<?php
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$return_arr[] = $row;
}
echo json_encode($return_arr);
?>

How can I retrieve data from a database using PHP?

I have a problem with retrieving data from a database using PHP statements. At the moment the output looks like:
[{"Bez":"Cino"},{"Bez":"Extra"},{"Bez":"Panini"},{"Bez":"And so on"}]
"Bez" is the label of the column and we don't want it to be displayed. We just want to display the cell's contents so it should look like:
[Cino,Extra,Panini,And so on]
The php is:
<?php
$username = "root";
$database = "kaffeehaus";
mysql_connect('localhost', $username);
#mysql_select_db($database) or die("Geht nicht!");
$query = "SELECT Bez FROM kategorie";
$result = mysql_query($query) or die(mysql_error("error"));
$num = mysql_numrows($result);
mysql_close();
$rows = array();
while ($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
echo json_encode($rows);
?>
Replace
$rows[] = $r;
With
$rows[] = $r['Bez'];
...though to be honest, I'd replace the whole "fetch" part with:
while($r = mysql_fetch_row($result))
$rows[] = $r[0];
That's because mysql_fetch_row is generally faster than mysql_fetch_assoc.
Replace
while ($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
with this:
while ($r = mysql_fetch_array ($result, MYSQL_ASSOC))
{
$rows[] = $r['Bez'];
}
Use mysql_fetch_row() instead (or mysql_fetch_array($result, MYSQL_NUM);). It fetches a numerical array so the column names are not shown.
Then, your output will look something like this:
[{"0":"Cino"},{"1":"Extra"},{"2":"Panini"},{"3":"And so on"}]
Remove the json_encode part:
echo json_encode($rows); ?>
And use bez as row key:
echo ($rows['bez']); ?>
And how does it work if there are more than one cell?
Our php looks like
<?php
$username = "root";
$database = "kaffeehaus";
mysql_connect('localhost', $username);
#mysql_select_db($database) or die("Geht nicht!");
$ID_Kategorie = $_GET["Kategorie"];
$query = "SELECT * FROM artikel WHERE ID_Kategorie=$ID_Kategorie";
$result=mysql_query($query) or die("error");
$num = mysql_numrows($result);
mysql_close();
$rows = array();
while ($r = mysql_fetch_assoc($result))
{
$rows = $r;
}
echo json_encode($rows); ?>
And the output like:
[{"ID_Artikel": "12","ID_Kategorie":"19","Bez":"blabla","Beschreibung":"blabla"}]
But it schould look like:
[{"12","19","blabla","blabla"}]

Categories