This question already has answers here:
How to check whether an array is empty using PHP?
(24 answers)
Closed 7 years ago.
I am creating a form to filter the data on my database (Mysql) with queries based on the user's selections.
I am using this code to generate the "data.json" file:
How can I improve the code and check if the array returns empty values? and instead of drawing a chart without bars tells the user to change the selections.
<?php
$rows1 = array();
$rows1['name'] = $varLabel;
while($rr = mysqli_fetch_array($TableData)) {
$rows1['data'][] = $rr[$varLabel];
}
$rows = array();
$rows['name'] = "Registros";
foreach($TableData as $r) {
settype($r['cnt'], "integer");
$rows['data'][] = $r['cnt'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
file_put_contents("data.json", json_encode($result));
?>
Since your array is created by looping over your database result set which you access using mysqli, Use mysqli_num_rows
if(mysqli_num_rows($TableData)==0)
{
// no data
}
Related
This question already has answers here:
mysqli_fetch_array Gives Me Duplicate Rows
(4 answers)
Closed 3 years ago.
enter image description here
$table = $this->Execute("select * from data ");
$result = array();
while($row = mysqli_fetch_array($table))
{
array_push($result, $row);
}
return $result;
this my code,
i dont know why my result including the index
Its because of this statement:
while($row = mysqli_fetch_array($table))
You are getting numeric indexes as well as text keys.
Replace this by:
while($row = mysqli_fetch_assoc($table)) // will return only associate (string) keys.
OR
while($row = mysqli_fetch_array($table, MYSQLI_ASSOC)) // will return only associate (string) keys.
This will not include numeric indexes.
References:
mysqli_fetch_assoc()
mysqli_fetch_array()
This question already has answers here:
mysqli query results to show all rows
(4 answers)
Sql array only showing first result
(4 answers)
Closed 5 years ago.
I have write these kind of codes multiple times and it always worked great but now that I am on a different system it shows only 1 result.
the query is simple
$HOST = 'localhost';
$USERNAME = 'root';
$PASSWORD = '';
$DATABASE = 'db_test';
$con = mysqli_connect($HOST,$USERNAME,$PASSWORD,$DATABASE);
$sql = "SELECT * FROM test ";
$res = mysqli_query($con,$sql);
$res_array = mysqli_fetch_assoc($res);
echo json_encode($res_array);
mysqli_free_result($res);
mysqli_close($con);
I wonder if there is any settings that I have to change before running the app
Seriously, it's all over the docs:
mysqli_fetch_assoc Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.
Note "the fetched row" part.
You need to do put your gathering in a cycle
$rows = [];
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row
}
json_encode($rows);
This line $res_array = mysqli_fetch_assoc($res); will only fetch one record.
You need to loop over result-set object and get all data from that.So use while() loop like below
$res_array =[];
while($row = mysqli_fetch_assoc($res)){
$res_array[] = $row;
}
Reference:-
mysqli_fetch_assoc()
Replace this line
$res_array = mysqli_fetch_assoc($res);
with
while ($row = mysqli_fetch_assoc($res)) {
$res_array[] = $row;
}
This question already has answers here:
How to load MySQLi result set into two-dimensional array?
(3 answers)
Closed 6 years ago.
Looking at all the questions are using the depreciated mysql_fetch_assoc/array, hence I don't think that this is a duplicate question.
I have a MySQL table with 5 columns,
ID | NAME | AGE | GENDER | HEIGHT
If I want to store the values of NAME, AGE, GENDER in a PHP array,
$query=$mysqli->query("SELECT NAME,AGE,GENDER FROM TableName")
while($result = $query->fetch_assoc()
{
$array = [];
}
Will my array be stored in the format of
$array=[[Name,Age,Gender],[Name,Age,Gender]]?
If not, what would be my approach in doing this?
It's very simple. You just have to append the result variable in to main array. Like this,
$array =array();
while($result = $query->fetch_assoc()
{
$array[] = $result;
}
$result is an array (fetch_assoc it returns result-set in array) so just append that into main array to get the desired result. ($array=[[Name,Age,Gender],[Name,Age,Gender]])
$data =[];
$i=0;
while($result = $query->fetch_assoc(){
$data[$i][] = $result;
$i++;
}
This question already has answers here:
Creating an array from a MySQL table
(2 answers)
Closed 10 years ago.
I am using PHPlot to make a graph.
I have an issue in generating the array from a MySQL table.
Basivally, I want to array is as follows:
$values = array($arrayx);
array('a',-3),
array('b',5),
array('c',7),
array('d',8),
array('e',12),
array('f',-6),
//);
$graph->SetDataValues($values);
$graph->SetXTickPos('none');
$graph->SetXTickLabelPos('none');
Part of the code where I tried to retrieve values from table to feed the array
$query="SELECT * FROM tasks";
$result=mysql_query($query);
//using a for loop to add values to the array
while ($resource=mysql_fetch_array($result)){
$thedate = $resource["date"];
$title = $resource2["title"];
$innerarray = "array('.$thedate.', $title),";
}
$values = array($innerarray).");";
$graph->SetDataValues($values);
$graph->SetXTickPos('none');
$graph->SetXTickLabelPos('none');
//Draw it
$graph->DrawGraph();
}
The way I'm doing the $innerarray and $values seems wrong. Can you please help me fix it?
Thank you
try replacing
$innerarray = "array('.$thedate.', $title),";
with
$innerarray = array($thedate, $title);
$new = array();
while(for condition ){
$new[] = '\''.thedate[$i].''\','.$title[$i].'\';
}
var_dump($new);
this an idea, you need to edit the code to make it working
I assume it is this that you want:
$sql="SELECT datefield, titlefield FROM tasks";
....
while (list($thedate,$thetitle) = mysql_fetch_array($result)) {
$values[] = array($thedate,$thetitle);
}
echo $values[0][0]; // will output your 1st date
echo $values[0][1]; // will output your 1st title
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JSON encode MySQL results
I want to use php to create a json object like below. it will return a string as a response from result sql query.
{"Orders":[
{"DeliveryId":"DeliveryId","CustomerName":"CustomerName","PhoneNumber":"PhoneNumber","Address":"Address"},
{"DeliveryId":"DeliveryId","CustomerName":"CustomerName","PhoneNumber":"PhoneNumber","Address":"Address"}
]
}
my code
<?php
mysql_connect("mysql12.000webhost.com","a4602996_longvan","longvan2012");
mysql_select_db("a4602996_lv");
$id=$_POST[user];
$sql=mysql_query("select * from testlongvan where Status = 'PACKED'" );
$json = array();
if(mysql_num_rows($sql)){
while($row=mysql_fetch_row($sql)){
$json['Orders'][]=$row;
}
}
//while($row=mysql_fetch_assoc($sql))
//$output[]=$row;
print(json_encode($json));
mysql_close();
?>
But when use my code the result is not what I expected:
{"Orders":[
["longvan","10/12/2012","Be34433jh","Long Van","115 Pham Viet Chanh, quan Binh Thanh","http://longvansolution.tk/image/sample.jpg","PACKED","0909056788"],
["takeshi","24/12/2012","BF6464633","Vn-zoom","16 nguyen cuu van, quan binh thanh","http://longvansolution.tk/image/hoadon3.jpg","PACKED","098897657"]
]}
Can you help me?
You have to create an array for each row to specify the field name and value.
$json['Orders'][] = array('DeliveryId' => $row[0], 'CustomerName' => $row[1], ...);
Or use mysqli_fetch_assoc() function if the table column name is exactly what you want to use in your JSON:
$rows = array();
while($r = mysqli_fetch_assoc($sql)) {
$rows[] = $r;
}
$data = array('Orders' => $rows);
print json_encode($data);