How to add an entry to mysqli array - php

I am trying to add a single column at the beginning of a csv file using the code below:
while ($row = mysqli_fetch_array($rows, MYSQL_ASSOC)) {
$list = "'2795', $row";
fputcsv($output, $list);
}
What am I missing? I know it's something simple. Thank you in advance.

You can't just join those values together:
$list = "'2795', $row";
Since $row returns a row result array, treat it as such, push that value inside:
$output = fopen('whatevername.csv', 'a+');
while ($row = mysqli_fetch_array($rows, MYSQLI_ASSOC)) {
$row[] = '2795'; // `$row` is an associative array
fputcsv($output, $row);
}
fclose($output);
Sidenote: This is a truncated code, so just make sure you have that file handle above this code that you presented.

Related

PHP array_push overwriting the pushed data

I seeing a rare behavior of the array_push php function. It's like when I'm looping through the result rows of the query and pushing the complete array of data into a 'parent' array ($rdo), the values are beeing modified with the ones of the last row added.
This is my code:
$rdo = array();
if($sentencia = $general_con->prepare("SELECT monthly_price, name FROM subscription_plan WHERE deleted=0"))
{
$sentencia->execute();
$sentencia->store_result();
$num_of_rows = $sentencia->num_rows;
$sentencia->bind_result($row['monthly_price'], $row['name']);
while($sentencia->fetch())
{
array_push($rdo, $row);
echo print_r($rdo,1).'<br/><br/>';
}
$sentencia->close();
die();
}
And this is the result:
It looks like this is an artifact of the way bind_result() uses references to the array elements. When you push $row onto $rdo, this is updating all those array elements.
I recommend you move away from using bind_result() and use fetch_assoc().
if($sentencia = $general_con->prepare("SELECT monthly_price, name FROM subscription_plan WHERE deleted=0"))
{
$sentencia->execute();
$result = $sentencia->get_result();
while($row = $result->fetch_assoc())
{
array_push($rdo, $row);
echo print_r($rdo,1).'<br/><br/>';
}
$sentencia->close();
die();
}

Array push rows from SQL 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'], ''));
}

array_push mysqli $row return the same data

I have a data base return array as such
$row['id']=1, $row['col1']='col1', $row['col2']=col2
when i push each $row to $result
array_push($result, $row);
the $row is overwritten b/c they share the same key. I can't get my mind around it. but if it is overwritten, when I var_dump($result) it should output only one set, instead it output multiple row with the same set of data, please help.
replace this: array_push($result, $row);
with this:
foreach($row AS $current_row)
{
array_push($result, $current_row);
}
I'm not sure to understand.
If you want to add $row in $result, you can use array_merge() function like this:
$result = array_merge($result, $row);
array_push adds elements to 2 or more dimension array. Before using it you must define an array. Use this:
$result = array();
while ($row = $stmt->fetch())
{
array_push($result, $row);
}

Exporting data from database to csv file using php

I am able to export database to csv but my code somehow imports twice the data to my csv file. I.e same column twice side by side.this is my code. I think my problem is with the implode statment. Any help would be appreciated.
<?php
$db = new sqlite3('I:\preethi\webbs.db');
$headers = array
('Id','CompanyId','DateTime','Serial','DeviceId','AgentAId','GpsAddress','Targa','CommonRoadDescription'
,'RoadCivicNumber','VehicleBrandDescription','VehicleModelDescription' ,'VerbaliVehicleTypeDescription','CommonColorVehicleDescription','VerbaliRuleOneCode','VerbaliRuleOneDes
cription','VerbaliRuleOnePoints'
,'VerbaliClosedNoteDescription','Points','VerbaliMissedNotificationDescription
','MissedNotificationNote','StatementNote');
$results = $db->query('select'.implode (',',$headers).'from VerbaliData');
//$results = $db->query( 'select
Id ,CompanyId ,DateTime ,Serial ,DeviceId ,AgentAId
,GpsAddress ,Targa ,CommonRoadDescription ,RoadCivicNumber ,VehicleBrandDescription
,VehicleModelDescription ,VerbaliVehicleTypeDescription ,CommonColorVehicleDescription
,VerbaliRuleOneCode ,VerbaliRuleOneDescription ,VerbaliRuleOnePoints ,VerbaliClosedNoteDescription
,Points ,VerbaliMissedNotificationDescription ,MissedNotificationNote ,StatementNote from
VerbaliData');
$fp = fopen('explores.csv', 'w');
fputcsv($fp,$headers);
while ($row = $results->fetchArray()) {
fputcsv($fp, $row);
}
fclose($fp);
?>
Just try with :
while($row = $results->fetchArray(SQLITE3_NUM)) {
Or
while($row = $results->fetchArray(SQLITE3_ASSOC)) {
More Details: http://php.net/manual/en/sqlite3result.fetcharray.php
You have a slight prob in your code fetchArray() returns two array sets one associative and one is numbered, use fetchArray(SQLITE3_NUM) or fetchArray(SQLITE3_ASSOC).

json showing duplicate output of mysql result

I am trying to print json_encode and I get output duplicated. I am certain there is one single record in database and yet it shows the same record data twice in various format. This is it:
[{"0":"Polo","name":"Polo","1":"City ","location":"City ","2":"Manama","city":"Manama"}]
The code behind this is:
$dataArray = array();
while($r = mysql_fetch_array($result))
{
$dataArray[] = $r;
}
print json_encode($dataArray, JSON_UNESCAPED_UNICODE);
Any idea?
This is because the default behavior of mysql_fetch_array() is to return both a column name and index keyed array.
Use mysql_fetch_assoc() or set the second parameter of mysql_fetch_array().
while($r = mysql_fetch_assoc($result)) {
$dataArray[] = $r;
}
You should set another fetch style. It now fetches all columns using both their 0 based index and their name.
This should work as expected:
$dataArray = array();
while($r = mysql_fetch_array($result, MYSQL_ASSOC))
{
$dataArray[] = $r;
}
print json_encode($dataArray, JSON_UNESCAPED_UNICODE);
You're getting this because you can access the results either by name or by column index, but you're serializing the entire thing, so both ways of getting the data are showing up.
try this
//$dataArray = array();
while($r = mysql_fetch_array($result))
{
$dataArray[] = $r;
}
print json_encode($dataArray, JSON_UNESCAPED_UNICODE);
I commented first line. Because you used like that $dataArray[].

Categories