Generating 2-dimension array in PHP with SQL query - php

looking for generating a multi-dimensional array in php (2 for now, more later) with SQL query results, in order to push it in a CSV file later. I want each line "each member" to contain 2 rows, "name" and "surname".
I'm trying this:
$table_echo ="";
$sql='SELECT * FROM members;
$nb = $bdd->query($sql);
while($result = $nb->fetch()){
$table_echo.= array($result['name'],$result['surname']).",";
}
$data = array(
$table_echo
);
inspired from the following example (w3schools.com):
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
SQL is OK, so do the CSV file generator (tested and working with the $cars array example), but the output CSV file is empty with the first code. What am I getting wrong? Can I use a "while" inside the $data array definition ? Is there an other way to do this? Thanks

I will use variables from the car example for better understanding
$cars = array();
// ... sql
while($result = $nb->fetch()){
$cars[] = array($result['name'],$result['surname']);
}
// here you have $cars full of data in "correct" structure
this should build the same structure as the cars example

You do not need to create array if your purpose only is to save a file as CSV.
//open csv file - if not exists will create new file
$csv_file = fopen('output.csv', "w");
$sql='SELECT * FROM members';
$nb = $bdd->query($sql);
while($result = $nb->fetch()){
//prepare line
$line = $result['name'].",".$result['surname'])."\n";
//write line to csv file
fwrite($csv_file, $line);
}
fclose($csv_file);

You can do this way
$table_echo ="";
$sql='SELECT * FROM members';
$nb = $bdd->query($sql);
$data = [];
while($result = $nb->fetch()){
$data []= array($result['name'],$result['surname']);
}

Related

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'], ''));
}

Add element and key to array php

I'm trying to add an element to array, but I get a weird output. The code is the following:
$getalltokens = $db->query("SELECT * FROM Tables WHERE available = '$comp'");
while ($row = $getalltokens->fetch(PDO::FETCH_ASSOC))
{
$fid = $row['FID'];
$tok = $row['token'];
$sql = $db->query("SELECT Firstname,Lastname FROM Users WHERE Token = '$tok'");
$rez = $sql->fetch(PDO::FETCH_ASSOC);
$names[] = $rez;
$fidzy = array(
'FID' => $fid
);
array_push($names, $fidzy);
}
$getalltokens = $db->query("SELECT FID FROM Tables WHERE available = '$comp'");
$tokenz = $getalltokens->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($names);
And the output I get is:
[{"Firstname":"Test","Lastname":"Test"},{"FID":"5"},
{"Firstname":"Test2","Lastname":"Test2"},{"FID":"4"}]
While what I need is the FID to be inside the $names array, so it would be more like:
[{"Firstname":"Test","Lastname":"Test","FID":"5"}]
$rez['FID'] = $fid; /* Added */
$names[] = $rez;
/* $fidzy and array_push removed */
You can use instead of array_push() like
$arrayname[indexname] = $value;
if you use array_push()
<?php
$array[] = $var;
?>
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.
Note: `array_push()` will raise a warning if the first argument is not an array. This differs from the `$var[]` behavior where a new array
is created.
Reference Array push
The solution to the specific problem at hand is selecting all the necessary data in a single query, removing the need to add elements to any array. This is done in the following fashion:
$sql = $db->query("SELECT
Users.Firstname,Users.Lastname,Tables.FID
FROM Users,Tables
WHERE Users.Token = Tables.token");
$rez = $sql->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rez);

How to add an entry to mysqli array

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.

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).

Make array with arrays from a mysql query

Working on a e-shop, i must read from the DB the products that have productpack not null.
productpack from the DB looks like this : 0141,3122,0104,0111,3114,0106,0117 .
I'm trying to get all the DB items that have productpack set (not null), and make them into an array with arrays with those codes (0141,3122,0104,0111,3114,0106,0117).
function p_productpacks(){
$productpacks = array();
$pack = array();
$q = mysql_query('SELECT productpack FROM products WHERE productpack <> "";');
while($p = mysql_fetch_object($q)){
$pack = explode(",", $p);
$productpacks[] = $pack;
}
return $productpacks;
}
You need to create an array otherwise, you're overwriting existing packs:
$pack = explode(",", $p->productpack);
$productpacks[] = $pack;
For more information read about array_pushDocs and PHP Arrays Docs (and mysql_fetch_objectDocs).
You can get all productpacks in a CSV array using:
$result = mysql_query("SELECT GROUP_CONCAT(productpack) as productpacks
FROM products WHERE productpack <> '' ");
if ($result) {
$row = mysql_fetch_row($result);
$productpacks_as_CSV_string = $row['productpacks'];
}
That way you only need to get one row out of the database, saving lots of time.
See: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
mysql_fetch_object returns an object and can't be used with string processing.. if you definitely want to use this, you need to do something like:
$pack=explode(',',$p->productpack);
$productpacks[]=$pack
Or, to use a good old array instead:
while ($p = mysql_query($q))
{
$pack = explode(",", $p['productpack']);
$productpacks[] = $pack;
}

Categories