Export MySQL database to CSV while converting Unix to date - php

A little bit of backstory first. I have a database that works with a custom created ticket system. New tickets are input via a HTML form that uses PHP.
I need to be able to export certain results to a CSV depending on what the users selects on a separate form.
A quick google of MySQL to CSV with PHP brings this website up.
http://www.a2zwebhelp.com/export-data-to-csv.
I've amended the code slightly so that the query doesn't select all columns from my table, below is my amended code.
<?php
// Database Connection
$host="localhost";
$uname="REMOVED";
$pass="REMOVED";
$database = "REMOVED";
$connection=mysql_connect($host,$uname,$pass);
echo mysql_error();
//or die("Database Connection Failed");
$selectdb=mysql_select_db($database) or die("Database could not be selected");
$result=mysql_select_db($database)
or die("database cannot be selected <br>");
// Fetch Record from Database
$output = "";
$table = "site_calls"; // Enter Your Table Name
$sql = mysql_query("select call_id, call_first_name, call_email, call_department, call_subject, call_status, call_user, call_date, call_date2 from $table WHERE (call_user = 15)");
$columns_total = mysql_num_fields($sql);
// Get The Field Name
$columns = ["call_id","call_first_name","call_email","call_department","call_subject","call_status","call_user","call_date","call_date2"];
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";
// Get Records from the table
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
// Download the file
$filename = "TicketExport.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
exit;
?>
This almost does exactly what I want it to do. The only problem, is due to the way time/date is saved in the database (Unix) the output of 2 columns call_date and call_date2 are output as Unix. I need these to come out as DD/MM/YY or another human readable format. I can manually change this using a formula in excel, but this is something that a customer would have access to, and they'll need to be able to read the date.
Also, mysql is depreciated, are there significant changes to the above code to get it working on mysqli. The rest of the system is written using mysqli for inputting the data.
TL:DR. Exporting some columns from a MYSQL database, need to convert 2 columns from Unix to readable date/time using php.

Try this :
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
if ($heading == 'call_date' || $heading == 'call_date2') {
$output .= '"'.date('d/m/y', strtotime($row["$i"])).'",';
}
else {
$output .='"'.$row["$i"].'",';
}
}
$output .="\n";
}

Use an if statement inside the for loop to identify you are on the date columns, then call the php date function to reformat.
Like this:
for ($i = 0; $i < $columns_total; $i++) {
if($i == 7 or $i == 8) {
$output .='"'.date('d/m/y', strtotime($row["$i"])).'",';
} else {
$output .='"'.$row["$i"].'",';
}
}
I hope this helps!

Related

In PHP and MySQL, my code only prints one row of the table's column

I'm a begginer with php, and I have some troubles with it. My question is about PHP and MySQL. The purpose of the code is that I have a parameter called $sql in which I will write the SQL query. The problem is that my code only prints one row of the consult. I mean, if I have a table with 4 columns (the attributes) and in that table I have 4 rows, the code only prints one row of each column.
The method consult code:
public function makeConsult($sql){
$result = mysqli_query($this->conn, $sql);
$nrows= mysqli_num_rows($result);
if ($nrows> 0) {
for($i = 0;$i<count($nrows);$i++) {
$row= mysqli_fetch_array($result,MYSQLI_NUM);
for ($j=0; $j < count($row) ; $j++) {
array_push($this->results, $row[$j]);
}
}
} else {
echo "No matches found";
}
}
The following method is where I print all the consults:
public function printResult(){
foreach ($this->results as $key => $value) {
echo $key . ": " . $value . "<br>";
}
$this->results = array();
}
The variable $conn is the variable where I have my sql connection.
My execution code:
$db = new dbConnection("localhost","root","","sportsweb");
$db->connect();
echo "Database name: " . $db->getDBname();
$consult = $db->makeConsult("SELECT * FROM articles A");
$db->printResult();
$db->closeConnection();
The columns (attributes) of the table "articles" are the following ones: Id,Name,Units,BranchOffice.
Thank you! :)
You have two mistakes here
$nrows= mysqli_num_rows($result);
if ($nrows> 0) {
for($i = 0;$i<count($nrows);$i++) {
$row= mysqli_fetch_array($result,MYSQLI_NUM);
for ($j=0; $j < count($row) ; $j++) {
array_push($this->results, $row[$j]);
}
}
}
So $nrows will be a count of how many rows you got back. So count($nrows) is useless because it's not an array
Second, I don't know where you got the idea to iterate rows like that, but you're doing it wrong. Use a while loop instead. I also removed the inner for loop and switched to a simpler foreach
$nrows= mysqli_num_rows($result);
if ($nrows> 0) {
while($row = mysqli_fetch_array($result,MYSQLI_NUM)) {
foreach($row as $val) $this->results[] = $val;
}
}

Php removing specific special character and php algorithm ideas

