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++;
}
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:
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
}
This question already has answers here:
Finding the position of an element in a simple array
(2 answers)
Closed 8 years ago.
I search a database that returns a bunch of values. These values are stored into an array called $result_array. I then want to find the position of an element within that array. Here is my current code
public function cardPosition($cid, $did) {
$query = "SELECT cid FROM card WHERE did = '$did' ORDER BY id ASC";
$result = mysql_query($query);
$result_array = array();
while($row = mysql_fetch_assoc($result)) {
$result_array[] = $row;
}
while ($correct_cid = current($result_array)) {
if ($correct_cid == $cid) {
$cardPosition = key($result_array);
}
next($result_array);
}
return $cardPosition;
}
I use mysql_fetch_assoc() because I want to assign every element a key value. I then use the second while loop to search for the element in the array that is the $correct_cid value. I then assign the value of the key to $cardPosition but when I return $cardPosition I get nothing. How can I get the position of the element within the array?
Update
I have used
$position = array_search($cid, $result_array);
but still get nothing as a result.
I know my query works because I ran
$num = mysql_num_rows($result);
and I get the correct number of rows.
you can find the position of array with array_search() function. suppose we have an array.
$a = array(
'blue' => 'nice',
'car' => 'fast',
'number' => 'none'
);
echo array_search("car",array_keys($a));
$position = array_search("search_text", $result_array);
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:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 1 year ago.
Likely a remedial question, but in all my days as a PHP user I have yet to encounter an answer. Basically, is there any way to grab a single field of a "mysql_query" as an array? For instance say I have the following:
$query = "Select id,first_name,last_name FROM people";
$result = mysql_query($query);
Is there any way to grab each (id, first_name, last_name) as individual arrays without iterating through the recordset? Can I say something like:
$ids = field_to_array($result['id']);
$first_names = field_to_array($result['first_name']);
$last_names = field_to_array($result['last_name']);
As I said, in the past I've always simply built the arrays as needed, but an existing method would be handy.
mysql doesn't have that as a native function. you could always write your own..
function mysql_convert_cols($dataset) {
foreach ($dataset as $row => $values) {
foreach ($values as $column => $value) {
$return[$$column][$row] = $value;
}
}
return($return);
}
$resultConverted = mysql_convert_cols($result);
$id=$resultConverted['id'];
$firstName=$resultConverted['firstName'];
I'm not sure why do you need this , but you can do it like this :
$resultArray = array();
while($row = mysql_fetch_array($result)){
$resultArray[] = array(
"id" => $row['id'],
"firstName"=>$row['first_name'],
"lastName"=>$row['last_name']
);
}
Check if values are in :
print_r($resultArray);
Then you can foreach or to do the for loop on values.