Coming up empty on this one and could use some insight.
I'm try to select only certain column_names (not column data) to set as a header for CSV file.
Right now, I can only pull all of the column names with
$result = mysql_query("SHOW COLUMNS FROM ".$table);
The problem is that it pulls all of the column names and I'm only wanting certain columns' data. To get the data values this query is working perfectly:
$values = mysql_query("SELECT ".$columns." FROM ".$table." WHERE channel_id=26");
How do I select or show only the column names for the columns I list out in $columns, for example?
EDIT - I'm adding my full PHP here to provide more context. Line 7 is my problem.
<?php
$table = 'exp_channel_data'; // table we want to export
$columns = 'entry_id, field_id_26, field_id_27, '; // only the columns we want to show
$file = 'registrations-from-web'; // csv name.
$result = mysql_query("SHOW COLUMNS FROM ".$table);
$count = mysql_num_rows($result);
$csv_output = "";
if ($count > 0)
{
while ($row = mysql_fetch_assoc($result))
{
$csv_output .= $row['Field'].", ";
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT ".$columns." FROM ".$table." WHERE channel_id=26");
while ($rowr = mysql_fetch_row($values))
{
for ($j=0; $j<$count; $j++)
{
$csv_output .= $rowr[$j].", ";
}
$csv_output .= "\n";
}
$filename = $file."_".date("d-m-Y_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>
If you know the name of the columns, you can add them and/or print them directly from an array.
If you want to have access to the ones retrieved from the query anyway, you can $result = mysql_fetch_assoc($values); per row, and the keys will always contain the name of the columns since the resulting array is associative.
Try:
$values = mysql_query('SELECT '. $columns. ' FROM '.
$table. ' WHERE channel_id = 26');
print_r(mysql_fetch_assoc($values));
For an insight of the contents of the resulting array.
Now try:
$first = 1;
echo '<table>';
while ($assoc = mysql_fetch_assoc($values))
{
echo '<tr>';
if ($first)
{
foreach ($assoc as $key => $value)
echo "<th>$key</th>\n";
$first = 0;
}
else
{
foreach ($assoc as $key => $value)
echo "<td>$value</td>\n";
}
echo '</tr>';
}
echo '</table>';
If what you want is to print a CSV file:
$columns = Array();
$values = Array();
$first = 1;
for ($i = 0; $assoc = mysql_fetch_assoc($values); ++$i)
{
if ($first)
{
foreach ($assoc as $key => $value)
$columns[] = $key;
$first = 0;
}
else
{
foreach ($assoc as $key => $value)
$values[$i][] = $value;
}
}
$out = fopen('php://output', 'w');
fputcsv($out, $columns);
foreach ($values as $line)
fputcsv($out, $line);
The foreach is repeated on purpose so this example is more clear.
You can query the USER_TAB_COLUMNS table for table column metadata.
SELECT table_name, column_name, data_type, data_length
FROM USER_TAB_COLUMNS
WHERE table_name = 'yourTableName'
so you might be using SQL server - for SQL server use this...
SELECT [name] AS [Column Name]
FROM syscolumns
WHERE id = (SELECT id FROM sysobjects WHERE type = 'V' AND [Name] = 'Your table name')
Type = 'V' for views Type = 'U' for tables
I don't know why I was missing this, but since I'm already having to list out the columns I need, I just needed to turn that string into an array to make is it work.
$column_names = Array($columns);
then later use
$csv_output .= '"'.$rowr[$j].'",';
That worked perfectly without redoing my entire code.
Related
I have a html-form to read out data from an SQL-database. The number of selections is completely free, which means that there are no obligatory fields.
I would like to show the results that meet all selected criteria in a html-table. Here is my code:
<?php
include("../files/zugriff.inc.php");
if (isset($_POST["submit"])) {
$sent = $_POST['sent'];
$datenWerte = array();
$fruitname = $_POST["fruitname"];
$fruitgroup = $_POST["fruitgroup"];
$vegetablegroup = $_POST["vegetablegroup"];
$country = $_POST["country"];
$season = $_POST["season"];
$diameter = $_POST["diameter"];
$color = $_POST["color"];
if(!empty($fruitgroup)) {
$datenWerte['fruitgroup'] = $fruitgroup;
}
if(!empty($vegetablegroup)) {
$datenWerte['vegetablegroup'] = $vegetablegroup;
}
if(!empty($country)) {
$datenWerte['country'] = $country;
}
if(!empty($season)) {
$datenWerte['season'] = $season;
}
if(!empty($diameter)) {
$datenWerte['diameter'] = $diameter;
}
if(!empty($color)) {
$datenWerte['color '] = $color;
}
foreach ($datenWerte as $key => $value) {
$spalten[] = $key;
$werte[] = "'$value'";
}
echo "<b>Results:</b><br><br>";
$sql = "SELECT * FROM fruitdatabase WHERE (" . implode(", ",
$spalten) . ") = (" . implode(", ", $werte) . ")";
$result = mysqli_query($db, $sql);
$data = array();
while($row = $result->fetch_object()){
$data[] = $row;
}
// Numeric array with data that will be displayed in HTML table
$aray = $data;
$nr_elm = count($aray); // gets number of elements in $aray
// Create the beginning of HTML table, and of the first row
$html_table = '<table border="1 cellspacing="0" cellpadding="2""><tr>';
$nr_col = count($spalten); // Sets the number of columns
// If the array has elements
if ($nr_elm > 0) {
// Traverse the array with FOR
for($i=0; $i<$nr_elm; $i++) {
$html_table .= '<td>' .$aray[$i]. '</td>'; // adds the value in
column in table
// If the number of columns is completed for a row (rest of
division of ($i + 1) to $nr_col is 0)
// Closes the current row, and begins another row
$col_to_add = ($i+1) % $nr_col;
if($col_to_add == 0) { $html_table .= '</tr><tr>'; }
}
// Adds empty column if the current row is not completed
if($col_to_add != 0) $html_table .= '<td colspan="'. ($nr_col -
$col_to_add). '"> </td>';
}
$html_table .= '</tr></table>'; // ends the last row, and the table
// Delete posible empty row (<tr></tr>) which cand be created after last
column
$html_table = str_replace('<tr></tr>', '', $html_table);
echo $html_table; // display the HTML table
}
mysqli_close($db);
?>
Unfortunately, it´s not working. Could somebody please help me to find the error?
Than you very much in advance!
enter image description here
This is my code :
$myfile = file_get_contents('/ftpfiles/monitor-data') or die ("Unable");
//$new_array = array_chunk($myfile, 9);
//$new_array = array_filter(explode("\n", file_get_contents('/ftpfiles/monitor-data') or die ("Unable")));
//$length = count($new_array);
//print_r($new_array)
$table = '';
$filearray = explode(" ", $myfile);
//var_dump($filearray);
foreach($filearray as $value)
{
$table .= '<tr><td align = "center">'.$value.'</td></tr>';
}
$table.='</table>';
echo $table;
But I am getting just one row, how can I create 9 columns for one row. I tried using Value[0].. value[8] but just broke whole string into single characters.
You should try to explode your rows as well (as you are doing it with the entire file) :
$myfile = file_get_contents('/ftpfiles/monitor-data') or die("Unable");
$table = '<table border="3">';
$filearray = explode(" ", $myfile);
foreach($filearray as $row) {
// here separate your row that is a string, into an array
$cols = explode(" ", $row);
$table .= '<tr>';
foreach($cols as $value) {
$table .= '<td align = "center">'.$value.'</td>';
}
$table .= '</tr>';
}
$table.='</table>';
echo $table;
Of course, that implies that all your rows will explode in the same amount of columns. If you monitor-data file differs from one line to another, you should adapt the code to parse each row.
I am trying to use PHP to interpret a simple CSV log file and print it out as a table.
The file has three columns - a name, followed by two columns with a 1 or a 0 in either.
E.g.
Test,1,0
Test,0,1
Test2,1,0
Test3,1,0
Test3,0,1
Test3,1,0
Test3,0,1
The goal is to sum all identical rows together to give this:
Test,1,1
Test2,1,0
Test3,2,2
And lastly print this as an HTML table.
So far I have a working solution for summing the first two columns but I don't know how to get it to work to include the third. To outline the entire process, I have an initial PHP script at the start of a web page that logs clicks to a CSV file:
<?PHP
if (isset($_GET['s1'])){
$sub1 = urlencode($_GET['s1']);
$fp1 = fopen ('botlog.csv', 'a+' );
fputcsv ( $fp1, array ( $sub1, '1', '0' ), ",", '"' );
fclose ( $fp1 );}
?>
Later I have a second script, loaded in an iFrame with a JS delay, that logs a similar value but to the third column rather than the second:
<?PHP
if (isset($_GET['sub1'])){
$sub2 = urlencode($_GET['sub1']);
$fp2 = fopen ('botlog.csv', 'a+' );
fputcsv ( $fp2, array ( $sub2, '0', '1' ), ",", '"' );
fclose ( $fp2 );}
?>
Then, I have the following to a) aggregate rows for the 2nd column value (haven't figured out how to do the third too) and put into an array, b) dump it all as a table:
<?php
$array = array_map('str_getcsv', file('botlog.csv'));
$inputfile = 'botlog.csv';
$inputHandle = fopen($inputfile, "r");
$sumArray = array();
while (($dataRow = fgetcsv($inputHandle, 1000, ",")) !== FALSE) {
$subid = $dataRow[0];
$extra1 = $dataRow[2];
if (!isset($sumArray[$subid])) {
$sumArray[$subid] = 0;
}
$sumArray[$subid] += $extra1;
}
var_dump($sumArray); //test sum works
function build_table($sumArray){
// start table
$html = '<table>';
// header row
$html .= '<tr>';
$header=array("SUBID"=>"1","Initial Clicks"=>"2","Secondary Clicks"=>"3", "Percentage"=>"4");
foreach($header as $key=>$value){
$html .= '<th>' . $key . '</th>';
}
$html .= '</tr>';
// data rows
foreach( $sumArray as $key=>$value){
$html .= '<tr>';
foreach($value as $key2=>$value2){
$html .= '<td>' . $value2 . '</td>';
}
$html .= '</tr>';
}
// finish table and return it
$html .= '</table>';
return $html;
}
echo build_table($array);
?>
The initial code works in that it makes an array with the column 2 values summed. Woot! However, I then try to use the HTML table print out on this sumArray, but it just displays the original content (i.e. not that generated from the while function.
So, goals:
Modify initial code block to create a $sumArray that merges all identical column 1 rows but adds their column 2 and 3 values.
Print this out in a nifty table with a 4th spare column.
Help much appreciated!
EDIT: This is the final working code I used:
<?php
if (file_exists('botlog.csv')) {
$array = array_map('str_getcsv', file('botlog.csv'));
$inputfile = 'botlog.csv';
$inputHandle = fopen($inputfile, "r");
$sumArray = array();
while (($dataRow = fgetcsv($inputHandle, 1000, ",")) !== FALSE) {
$subid = $dataRow[0];
if (!isset($sumArray[$subid])) {
$sumArray[$subid] = array_fill(0, count($dataRow)-1, 0);
}
for ($i = 1; $i < count($dataRow); $i++) {
$sumArray[$subid][$i-1] += $dataRow[$i];
}}
arsort($sumArray);
$table = $sumArray;
echo '<table>';
echo "<thead><td><span>Subid</span></td><td><span>Initial Clicks</span></td><td><span>Secondary Clicks</span></td><td><span>Percentage</span></td></thead>";
foreach ($table as $subids => $values)
{
echo "<tr><td>".$subids."\n";
echo "<td>" . $values['0'] . "</td>";
echo "<td>" . $values['1'] . "</td>";
echo "<td>Final column contents</td>";
}
echo "</table>";
}
else{ echo "Botlog.csv file was not found in current directory";}
?>
Make $sumArray a 2-dimensional array. The key of the first dimension is the first column of the CSV, and the second dimension is the sums of the remaining columns.
while (($dataRow = fgetcsv($inputHandle, 1000, ",")) !== FALSE) {
$subid = $dataRow[0];
if (!isset($sumArray[$subid])) {
$sumArray[$subid] = array_fill(0, count($dataRow)-1, 0);
}
for ($i = 1; $i < count($dataRow); $i++) {
$sumArray[$subid][$i-1] += $dataRow[$i];
}
I am trying to pull the image link for 10 different rows based on ids in an array. It seems to break when the query is in the loop..Any ideas how i can accomplish this?
$array = array(54, 319, 342, 298, 281, 190,178,158,138,7);
$shuffleKeys = array_keys($array);
shuffle($shuffleKeys);
$newArray = array();
foreach($shuffleKeys as $key) {
$newArray[$key] = $array[$key];
}
for($i=0;$i<=count($newArray);$i++){
$query = "SELECT logoName,logoImageLink, logoImageLink2, countryImg, logoArtist, afterText, country FROM logos WHERE id = $array($i) ";
$result = mysql_query($query);
/* fetch rows in reverse order */
for ($i = mysql_num_rows($result) - 1; $i >= 0; $i--) {
if (!mysql_data_seek($result, $i)) {
echo "Cannot seek to row $i: " . mysql_error() . "\n";
continue;
}
if (!($row = mysql_fetch_assoc($result))) {
continue;
}
$imageLink = $row['logoImageLink'];
echo "<li class=\".$array($i).\" ><img src=\".$imageLink.\" /></li>";
}
You can use the MySQL IN clause and do this in a single select.
$ids = join(',',$newArray);
$query = "SELECT logoName,logoImageLink, logoImageLink2, countryImg, logoArtist, afterText, country FROM logos WHERE id IN ($ids)";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
$imageLink = $row['logoImageLink'];
echo "<li><img src=\"$imageLink\"/></li>";
}
I have an Array of Arrays and Want to create a Tabular data layout. This is not the exact code, as how their generated is quite the cluster (Coming from COBOL interaction) but this should give me enough to make it work if someone can think of a clean way to code this.
array(
Array(847.0, 97010, 11)
Array(847.0, 97012, 10)
Array(847.1, 97010, 08)
Array(847.1, 97012, 14)
)
So I want to put these into a Table that looks something like
97010 97012
847.0 11 10
847.1 08 14
The first 2 elements of the arrays will always be the two axis and the 3rd the contents of the table.
Any Suggestions? thanks!
$table = array();
$columns = array();
// copy the array (x, y, value) into a table
// keeping track of the unique column names as we go
foreach ($dataSet as $point) {
// provided sample data used floats, ensure it is a string
$x = strval($point[0]);
$y = strval($point[1]);
$data = $point[2];
if (!isset($table[$x])) {
$table[$x] = array();
}
$table[$x][$y] = $data;
// quick and dirty style 'unique on insert'
$columns[$y] = true;
}
// switch the column names from title => true to just titles
$columns = array_flip($columns);
// Display the table
echo '<table>';
// Header row
echo '<tr>';
echo '<th> </th>';
foreach ($columns as $columnTitle) {
echo '<th>' . $columnTitle . '</th>';
}
echo '</tr>';
// Bulk of the table
foreach ($table as $rowTitle => $row) {
echo '<tr>';
echo '<th>' . $rowTitle . '</th>';
foreach ($columns as $columnTitle => $junk) {
if (isset($row[$columnTitle]) {
echo '<td>' . $row[$columnTitle] . '</td>';
} else {
// Handle sparse tables gracefully.
echo '<td> </td>';
}
}
echo '</tr>';
}
echo '</table>';
From what I understood:
$arr[847.0][97010] = '11';
$arr[847.0][97012] = '10';
$arr[847.1][97010] = '08';
$arr[847.1][97012] = '14';
And you may create a table:
$result = "<table>";
foreach($arr as $row_key => $row) {
$result .= "<tr>";
foreach($row as $column_key => $data) {
$result .= "<td>".$data."</td>";
}
$result .= "</tr>";
}
$result .= "</table>";
echo $result;