Trying to return a DB resultset as an array in my DAO:
I want to append string key-values to the array $retval in the below code. However, the array keeps getting overwritten each iteration instead of being appended to.
So at the end of the loop, I end up with 1 key-value instead of n pairs (n rows retrieved from the database). What am I doing wrong?
$retval = array();
while ($row = mysql_fetch_assoc($result)) {
foreach($columns as $var) {
$retval[$var]=$row[$var];
}
}
var_dump($retval);
$retval ends up as ["name"=>"Japan","capital"=>"Tokyo"] instead of the expected ["name"=>"Korea","capital"=>"Seoul"...."Japan"=>"Tokyo"] where columns are name and capital.
I'd have to see what your columns are, but shouldn't it be:
$retval = array();
while ($row = mysql_fetch_assoc($result)) {
$retval[ $row['country'] ] = $row['capital'];
}
It is because you are overwriting the same value (column name here.) Something like:
$retval['a'] = 1;
$retval['a'] = 2;
// ...
Instead use:
$retval[] = $row[$var];
HTH.
Related
I have a simple question. I have an array that has two columns (id, name) that is a result of a MySQL query. I want to store the result of the query into a array variable so i can access each element when i need to.
I am able to store a one dimension array like the following:
$array = array();
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row['name'];
}
How can I store and access a two dimensional array? Also is it best to use a for loop or while loop to store these?
Simply do this:
$array = array();
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
To access your results you can do this:
$firstResultRow = $array[0];
$firstResultName = $array[0]['id'];
$firstResultName = $array[0]['name'];
This will tell you if a particular row exists:
if(isset($array[$x])) {
$aRow = $row[$x];
// do stuff with $aRow;
}
This will give you a row count for your array:
$rowCount = count($array);
This will set up a loop through your array:
foreach($array as $index => $row) {
$id = $row['id']
$name = $row['name'];
// $index will have the array index of the current row. 0 -> $rowCount - 1
}
Don't specifically store the index of $row but rather store the whole row.
$array = array();
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
Then $array will have the following structure:
$array = [
[
'id'=> ...,
'name' => ...,
],
...
];
To initially access all of the results from [mysqli_fetch_assoc][1] you will want to use the while loop like you are, mysqli_fetch_assoc will continue to output results until it doesn't have any more data. Then at that point mysqli_fetch_assoc will return NULL. This will signal to your while loop to stop iterating.
Then to access variables inside of your $array, I recommend using foreach.
You could then do:
foreach ($array as $row) {
do something with $row['name'] or $row['id']
}
You could also use a for loop, but it takes more work IMO. Compare the above with this alternative:
for ($i = 0; $i < count($array); $i++) {
$row = $array[$i];
do something with $row['name'] or $row['id']
}
I am trying to do a mysql fetch but it keeps adding numbered and labeled keys to the array. I want it to record only the labeled names and data in the array.
Am I using the wrong mysql call?
global $con,$mysqldb;
$sql="SHOW FIELDS FROM ".$dbtable;
$tr = mysqli_query($con,$sql);
$tl = mysqli_fetch_array($tr);
$tl = mysqli_fetch_array($tr);
$sql="SELECT * FROM ".$mysqldb.".".$dbtable." ORDER BY ".$tl['Field']." LIMIT 3";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$table[$row[1]] = $row;
}
foreach($table as $item => $data){
foreach(array_keys($data) as $pointer => $field) {
echo"pointer=".$pointer."\t";
echo"field=".$field."\n";
echo "data=".$data[$field]."\n";
}
}
reults
pointer=0 field=0 data=3823
pointer=1 field=PID data=3823
pointer=2 field=1 data=AA
pointer=3 field=symbol data=AA
pointer=4 field=2 data=1
pointer=5 field=value data=1
I want to omit 0, 2, & 4 from the array.
Take a look at the PHP.net manual for the mysqli_fetch_array() function.
You'll see there's an option called resulttype that will accept 1 of 3 values - MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH the default.
Using MYSQLI_ASSOC will remove the numbered keys.
Or check mysqli_fetch_assoc().
Thanks to thebluefox for a speedy response.
I replaced the fetch with:
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
And now the results are being recorded as they should.
Im trying to set the indexes of a 2d PHP array from numeric indexing to keys. What I have so far is :
$result = mysql_query("SELECT * FROM settings");
if(mysql_num_rows($result) > 0 ){
while($row = mysql_fetch_assoc($result)){
$dataArray[] = $row ;
}
}
$value_to_display = $dataArray[0]['value'];
However, what I'd like to be able to use is something like this :
$value_to_display = $dataArray['some_index_value']['value'];
Anyone know how I can achieve this ? Ive tried replacing making a keys array and then using combine, but I can only do this manually. Any help is appreciated!
How about
while ($row = mysql_fetch_assoc($result)) {
$dataArray[$row['somefield']] = $row;
}
Assuming that somefield is unique, you'll get an array keyed by that field's values. If you need to key names to come from somewhere else, e.g.
$keynames = array('foo', 'bar', 'baz', ....);
$idx = 0;
while($row = mysql_fetch_assoc($result)) {
$dataArray[$keynames[$idx]] = $row;
$idx++;
}
just make sure you have enough keynames to handle all the records you get back from the query.
I am trying to save the rows (results) from an SQL query to a csv file.
I am using array push in order to put the results in a list. Later I put the data from this list to my csv file.
My code :
while ($row = $query->fetch_assoc())
{
echo sprintf( $row['campaign']);
array_push($list, $row['campaign']);
}
The results are there because sprintf works. The problem is with the syntax of array_push. I even tried :
array_push($list, array(''.$row['campaign']);
I am getting an error:
fputcsv() expects parameter 2 to be array
The full code is here :
$list = array
(
array('old_campaign_name', 'new_campaign_name')
);
// table 1
$sql = ('select distinct(campaign) as campaign from '.$table1.'');
// Run the query
$query = $Db->query($sql);
// Check for SQL errors
if ($Db->error)
{
return ($Db->error);
}
// Put data in the list
while ($row = $query->fetch_assoc())
{
echo sprintf( $row['campaign']);
array_push($list,$row['campaign'],'');
}
$fp = fopen($location, 'w');
foreach ($list as $fields)
{
fputcsv($fp, $fields);
}
fclose($fp);
As the error says, fputcsv expects each row that you put to be an array, so it can write it out with commas separating the elements. $list should be a 2-dimensional array, so you need to push an array onto it when you're building it.
while ($row = $query->fetch_assoc() {
$list[] = array($row['campaign']);
}
BTW, $list[] = x is equivalent to array_push($list, x).
When you initially create the $list array, it is an array containing one array. But when you add more values to it from your query results, you are pushing strings onto the end of it, not arrays. In effect, you will be making something like
$list = array (
array('old_campaign_name', 'new_campaign_name'),
'first campaign',
'second campaign',
'etc.',
...
);
Because of this, when you loop over $list, the first value should work with fputcsv, because it is an array, but any subsequent values will be strings instead of arrays and will cause the error you are seeing.
You should be able to fill the $list like this:
while ($row = $query->fetch_assoc()) {
$list[] = $row;
}
$list[] = $row will not overwrite the values previously in $list. From the PHP documentation for array_push:
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
It works like this :
while ($row = $query->fetch_assoc())
{
// array_push($list,$row['campaign'],'');
array_push($list,array($row['campaign'], ''));
}
I want to show string outside while loop, but it only shows one result.
while($row = $result->fetch_assoc()) {
$myarr = array();
}
echo $myarr;
This shows only one result but I need all the results outside the while loop.
Could you please help me how is this possible?
I am not sure if you want the whole row returned from the query or just a single field.
If its the whole row then try
$myarr = array(); // initialize
while($row = $result->fetch_assoc()) {
$myarr[] = $row;
}
print_r($myarr);
This will give you an array containing n row arrays.
Problem :
You are just assigning the result one after again
$myarr = array();
Here, It means you're assigning the array() again and again, which replaces the old value
Solution / What You should do
1. You can assign it to an Array (Good Approach)
while($row = $result->fetch_assoc()) {
$myarr[] = $row['yourdbitem']; // or $row if you want whole row
}
print_r($myarr);
2. You can concat in each iteration (Bad Approach)
$somevariable = '';
while($row = $result->fetch_assoc()) {
$somevariable .= $row['yourdbitem']; // or $row if you want whole row
}
echo $somevariable
Note :
I have given good and bad approach to updating what you should do and what you should not do :)