so I ended up with this project, that,due to my opinion, is some levels greater than my skills, so I would like you to help me.
This project's functionality is to write some words in those 4 columns,which have to be combined.The words that are in the same column mustn't be combined. You can only combine words with the rest of the columns.
I will give you the full code so you can see what I have done.
The second question I have is how you delete a special character(in this case, the "\n")
<?php
if(isset($_POST['submit']))
{
if(isset($_POST["separator"])){$separator= $_POST["separator"];}
if(isset($_POST["match"])){$matchType = $_POST["match"];$matchArr = array();
foreach($matchType as $match)
{
$matchArr = $match;
}}
$j=0;
$columnCount=array();
$wordArr[] = array();
$wordArrRows[] = array();
$protasi="";
$wordsCombinations = 1;
$wordsCounter = 0;
for($i=0; $i<4; $i++)
{ $words=0;
$enterChar=0;
if(isset($_POST["in$i"]) && !empty($_POST["in$i"]))
{
$input=$_POST["in$i"];
$enterChar = substr_count($input,"\n");
$words= $enterChar+1;
if($words>0)
{
$wordArr[$j]= explode("\n",$input);
$wordArrRows[$j]= $words;
$j++;
}
$wordsCombinations*=$words;
}
}
$i2=0;
$columnCounter = array_fill(0, $j, "0");
while($wordsCounter < $wordsCombinations)
{
if($i2<sizeof($columnCounter) && $columnCounter[$i2] < $wordArrRows[$i2])
{
echo "grammi: ".$i2." <br>";
$i=0;
for($i=0; $i<$j; $i++)
{
//echo "wordArr[".$i."][".$columnCounter[$i]."]".$separator;
echo $wordArr[$i][$columnCounter[$i]]." ";
}
$columnCounter[$i2]++;
if($columnCounter[$i2] >= $wordArrRows[$i2] ){$columnCounter[$i2]=0;}
echo "<br>";
}
$i2++;
if($i2>=sizeof($columnCounter)){$i2=0;}
$wordsCounter++;
}
}
?>
(NOTE: don't use the radio buttons or the check boxes, they're not functional).
EDIT
What is the expected result for that example?
The second question: trim() to delete "\n"

Distinguish between elements and last element of array

