Export MYSQL Result to CSV - php

I've been building a database to calculate termination fees.
The below code (termination.php) takes multiple rows selected from check boxes on a previous page, processes the query, and outputs in a loop to a simple HTML table. This is working as required.
<?php
require_once '.\Includes\dbcon.php';
$rowCount = count($_POST["select"]);
for ($i = 0; $i < $rowCount; $i++)
{
$sql = "UPDATE `{$_POST['customer']}` SET `DateOfCancellation`='{$_POST['dateofcancellation']} WHERE ServiceID={$_POST['select'][$i]}'";
if ($con->query($sql) === TRUE)
{
echo "";
}
else
{
echo "Error: " . $sql . "<br />" . $con->error;
}
}
?>
Back to Index</p>
<strong>Termination for <?php echo ucwords($_POST['customer']) ?> Based on Cancellation Date <?php echo $_POST['dateofcancellation'] ?></strong></p>
<table>
<tr>
<th>Service Name</th>
<th>License Start Date</th>
<th>License End Date</th>
<th>Cost Per Calendar Month</th>
<th>Balance on Termination</th>
<?php
$rowCount = count($_POST["select"]);
for ($i = 0; $i < $rowCount; $i++)
{
$sql = mysqli_query($con, "$select FROM `{$_POST['customer']}` WHERE ServiceID={$_POST['select'][$i]}");
$row[$i] = mysqli_fetch_array($sql); ?>
<tr>
<td><?php
echo $row[$i]['ServiceName']; ?></td>
<td><?php
echo $row[$i]['LicenseStart']; ?></td>
<td><?php
echo $row[$i]['LicenseEND']; ?></td>
<td>£<?php
echo $row[$i]['CostPCM']; ?></td>
<td>£<?php
echo $row[$i]['CostOfTermination']; ?></td>
<?php
}
$sql = "UPDATE `{$_POST['customer']}` SET `DateOfCancellation`='0000-00-00'";
if ($con->query($sql) === TRUE)
{
echo "";
}
else
{
echo "Error: " . $sql . "<br />" . $con->error;
}
$sum = 0;
for ($i = 0; $i < $rowCount; $i++)
{
$sum = $sum + $row[$i]['CostOfTermination'];
}
echo "<strong>The Total Balance of Termination is: </strong>£" . $sum;
echo "<p>";
$sum = 0;
for ($i = 0; $i < $rowCount; $i++)
{
$sum = $sum + $row[$i]['CostPCM'];
}
echo "<strong>Balance of Termination per Month: </strong>£" . $sum;
echo "<p>";
?>
</tr>
What do I need to do to export the data in the table to an Excel file (ideally) or a CSV file. I've tried a few different methods and can get the headers but not the actual data. I think the for loop is what's throwing me off.

Try something like this:
<?php
$titles = "Service Name,License Start Date,License End Date,Cost Per Calendar Month,Balance on Termination";
$rowCount = count($_POST["select"]);
echo $titles;
for ($i = 0; $i < $rowCount; $i++)
{
$sql = mysqli_query($con, "$select FROM `{$_POST['customer']}` WHERE ServiceID={$_POST['select'][$i]}");
$row[$i] = mysqli_fetch_array($sql);
echo
$row[$i]['ServiceName'] . "," .
$row[$i]['LicenseStart'] . "," .
$row[$i]['LicenseEND'] . "," .
$row[$i]['CostPCM'] . "," .
$row[$i]['CostOfTermination'] ."<br>";
}

Related

Display images from database into a Table on PHP

