I am trying to fetch records from MySql and display them in an array along with column headers using PDO, reason I am doing this is because i want to export them in an excel and I am using php-excel
right now the following code displays the records perfectly fine in an array and I am able to export them just fine
while ($row[] = $stmt->fetch(PDO::FETCH_ASSOC)) :
$data = $row;
endwhile;
The array i get as a result of above code is as following
Array
(
[0] => Array
(
[user_id] => 1
[fname] => First Name
[lname] => Last Name
)
[1] => Array
(
[user_id] => 91
[fname] => First Name
[lname] => Last Name
)
)
But the problem is I am missing column headers in excel, so for that I need to display the MySql column headers in an array as well.
I am using the following code to create an array for column headers
for ($i = 0; $i < $stmt->columnCount(); $i++) {
$col = $stmt->getColumnMeta($i);
$columns[] = $col['name'];
}
but this gives me an array in following format
Array
(
[0] => user_id
[1] => fname
[2] => lname
)
whereas I need the column header array in following format
Array
(
[0] => Array
(
[user_id] => user_id
[fname] => fname
[lname] => lname
)
)
I will appreciate any help.
I assume you want the headers to be in the same array. In that case you would do this before the while loop
$data[0] = array();
for ($i = 0; $i < $stmt->columnCount(); $i++) {
$col = $stmt->getColumnMeta($i);
$data[0][$col['name']] = $col['name'];
}
Also, the while loop is a little inefficient. You're pushing each row into the $row array and then copying it into $data every single time. It should be done like this instead:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) :
$data[] = $row;
endwhile;
This should get you:
$data = Array
(
[0] => Array
(
[user_id] => user_id
[fname] => fname
[lname] => lname
)
[1] => Array
(
[user_id] => value...
...
)
...
)
Instead of letting it auto-number, just provide the name again as the key:
for ($i = 0; $i < $stmt->columnCount(); $i++) {
$col = $stmt->getColumnMeta($i);
$columns[$col['name']] = $col['name'];
}
Example: https://eval.in/117424
Might be easier:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if(!isset($data)) {
$data[] = array_combine(array_keys($row), array_keys($row));
}
$data[] = $row;
}
Or you could add them after the fact using array_unshift().
Or in a separate array:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if(!isset($col)) {
$col[] = array_combine(array_keys($row), array_keys($row));
}
$data[] = $row;
}
Related
I am working on online TV series website and can't figure out this one need to get values from array which is inside array.
This is structure contains $seasons variable:
Array
(
[0] => Array
(
[0] => link1-1
[1] => link1-2
[2] => link1-3
)
[1] => Array
(
[0] => link2-1
[1] => link2-2
[2] => link2-3
)
)
i need to get values like:
0
link1-1
link1-2
link1-3
1
link2-1
link2-2
link2-3
and then put them inside html video tag, but i can't figure out how to get values correctly
tried:
while ($row = $result->fetch_assoc()) {
$season_count = $row['season_count'];
$seasons = array_map("str_getcsv", explode("___", $row['en_url']));
array_shift($seasons);
for($i = 0; $i < count($seasons); $i++){
print_r($seasons[$i][*]); // i need equivalent of * to select all values of each array
}
break;
}
foreach ($seasons as $season){
foreach ($season as $link) {
echo '<video src="' . $link . '"><video>';
}
}
And next time - please formulate your task clearly.
I am having issues getting an array into a CSV file, I can get the output into the CSV file now, however it is only printing the following into the CSV file:
objectId createdAt
Array Array
Array Array
Array Array
Array Array
Array Array
Array Array
Array Array
I believe it is because I need to flatten the array, but am at a loss on how to do it, I am pretty much picking up how to work with arrays & parse.com as I go, I do however have good knowledge of PHP, My code is as follows:
$query = new ParseQuery("Counts");
$results = $query->find();
for ($i = 0; $i < count($results); $i++)
{
$detail=array();
$object = $results[$i];
$detail['objectId'][$i] = $object->getObjectId();
$detail['createdAt'][$i] = $object->getCreatedAt();
// print_r($detail);
$response[]=$detail;
}
$output = fopen('php://output', 'w');
header("Content-Type:application/csv");
header("Content-Disposition:attachment;filename=dboutput.csv");
fputcsv($output, array('objectId','createdAt'));
foreach ($response as $fields) {
fputcsv($output, $detail);
}
fclose($output);
instead of it outputting Array I need it to output the stored information, which is stored in my parse.com DB (createdAt = date & objectId = string).
If it helps the array looks like the following:
Array
(
[date] => Array
(
[0] => eGocH6OznC
)
[createdAt] => Array
(
[0] => DateTime Object
(
[date] => 2015-12-11 23:02:03.968000
[timezone_type] => 2
[timezone] => Z
)
)
)
Array
(
[date] => Array
(
[1] => P3uhKFzpsq
)
[createdAt] => Array
(
[1] => DateTime Object
(
[date] => 2015-12-11 23:16:55.633000
[timezone_type] => 2
[timezone] => Z
)
)
)
I need to get just the Date value & objectId value into 2 columns of a CSV file.
Any guidance on this is greatly appreciated.
The correct code for doing this is:
$query = new ParseQuery("Counts");
$results = $query->find();
$detail=array();
for ($i = 0; $i < count($results); $i++)
{
$object = $results[$i];
$detail[$i]['objectId'] = $object->getObjectId();
$detail[$i]['createdAt'] = $object->getCreatedAt()->format('Y-m-d H:i:s');
}
$output = fopen('php://output', 'w');
header("Content-Type:application/csv");
header("Content-Disposition:attachment;filename=dboutput.csv");
fputcsv($output, array('objectId','createdAt'));
foreach ($detail as $fields) {
fputcsv($output, $fields);
}
fclose($output);
?>
Fetch all rows based on the query into an array and return single value
Query database for data
//----------------------------------------------------------------------
$result = mysql_query("SELECT * FROM $tableName"); query
$array = mysql_fetch_row($result);
fetch result In Array
$arr = array();
while ($row = mysql_fetch_assoc($result)) {
$arr2 = array();
foreach ($row as $val) $arr2[] = $val;
$arr[] = $arr2;
}
Result Will Be
Array
(
[0] => Array
(
[0] => status_site
[1] => 0
)
[1] => Array
(
[0] => title_site
[1] => Script
)
[2] => Array
(
[0] => keys_site
[1] =>
)
)
I need to make function that return element 0 to 1
ex: function getsetting (title_site){
return value script}
Replace the $arr[] = $arr2; with $arr[$arr2[0]] = $arr2[1];. That might solve your problem.
I've a $_POST that sends an array. And i've a prevoious array with contains a key that could contain or not one of the values from teh $_POST.
For Example:
$_post: Array ( [0] => 13 [1] => 10 [2] => 52)
Previous: Array ( [0] => Array ( [collection_id] => 13 [artwork_id] => 21 )
[1] => Array ( [collection_id] => 11 [artwork_id] => 21 ) )
So i need to check if the $_POST itms already exists on the previuos array ([collection_id] key) and extract the new ones (in this case [1] => 10 [2] => 52) to ve added to the database and also get those which has changed that need to be removed from the database (replaced) by the new values.
This my current code but not working well...
$new_nodes = array();
$i = 0;
foreach($old_nodes as $node){
foreach ($collections as $collection) {
$new = array('collection_id' => $collection, 'artwork_id' => $artwork['id']);
if(array_diff($node, $new)){
if($collection > 0){
array_push($new_nodes, $new);
}
}
else{
unset($old_nodes[$i]);
}
}
$i++;
}
foreach($new_nodes as $node){
for ($i = 0; $i <= count($new_nodes); $i++) {
if(isset($new_nodes[$i])){
if(!array_diff($node, $new_nodes[$i])){
unset($new_nodes[$i]);
}
}
}
}
NOTE: old_nodes is "Previous" and $collections is "$_POST"
Try something like this:
$old_nodes = array();
$new_nodes = array();
$del_nodes = array();
foreach ($collections as $collection) {
array_push($old_nodes, $collection['collection_id']);
}
$new_nodes = array_diff($collections, $old_nodes);
$del_nodes = array_diff($old_nodes, $collections);
Hello I have an array that looks like this,
Array
(
[cfi_title] => Mr
[cfi_firstname] => Firstname
[cfi_surname] => Lastname
[cfi_email] => test#test.co.uk
[cfi_subscribe_promotional] =>
[cfi_tnc] =>
[friendsName] => Array
(
[0] => Firstname 1
[1] => Firstname 2
[2] => Firstname 3
)
[friendsEmail] => Array
(
[0] => email1#address.com
[1] => email2#address.com
[2] => email3#address.com
)
[submit_form] => Submit
)
My dilema is I need to save the values from the friendsName and friendsEmail arrays into a database, I know I can loop through them but how can I send the matching data, for example I need to save [friendsName][0] and friendsEmail][0] on the same row of database?
I know I need to use a foreach but I just cannot figure out the logic.
foreach($friendsName as $key=>$val) {
$friend = $val;
$email = friendsEmail[$key];
}
or
$count = count($friendsName);
for($i = 0; $i< $count; ++$i) {
$friend = $friendsName[$i];
$email = $friendsEmail[$i];
}
Each of the above examples are using the assumption that the array key is the matching identifier between the two bits of data
Complete solution
//Prepare an array for the collected data
$data = array();
//Loop through each of your friends names
foreach($array['friendsName'] as $key => $value)
{
//Save the name as part of an associative array, using the key as an identifier
$data[$key] = array("name" => $value);
}
//Loop through the emails
foreach($array['friendsEmail'] as $key => $value)
{
//The array is allready there so just save the email
$data[$key]['email'] = $value;
}
$datanow contains your values paired up.