Im creating tablerows based on the number of the array colours:
$query = mysql_query("SELECT * FROM things);
$num = mysql_num_rows($query );
$colours = array ();
if($num)
{
for ($i = 0; ($row = mysql_fetch_assoc($query)); ++$i)
{
$colours[$i] = $row["colours"];
}
}
$arrlength = count($colours);
for ($i = 0; ($i < ($arrlength)); ++$i){
echo "
<tr class='border_bottom'><td>".$colours[$i]."</td></tr>
";
}
So, if colours is, lets say, equal to 8, 8 table rows with the class border_bottom are created.
border_bottom is used by CSS to add a border to the bottom of each tablerow.
What I need is some PHP help: I need code which checks the array colours. The last element of the array has to go with an empty id since I dont want a border-bottom added to that very last tablerow. All other tablerows have to go with the border_bottom class, tho.
I was thinking of starting the code like that:
echo"
<tr class='
";
-->PHP code goes here<--
echo"
'>
<td>".$colours[$i]."</td></tr>
Try this:
<?php
$query = mysql_query("SELECT * FROM things");
$num = mysql_num_rows($query);
$colours = array();
if($num)
{
while($row = mysql_fetch_assoc($query))
{
$colours[] = $row["colours"];
}
}
$arrlength = count($colours);
for ($i = 0; $i < $arrlength; ++$i){
if($i < $arrlength - 1){
echo "<tr class='border_bottom'><td>{$colours[$i]}</td></tr>";
}else{
echo "<tr><td>{$someColor}</td></tr>";
}
}
Try the following code in your table row echo
echo "<tr"
.($i < $arrlength - 1 ? " class='border_bottom'" : "")
.">"
."<td>{$colours[$i]}</td></tr>";
You can actually do this while fetching the rows without needing to count how many there are, by reading ahead one row.
$previous_row = mysql_fetch_array(); // fetch the first row (if there is one)
while ($previous_row) {
if ($row = mysql_fetch_array()) {
// if another row is fetched, then the previous row was NOT the last row
echo '<tr class="border_bottom"><td>' . $previous_row['colours'] . '</td></tr>';
} else {
// otherwise, the previous row WAS the last row, and does not get the class
echo '<tr><td>' . $previous_row['colours'] . '</td></tr>';
}
$previous_row = $row; // Set the previous row to the current row
}

how to show random articles

I am working on project which shows articles and this was done by article manager (a ready to use php script) but I have a problem, I want to show only four article titles and summaries from old list of article randomly which contains 10 article. Any idea how to achieve this process?
I have auto generated summary of article
<div class="a1">
<h3><a href={article_url}>{subject}</h3>
<p>{summary}<p></a>
</div>
When a new article is added the above code will generated and add into summary page. I want to add it to side of the main article page, where user can see only four article out of ten or more randomly.
<?php
$lines = file_get_contents('article_summary.html');
$input = array($lines);
$rand_keys = array_rand($input, 4);
echo $input[$rand_keys[0]] . "<br/>";
echo $input[$rand_keys[1]] . "<br/>";
echo $input[$rand_keys[2]] . "<br/>";
echo $input[$rand_keys[3]] . "<br/>";
?>
Thanks for your kindness.
Assuming I understood you correctly - a simple solution.
<?php
// Settings.
$articleSummariesLines = file('article_summary.html', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$showSummaries = 4;
// Check if given file is valid.
$validFile = ((count($articleSummariesLines) % 4 == 0) ? true : false);
if(!$validFile) {
die('Invalid file...');
}
// Count articles and check wether all those articles exist.
$countArticleSummaries = count($articleSummariesLines) / 4;
if($showSummaries > $countArticleSummaries) {
die('Can not display '. $showSummaries .' summaries. Only '. $countArticleSummaries .' available.');
}
// Generate random article indices.
$articleIndices = array();
while(true) {
if(count($articleIndices) < $showSummaries) {
$random = mt_rand(0, $countArticleSummaries - 1);
if(!in_array($random, $articleIndices)) {
$articleIndices[] = $random;
}
} else {
break;
}
}
// Display items.
for($i = 0; $i < $showSummaries; ++$i) {
$currentArticleId = $articleIndices[$i];
$content = '';
for($j = 0; $j < 4; ++$j) {
$content .= $articleSummariesLines[$currentArticleId * 4 + $j];
}
echo($content);
}

Displaying data from databases - including images

This is my webpage:
http://www.autoweek62.uni.cc/carprice.php
Here is the source code for it:
<?php
$dbname = "autoweek_auto1";
$loginname = "autoweek_root";
$loginpass = "PASSWORD (not my real one)";
$dbhost = "localhost";
echo('<html><body bgcolor="#FFFFFF">');
echo('<font face="arial" size="+4"><center>');
echo("Database $dbname");
$id_link = #mysql_connect($dbhost, $loginname, $loginpass);
$tables = mysql_list_tables($dbname, $id_link);
$num_tables = mysql_num_rows($tables);
// store table names in an array
$arr_tablenames[] = '';
// store number of fields per table(index 0,1,2..) in an array
$arr_num_fields[] = '';
for ($i=0; $i < $num_tables; $i++) {
$arr_tablenames[$i] = mysql_tablename($tables, $i);
$arr_num_fields[$i] = mysql_num_fields(mysql_db_query($dbname, "select * from $arr_tablenames[$i]", $id_link));
}
// store field names in a multidimensional array:
// [i] == table number, [ii] == field number for that table
for ($i=0; $i < $num_tables; $i++) {
for ($ii=0; $ii < $arr_num_fields[$i]; $ii++) {
$result = mysql_db_query($dbname, "select * from $arr_tablenames[$i]", $id_link);
$hash_field_names[$i][$ii] = mysql_field_name($result, $ii);
}
}
for ($i=0; $i < $num_tables; $i++) {
echo("<center><h2>Table $arr_tablenames[$i] </h2></center>");
echo('<table align="center" border="1"><tr>');
$result = mysql_db_query($dbname, "select * from $arr_tablenames[$i]", $id_link);
for ($ii=0; $ii < $arr_num_fields[$i]; $ii++) {
echo("<th>");
echo $hash_field_names[$i][$ii];
echo("</th>");
}
echo("</tr><tr>");
$number_of_rows = #mysql_num_rows($result);
for ($iii = 0; $iii < $number_of_rows; $iii++) {
$record = #mysql_fetch_row($result);
for ($ii=0; $ii < $arr_num_fields[$i]; $ii++) {
echo("<td>");
echo $record[$ii];
echo("</td>");
}
echo("</tr>");
}
echo("</table>");
}
echo('</body></html>');
?>
It displays, but I'm not sure how to get it to display in a manner similar to this:
redbook.com.au/new-cars/results.aspx?Ns=p_Make_String|0||p_ClassificationType_String|0||p_Family_String|0||p_Year_String|1||p_SequenceNum_Int32|0&N=2994+2951+4294961316+4294843565&TabId=1407343
[not linked since I can't post more than 1 being new here]
(although mine is simply the make, model, bodystyle and prices as a list, not as complicated as the link above!)
I've Googled for some inspiration, but despite trying haven't got any far. I'm not looking for an instant answer, but any solutions are welcomed!
Displaying images is the trickiest part... I have the JPGs stored on the server, trying to get them to display is a problem.
All help is welcomed!
You could try making a separate script that returns just the image.
In that script you retrieve the image from the database, output mime-type header and then the raw image data. In your main HTML outputting script you just write <img src="getImage.php?id=1234" />

Categories