I have some problems creating a table that will display pictures from a php database
This is my code:
$query = "SELECT * FROM images ORDER BY name ASC ";
$result = $db->query($query);
$num_result = $result->num_rows;
echo "<h1> Images</h1>";
$array = array();
for ($i = 0; $i < $num_result; $i++){
$row = $result->fetch_assoc();
$name = $row['name'];
$URL = $row['imageURL'];
$array[] = $URL;
}
//this loop is printing the images correctly in order
foreach ($array as $image){
echo '<img src="'.$image.'"/>';
}
What I am trying to accomplish is to create a table with 2 Columns that will print the images there, something like this
echo '<table>';
echo ' <tr>';
echo ' <td>image 1</td>';
echo ' <td>image 2</td>';
echo ' </tr>';
echo ' <tr>';
echo ' <td>image 3</td>';
echo ' <td> image 4</td>';
echo ' </tr>';
// and so on if there is more images
echo '</table>';
Any suggestions will help , Thanks!
i think you want something like
$i=0;
echo"<table>";
echo"<tr>";
foreach ($array as $image)
{
if($i%2==0 && $i>0 )
echo"</tr><tr>";
echo"<td>";
echo '<img class="coupons" src="'.$image.'"/>';
echo"</td>";
$i++;
}
echo"</tr>";
echo"</table>";

Converting to PDO prepared statements from mysqli

I have the following bit of code, that selects a table, loops through all the values which match an actor and displays the reviews for that actor.
include("app/config/db.php");
$aid=$actor['id'];
$query = "SELECT * FROM `reviews` WHERE `actor_id` = $aid";
$result = $mysqli->query($query);
$num_results = $result->num_rows;
if( $num_results ){
//loop to show each records
while( $row = $result->fetch_assoc() ){
extract($row);
echo "<span class=\"review-score\">";
echo $row['score']*10;
echo "</span>";
echo " by <strong>";
echo $row['author'];
echo "</strong>";
echo " on <strong>";
echo $row['created_at'];
echo "</strong>";
echo "<p class=\"review-body\">";
echo $row['body'];
echo "</p>";
echo "</br>";
}
}else{
echo "No records found.";
}
$result->free();
$mysqli->close();
I want to convert to using PDO prepared statements.
This is what I've tried. It doesn't display any of the reviews assigned to the actor. Please help
include("app/config/db.php");
$aid=$actor['id'];
$st = DBase::singleton()
->prepare(
'select * ' .
'from `reviews` ' .
'where `actor_id` like :aid ' .
'limit 0,10');
$st->bindParam(':aid', $aid, PDO::PARAM_STR);
if ($st->execute())
{
while ($row = $st->fetch(PDO::FETCH_OBJ))
{
echo "<span class=\"review-score\">";
echo $st['score']*10;
echo "</span>";
echo " by <strong>";
echo $st['author'];
echo "</strong>";
echo " on <strong>";
echo $st['created_at'];
echo "</strong>";
echo "<p class=\"review-body\">";
echo $st['body'];
echo "</p>";
echo "</br>";
}
}
DBase:singleton
static public function singleton()
{
if (!is_object(self::$pdo))
{
self::$pdo = new PDO('mysql:dbname=' . self::DATABASE . ';host=' . self::HOST,
self::USERNAME,
self::PASSWORD);
}
return self::$pdo;
}
You're storing each row's result in $row, but not accessing $row when you want to display the data.
while ($row = $st->fetch(PDO::FETCH_OBJ))
{
...
echo $st['score']*10;
The echo line should be:
echo $row->score*10;
You're also fetching objects but accessing the data as an array.
thats how I was taught to write a while loop.. how else could I do it?
My point is that if assign a variable with successive values of the row, then the data is in that variable, not in the object that iterates over rows. What you've done is analogous to this:
for ($i = 0; $i < $count; $i++) {
echo $count;
}
Whereas in that example one should do this instead to get successive values in the loop:
for ($i = 0; $i < $count; $i++) {
echo $i;
}

click on a link in a table, then check in what row the link was

What I want to make is this:
I am making a blog. Now I want a query in my mysql-database that finds all the information that is in there. After that it should echo the title's of the blog's on my site in a table.
Then I would like to give people a choice which blog they would like to see. So when they click on the first title they will see the content of that blog.
So now the problem is that I don't know how I can make href's on every title that all go to another php file. In that file it should know which row/title is clicked and then it should make another query in the database that will find the content of that title. Then it should echo it on the site.
I got the table finished. I also know how to make the href's to the other page. the only thing I need to know is which title/href is clicked.
Is it possible to make this with php only? if yes, please explain me how.
I hope I am clear in what i would like to make.
EDIT: this is my code so far:
<?php
session_start();
$connectie = mysql_connect('localhost', 'root', 'usbw');
if ($connectie == false){
echo 'Er is iets fout gegaan met de connectie van de database';
}
if (mysql_select_db('dldatabase', $connectie) == false) {
echo 'Er kon geen verbinding met de database gemaakt worden';
}
$query = "Select *
from forum";
$resultaat = mysql_query($query, $connectie);
echo "<table border='1'>
<tr>
<th>Tijd</th>
<th>Gebruikersnaam</th>
<th>Titel</th>
</tr>";
`while($row = mysql_fetch_array($resultaat))
{
$_SESSION['row'] = $row;
echo "<tr>";
echo "<td>" . $row['Tijd'] . "</td>";
echo "<td>" . $row['Gebruikersnaam'] . "</td>";
echo "<td>" . '<a class="formtitellink" href="forumdocument.php">' . $row['Titel'] . '</a>' . "</td>";
echo "</tr>";
}
echo "</table>";`
this is the blog page
and this is where the content of the blog should be±
session_start();
$row = $_SESSION['row'];
$row = $row + 1;
$query = "Select titel, inhoud
from forum
where `ID` = '$row'";
$resultaat = mysql_query($query, $connectie);
echo "$resultaat";
You can always use a framework like Wordpress, but if you want this kind of structure from scratch then you should read more about URL manipulation and use of GET parameters.
Simplest solution will be:
Create a page say post.php
Now every time you want a post to be displayed, send it with get
parameter. For eg: "page.php?id=hello-world"
On post.php, you can read this "id" parameter and then fire a
query accordingly.
Then print the resultant data on page.php
You need to pages like first page and the second page to open as hyper link.
Here is the sample code:
<?php
echo '<table width="650"><p><tr><th style="margin-left: 10px; padding-right: 70px;"></th>
<th style="width: 350px; ">Item for sale</th> <th>Location</th> <th>Posted</th></tr></table>';
$query1 = "select id from tblads order by priority desc LIMIT 10 OFFSET 1";
$result1 = mysql_query($query1);
$i1 = 0;
while ($row1 = mysql_fetch_row($result1))
{
$count1 = count($row1);
$y1 = 0;
while ($y1<$count1)
{
$c_row1 = current($row1);
$id = $c_row1;
next($row1);
$y1 = $y1 + 1;
//////TABLE
echo'<style> th{padding:0;}</style> ';
echo '<table style=" table-layout:fixed; order-collapse: collapse; " width="650">';
echo '<tr> <th> </th> <th style="width:350px;"> </th> <th style=""></th> <th style="width:100px;"></th></tr>';
$query = "select image,details, location, date from tblads where id=$id";
$result = mysql_query($query);
if (!$result) {$message = 'ERROR:' . mysql_error();return $message;}
else
{ $i = $i1;
$i = 0;
while ($row = mysql_fetch_row($result))
{
echo '<tr> ';
$count = count($row);
$y = 0;
while ($y < $count)
{
$c_row = current($row);
echo '<td style="">' . $c_row . '</td>';
next($row);
$y = $y + 1;
}
echo ' </tr>';
$i = $i + 1;
}
}
}
echo'</table>'; //Content TABLE CLOSE
}
mysql_free_result($result); mysql_close($con);
?>
Then the second page view.php to be opened by the hyperlink:
<?php
$id=$_GET['id'];
$query = "select image, details, location, price, date, id from tblads where id=$id";
$result = mysql_query($query);
if (!$result)
{
$message = 'ERROR:' . mysql_error();
return $message;
}
else
{ $i = 0;
echo '<table><p><tr>';
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo '<th>' . $meta->name . '</th>';
$i = $i + 1;
}
echo '<th>View</th></tr>';
$i = 0;
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
$count = count($row);
$y = 0;
while ($y < $count)
{
$c_row = current($row);
echo '<td>' . $c_row . '</td>';
next($row);
$y = $y + 1;
}
echo '<td></td> </tr>';
$i = $i + 1;
}
echo' </p></table>';
mysql_free_result($result);
mysql_close($con);
}
?>

PHP doesn't echo text for last row

I'm trying to write a relatively simple twitter query in php with result like this:
from:TravisBenjamin3 OR from:AshleyElisaG OR from:tncvaan ...
This code works accept it doesn't echo the second OR, also I don't want to display an OR on the last row.
$counter = 0;
while($row = mysql_fetch_array($result)){
$counter++;
echo " from:";
echo $row['twitter'];
if ($counter < count($row)) {
echo " OR";
}
}
Some help would be greatly appreciated. Thanks,
<?php
$tweets = array();
while($row = mysql_fetch_array($result)) {
$tweets[] = $row['twitter'];
}
if(count($tweets) > 0) {
echo "from:" . implode(" OR from:", $tweets);
}
?>
$rowCount = mysql_num_rows($result);
while($row = mysql_fetch_array($result)){
$counter++;
echo " from:";
echo $row['twitter'];
if ($counter < $rowCount) {
echo " OR";
}
}
$count = mysql_num_rows($result);
for($r = 0; $r < $count; $r++)
{
$row = mysql_fetch_array($result));
echo " from:";
echo $row['twitter'];
if ($r < ($count - 1))
{
echo " OR";
}
}
Or, even easier:
$search = "";
while($row = mysql_fetch_array($result))
{
$search .= " from:" . $row['twitter'] . " OR";
}
// Cut the last " OR"
$search = substr($search, 0, strlen($search) - 3);
echo $search;
Which is actually a poor man's implementation for implode() suggested by Aaron W..

PHP sequential numbering

I'm having trouble with my page here:
LINK
My "rank" part of the table keeps resetting back to zero when you click on page 2 and beyond. It doesn't start at 21, it just resets back to zero.
How do I fix that?
<?php
include ("database.php");
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * 20;
$sql = ("SELECT * FROM voting ORDER BY votepoints DESC LIMIT $start_from, 20") or die ("Error 1.");
$rs_result = mysql_query ($sql) or die (include ("error.html"));
$rank = 1;
?>
<table>
<tr><td>Rank</td><td></td><td>Username</td><td></td><td></td><td></td><td>Vote points</td></tr>
<?php
while ($row = mysql_fetch_assoc($rs_result)) {
?>
<tr>
<td><? echo $rank++; ?></td>
<td></td>
<td><? echo $row["username"]; ?></td>
<td></td>
<td></td>
<td></td>
<td><? echo $row["votepoints"]; ?></td>
</tr>
<?php
};
?>
</table>
<?php
echo '<br>';
echo 'Total Votes: ';
include ("sum.php");
include("database.php");
$sql = "SELECT COUNT(votepoints) FROM voting";
$rs_result = mysql_query($sql);
$row = mysql_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / 20);
echo '<span class="text-bleumarin">';
if($page>1)
$pagelink ='prev ';
echo $pagelink;
for ($i=1; $i<=$total_pages; $i++) {
if ($i != $page)
echo "<a href='votes.php?page=".$i."'>".$i."</a> ";
if ($i==$page)
echo '' . $i . ' ';
};
if($page<$total_pages)
$pagelink ='next ';
echo $pagelink;
echo '</span>';
?>
EDIT: this is the line you need to change
*EDIT2: subtracted 1 from page as you set 1 to default.*
<td><? echo (($page-1)*20)+$rank++; ?></td>
This will do:
(0*20) + 1 = 1
(0*20) + 2 = 2
...
(0*20) + 20 = 20
(1*20) + 1 = 21
(1*20) + 2 = 22
...
(1*20) + 20 = 40
(2*20) + 1 = 41
(2*20) + 2 = 42
...
(2*20) + 20 = 60
...
(21*20) + 1 = 421
Note: No code provided when this solution was posted
Assuming you are using a for loop of some sort to keep count:
if (!isset($_GET['page']))
{
$page=0;
}
else
{
$page=$_GET['page'];
}
for($i=1; $i<21; $i++)
{
echo '<tr>';
echo '<td>'.($page*20)+$i.'</td>;' //THIS IS THE RANK LINE
//Other fields
echo '</tr>';
}

Categories