Generate table from MySQL to PDF (using PHP) - php

I'm trying to export the table (filtered) from MySQL to pdf.
The main problem here is that it only prints the last result on the list, instead of printing all the results.
I have tried other code but I still get the same result. I don't know what is wrong with my code:
<?php
include("configsample.php");
?>
<?php
$string=$_GET['string'];
$course=$_GET['course'];
$category=$_GET['category'];
$from=$_GET['from'];
$to=$_GET['to'];
if ($_REQUEST["string"]<>'') {
$search_string = " AND restu_title LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%'";
}
if ($_REQUEST["course"]<>'') {
$search_course = " AND restu_course='".mysql_real_escape_string($_REQUEST["course"])."'";
}
if ($_REQUEST["category"]<>'') {
$search_category = " AND category='".mysql_real_escape_string($_REQUEST["category"])."'";
}
if ($_REQUEST["from"]<>'' and $_REQUEST["to"]<>'') {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE restu_year BETWEEN '".mysql_real_escape_string($_REQUEST["from"])."' AND '".mysql_real_escape_string($_REQUEST["to"])."'".$search_string.$search_course;
} else if ($_REQUEST["from"]<>'') {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE restu_year = '".mysql_real_escape_string($_REQUEST["from"])."'".$search_string.$search_course;
} else if ($_REQUEST["to"]<>'') {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE restu_year = '".mysql_real_escape_string($_REQUEST["to"])."'".$search_string.$search_course;
} else {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE restu_id>0".$search_string.$search_course.$search_category;
}
$html='<table>
<tr style="color:#010101; font:bold 13px Times New Roman; height:40px;">
<th>Research Title</th>
<th>Year</th>
<th>Proponent(s)</th>
<th>Adviser</th>
<th>Research Panel</th>
</tr>';
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
if (mysql_num_rows($sql_result)>0) {
while ($row = mysql_fetch_assoc($sql_result)){
$html2='<tr>
<td style="padding:10px;">'.$row['restu_title'].'</td>
<td style="padding:10px;">'.$row['restu_year'].'</td>
<td style="padding:10px;">'.$row['restu_by'].'</td>
<td style="padding:10px;">'.$row['restu_ad'].'</td>
<td style="padding:10px;">'.$row['restu_panel'].'</td>
</tr>
</table>';
}
}
include("mpdf60/mpdf.php");
$mpdf=new mPDF('c','Letter','','',20,20,18,16,9,9,'L');
$mpdf->SetDisplayMode('fullpage');
$mpdf->AddPage('L');
$mpdf->WriteHTML($html);
$mpdf->WriteHTML($html2);
$mpdf->Output();
exit;
?>

You need to concatenate your text string to avoid $html2 to be overwritten by the next value.
Everytime the loop is running, $html2 is overwritten with the new value. In your case, you need to add a dot just before the equal symbol:
while ($row = mysql_fetch_assoc($sql_result)){
$html .='<tr>
<td style="padding:10px;">'.$row['restu_title'].'</td>
<td style="padding:10px;">'.$row['restu_year'].'</td>
<td style="padding:10px;">'.$row['restu_by'].'</td>
<td style="padding:10px;">'.$row['restu_ad'].'</td>
<td style="padding:10px;">'.$row['restu_panel'].'</td>
</tr>';
}
Be careful to correctly place the </table>. If your SQL request has no result, the table will not be closed, rendering the HTML invalid.
You need to do it like this:
$html='<table>
<tr style="color:#010101; font:bold 13px Times New Roman; height:40px;">
<th>Research Title</th>
<th>Year</th>
<th>Proponent(s)</th>
<th>Adviser</th>
<th>Research Panel</th>
</tr>';
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
if (mysql_num_rows($sql_result)>0) {
while ($row = mysql_fetch_assoc($sql_result)){
$html .='<tr>
<td style="padding:10px;">'.$row['restu_title'].'</td>
<td style="padding:10px;">'.$row['restu_year'].'</td>
<td style="padding:10px;">'.$row['restu_by'].'</td>
<td style="padding:10px;">'.$row['restu_ad'].'</td>
<td style="padding:10px;">'.$row['restu_panel'].'</td>
</tr>';
}
}
$html .= '</table>';

append $html2. You are assigning value in loop so it displaying only last record.
Use like this..
$html2=$html2.'<tr>
<td style="padding:10px;">'.$row['restu_title'].'</td>
<td style="padding:10px;">'.$row['restu_year'].'</td>
<td style="padding:10px;">'.$row['restu_by'].'</td>
<td style="padding:10px;">'.$row['restu_ad'].'</td>
<td style="padding:10px;">'.$row['restu_panel'].'</td>
</tr>';

Related

viewing a table based on a previous id

I have a table set up called Modules, that once a user is logged in it brings up the modules related to that user, this works fine. At the side of each module in the table I have a lessons link. once the user clicks on that I want it to display the lessons based on the module ID.
Any help would be great full.
My Module code in case I need to add something to it is as follows;
<?
include('../inc/security.inc.php');
authorise();
// Include databse connection file
include('../inc/connection.inc.php');
// Connect to the database
connect();
$userID = $_SESSION['userID'];
$sql = "SELECT * FROM tblModule WHERE userID = '$userID'" ;
$result = #mysql_query($sql) or die(mysql_error());
?>
and displaying the module table as follows;
<?php
// run a while loop through all records and create a new row for each one
while ($record = mysql_fetch_object($result))
{
?>
<table class="myTable">
<th class="col">Module ID</th>
<th class="col">Module Title</th>
<th class="col">Module Description</th>
<th class="col">User ID</th>
<th class="col">Manage</th>
</tr>
<tr class="row">
<td class="cell"><?php echo $record->moduleID; ?></td>
<td class="cell"><?php echo $record->moduleTitle; ?></td>
<td class="cell"><?php echo $record->moduleDescription; ?></td>
<td class="cell"><?php echo $record->userID; ?></td>
<td class="cell">Lessons</td>
</tr>
</table>
<?
}
// clean up after ourselves by cleating $result and closing the database connection
mysql_free_result($result);
mysql_close();
?>
Then so far in the lesson table i have;
<?
include('../inc/security.inc.php');
authorise();
// Include databse connection file
include('../inc/connection.inc.php');
// Connect to the database
connect();
$moduleID = $_SESSION['moduleID'];
$sql = "SELECT * FROM tblLessons WHERE moduleID = '$moduleID'" ;
$result = #mysql_query($sql) or die(mysql_error());
?>
With the result been displayed as;
<?php
// run a while loop through all records and create a new row for each one
while ($record = mysql_fetch_object($result))
{
?>
<table class="myTable">
<th class="col">LessonID</th>
<th class="col">Lesson Number</th>
<th class="col">Lesson Description</th>
<th class="col">ModuleID</th>
<th class="col">Lesson Plan ID</th>
<th class="col">Manage</th>
</tr>
<tr class="row">
<td class="cell"><?php echo $record->lessonID; ?></td>
<td class="cell"><?php echo $record->lessonNumber; ?></td>
<td class="cell"><?php echo $record->lessonDescription; ?></td>
<td class="cell"><?php echo $record->moduleID; ?></td>
<td class="cell"><?php echo $record->lessonPlanID; ?></td>
</tr>
</table>
<?
}
// clean up after ourselves by cleating $result and closing the database connection
mysql_free_result($result);
mysql_close();
?>
You're passing the moduleID as a query string variable to lessons.php, but in lessions.php you're looking for it in session data.
$moduleID = $_SESSION['moduleID'];
Try:
$moduleID = isset($_GET['moduleID']) ? $_GET['moduleID'] : false;
if ( $moduleID ) {
$sql = sprintf('SELECT * FROM tblLessons WHERE moduleID = %d', $moduleID);
$result = #mysql_query($sql) or die(mysql_error());
} else {
// No moduleID, so show an error message, redirect user, or the like
}
Note that I'm using sprintf so that $moduleID is converted to a digit. The code you're using - passing the value directly to MySQL - is dangerous. Google: "sql injection".
If $moduleID can in fact be a string, then you need to take extra steps to ensure that the data is sanitized before being passed to MySQL, e.g.
$moduleID = isset($_GET['moduleID']) ? $_GET['moduleID'] : false;
if ( $moduleID ) {
$sql = sprintf("SELECT * FROM tblLessons WHERE moduleID = '%s'", mysql_real_escape_string($moduleID));
$result = #mysql_query($sql) or die(mysql_error());
} else {
// No moduleID, so show an error message, redirect user, or the like
}
You should also consider switching to PDO, as the mysql_ functions are depreciated. PDO is a much easier, safer way to interact with MySQL.

Php Delete item from mysql data base

Hope some one can help me out here, i guess am not calling my functions right.
Am trying to retrieve some data from my database and have a delete link attached to each items being retrieved, so that when ever i click on delete, it will delete that particular item which have the delete function.
My Code to retrieve items from database are as follows.
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("uloaku", $con);
$count = 1;
$y = mysql_query("SELECT * FROM transaction");
if(mysql_num_rows($y) != 0){
echo "<table bgcolor=\"white\" width=\"1000\" bordercolor=\"grey\" border=\"5\" >";
echo "<tr>
<td align=\"center\">No</td>
<td align=\"center\">Date</td>
<td align=\"center\">Current Balance</td>
<td align=\"center\">Avaliable Balance</td>
<td align=\"center\">Account Status</td>
<td align=\"center\">Delete Account</td>
</tr>";
while ($z = mysql_fetch_array($y, MYSQL_BOTH)){
echo "<tr>
<td align=\"center\">".$count++."</td>
<td align=\"center\">".$z[1]."</td>
<td align=\"center\">".$z[2]."</td>
<td align=\"center\">".$z[3]."</td>
<td align=\"left\" width=\"300\">".$z[4]."</td>
<td>delete</td>
</tr>";
}
echo "</table>";
}
?>
And my code to delete
<?php
session_start();
$con = mysql_connect("localhost","root","");
mysql_select_db("uloaku", $con);
$id = $_GET['id'];
$sql = mysql_query("DELETE FROM transaction WHERE id='$id' LIMIT 1") or die (mysql_error());
header("Location: vacct.php");
?>
I know am missing out the logic here and hope somebody can direct me or show me the easy way out. at the moment i can successfully retrieve my items from the data base my only problem is to be able to apply the delete function each time the delete button is tapped.
You have to pass the id when you click on the delete link:
<a href=\"delete.php?id=$z[theIdKey]\">
Use the below code.I have added validation and encryption
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("uloaku", $con);
$count = 1;
$y = mysql_query("SELECT * FROM transaction");
if(mysql_num_rows($y) != 0){
echo "<table bgcolor=\"white\" width=\"1000\" bordercolor=\"grey\" border=\"5\" >";
echo "<tr>
<td align=\"center\">No</td>
<td align=\"center\">Date</td>
<td align=\"center\">Current Balance</td>
<td align=\"center\">Avaliable Balance</td>
<td align=\"center\">Account Status</td>
<td align=\"center\">Delete Account</td>
</tr>";
while ($z = mysql_fetch_array($y, MYSQL_BOTH)){
echo "<tr>
<td align=\"center\">".$count++."</td>
<td align=\"center\">".$z[1]."</td>
<td align=\"center\">".$z[2]."</td>
<td align=\"center\">".$z[3]."</td>
<td align=\"left\" width=\"300\">".$z[4]."</td>
<td>delete</td>
</tr>";
}
echo "</table>";
}
?>
code to delete
<?php
session_start();
$con = mysql_connect("localhost","root","");
mysql_select_db("uloaku", $con);
$id = base64_decode($_GET['id']);
if(!empty($id)){
$sql = mysql_query("DELETE FROM transaction WHERE id='$id' LIMIT 1") or die (mysql_error());
}
header("Location: vacct.php");
?>
<td>delete</td>
How are you passing the id to delete to your delete.php script?
Change:
<td>delete</td>
to:
<td>delete</td>
if $z[0] is the ID.
In your delete.php, make sure you also escape the word "transaction" using backtick:
DELETE FROM `transaction` WHERE id=123
this is because "transaction" is a reserved mysql keyword.
Please also read on SQL Injections.

php explode product array throwing up errors

I have set up an 'orders' page that should be pretty straight-forward, requiring a for each loop to generate past orders from the DB. Within each loop, there needs to be an explode to separate each item(,), then another explode to pull the details out of each item(-). I was wondering if anyone could tell me why I'm getting the error message "Warning: mysql_num_rows() expects parameter 1" at the end of each iteration of my foreach loop? It's particularly confusing for me because the code still works, which I don't think it should if the error was true.
<?php
$sql = "SELECT * FROM orders WHERE store='$user'";
$res = mysql_query($sql);
$arrOrders = array();
while ($row = mysql_fetch_array($res)) {
array_push($arrOrders, $row);
}
?>
<table width="85%" align="center" border="0" cellpadding="5">
<?php if (count($arrOrders) > 0) { ?>
<?php foreach ($arrOrders as $key => $value) { ?>
<tr>
<td valign="top" style="font-weight: bold">
ID #<?=$value['id']?>
</td>
<td valign="top" style="font-weight: bold">
Status: <?=$value['status']?>
</td>
<td valign="top" style="font-weight: bold">
Order #<?=$value['order_ref']?>
</td>
<td align="left" valign="top" style="font-weight: bold">
<?php
$tmpProds = explode(',', $value['products']);
foreach ($tmpProds as $key2 => $value2) {
$tmpProdInfo = explode('-', $value2);
$sql2 = 'SELECT * FROM products_full WHERE id = ' . $tmpProdInfo[0];
$res2 = mysql_query($sql2);
if (mysql_num_rows($res2) > 0) { // THIS IS THE ROW THAT THE ERROR MESSAGE POINTS TO
echo $tmpProdInfo[1] + $tmpProdInfo[2] . ' x ' . mysql_result($res2, 0, 'alpha_code') . ' (' . trim(mysql_result($res2, 0, 'description')) . ')<br /><br />';
}
}
?>
</td>
</tr>
<tr>
<td width="100%" colspan="5" align="center">
<hr style="width: 100%" />
</td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td width="100%" align="center">
There are currently no complete orders.
</td>
</tr>
<?php } ?>
</table>
Thanks in advance, I think I've included everything that is relative but if anything else is needed please let me know.
Joe
Try this:
$sql2 = 'SELECT * FROM products_full WHERE id = '.$tmpProdInfo[1].'';
if (count($res2) > 0)
Also, be aware when you want to use MySQL_num_rows you should include the connection. see the manual:
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);

Mysql/PHP code is returning all rows except first and last

I am having a time tryng to pull ALL records out of a database. For example I have the following
$result = mysql_query("SELECT * FROM `plant_info` ORDER BY id LIMIT 0, 50") or die(mysql_error());
// Variables to pull from the database
// I know the line below is the culprit now, so i must change the code below correct? ///
$returneddata = mysql_fetch_array($result);
///////////////////////////////////////////
$LatinName = $returneddata['Latin_Name'];
$CommonName = $returneddata['Common_Name'];
$Category = $returneddata['Category'];
$Type = $returneddata['Type'];
$Fruit = $returneddata['Fruit'];
$Flower = $returneddata['Flower'];
$MinHeight = $returneddata['Min_Height'];
$MaxHeight = $returneddata['Max_Height'];
$MinWidth = $returneddata['Min_Width'];
$MaxWidth = $returneddata['Max_Width'];
$Exposure = $returneddata['Exposure'];
$Comments = $returneddata['Comments'];
$SoilType = $returneddata['Soil_Type'];
$Zone = $returneddata['Zone'];
$PotSize = $returneddata['Pot_Size'];
$CostPrice = $returneddata['Cost_Price'];
$RetailPrice = $returneddata['Retail_Price'];
$ImageName = $returneddata['Image_Name'];
$ImageNameThumb = $returneddata['Image_Name_Thumb'];
$num_rows = mysql_num_rows($result); echo "$num_rows Rows\n";
while ($row = mysql_fetch_array($result)) {
echo " <tr>
<td align=\"center\" bgcolor=\"#000000\">
<p><img src=\"$row[Image_Name]\" style=\"width:120px;height:auto;\"></p>
</td>
<td align=\"center\" bgcolor=\"#90c084\">
<p>$row[Latin_Name]</p>
</td>
<td align=\"center\" bgcolor=\"#90c084\">
<p>$row[Common_Name]</p>
</td>
<td align=\"center\" bgcolor=\"#90c084\">
<p>$row[Category]</p>
</td>
<td align=\"center\" bgcolor=\"#90c084\">
<p>$row[Type]</p>
</td>
<td align=\"center\" bgcolor=\"#90c084\">
<p>$row[Flower]</p>
</td>
<td align=\"center\" bgcolor=\"#90c084\">
<p>$row[Comments]</p>
</td>
</td>
<td align=\"center\" bgcolor=\"#90c084\">
<p>Edit</p>
<p>Print</p>
</td>
</tr>
";
}
The issue i have is that it will pull all the records except for the first one. Every other record shows, there are only 5 records currently.
I am missing something silly I know it. I looked through questions and could not find the answer. Thanks
It could be because you're calling the mysql_fetch_array command twice.
$row = mysql_fetch_array($result);
while ($row = mysql_fetch_array($result)) {
You only need to declare mysql_fetch_array once, which is inside the while parameter.
This should be your code:
$result = mysql_query("SELECT * FROM `plant_info` ORDER BY id LIMIT 0, 30");
while ($row = mysql_fetch_array($result)) {
echo " <tr>
<td align=\"center\" bgcolor=\"#000000\">
<p><img src=\"$row[Image_Name]\" style=\"width:120px;height:auto;\"></p>
</td>
<td align=\"center\" bgcolor=\"#90c084\">
<p>$row[Latin_Name]</p>
</td>
<td align=\"center\" bgcolor=\"#90c084\">
<p>$row[Common_Name]</p>
</td>
<td align=\"center\" bgcolor=\"#90c084\">
<p>$row[Category]</p>
</td>
<td align=\"center\" bgcolor=\"#90c084\">
<p>$row[Type]</p>
</td>
<td align=\"center\" bgcolor=\"#90c084\">
<p>$row[Flower]</p>
</td>
<td align=\"center\" bgcolor=\"#90c084\">
<p>$row[Comments]</p>
</td>
</td>
<td align=\"center\" bgcolor=\"#90c084\">
<p>Edit</p>
<p>Print</p>
</td>
</tr>
";
}
you didn't post valid/all your PHP - there's no mysql_query() call.
SELECT * FROM `plant_info` ORDER BY id LIMIT 0, 30
$row = mysql_fetch_array($result);
while ($row = mysql_fetch_array($result)) {
line 2 there fetches a row and does nothing with it anyway, throwing away the first row. try this:
$result = mysql_query("SELECT * FROM `plant_info` ORDER BY id LIMIT 0, 30");
while ($row = mysql_fetch_array($result)) {
After your question update, it looks like you want to pull out info from the first row, then loop over all the rows. Here's a way to do that:
$result = mysql_query("SELECT * FROM `plant_info` ORDER BY id LIMIT 0, 30");
while ($row = mysql_fetch_array($result)) {
$rows[] = $row;
}
$row = $rows[0];
$LatinName = $returneddata['Latin_Name'];
...
foreach ($rows as $row){
...
}

Sorting a php table on the basis of just one particular field

Hi I am trying to sort this table on the basis of $fratio. The one who has the highest $fratio will be placed as Number 1 in the table. Here's the code that I have worked so far -
// MySQL connection.
$connection = mysql_connect($host,$username,$password);
#mysql_select_db($database) or die( "Unable to select database. Be sure the databasename exists and online is.");
$query="SELECT `UserID`,`Playername`,`Kills`,`Deaths` FROM users LIMIT 0,50";
$query = mysql_query($query);
echo('<table width="300" border="2" cellspacing="3" cellpadding="3">
<tr>
<td style="min-width:150px;">Playername:</td>
<td style="width:100px">Kills:</td>
<td style="width:100px">Deaths:</td>
<td style="width:100px">Ratio:</td>
</tr>');
while($row = mysql_fetch_assoc($query))
{
$id = $row['UserID'];
$playername = $row['Playername'];
$kills = $row['Kills'];
$deaths = $row['Deaths'];
$ratio = ($kills/$deaths);
$fratio = ceil($ratio);
echo('
<tr>
<td style="min-width:150px;">'.$playername.'</td>
<td style="width:100px">'.$kills.'</td>
<td style="width:100px">'.$deaths.'</td>
<td style="width:100px">'.$fratio.'</td>
</tr>');
}
echo('</table>');
mysql_close($connection);
?>
You could try using
ORDER BY kills / deaths DESC
So the full query would look like
SELECT `UserID`,`Playername`,`Kills`,`Deaths` FROM users ORDER BY kills / deaths DESC LIMIT 0,50
And the full code would look like this:
// MySQL connection.
$connection = mysql_connect($host,$username,$password);
#mysql_select_db($database) or die( "Unable to select database. Be sure the databasename exists and online is.");
$query="SELECT `UserID`,`Playername`,`Kills`,`Deaths` FROM users ORDER BY kills / deaths LIMIT 0,50";
$query = mysql_query($query);
echo('<table width="300" border="2" cellspacing="3" cellpadding="3">
<tr>
<td style="min-width:150px;">Playername:</td>
<td style="width:100px">Kills:</td>
<td style="width:100px">Deaths:</td>
<td style="width:100px">Ratio:</td>
</tr>');
while($row = mysql_fetch_assoc($query))
{
$id = $row['UserID'];
$playername = $row['Playername'];
$kills = $row['Kills'];
$deaths = $row['Deaths'];
$ratio = ($kills/$deaths);
$fratio = ceil($ratio);
echo('
<tr>
<td style="min-width:150px;">'.$playername.'</td>
<td style="width:100px">'.$kills.'</td>
<td style="width:100px">'.$deaths.'</td>
<td style="width:100px">'.$fratio.'</td>
</tr>');
}
echo('</table>');
mysql_close($connection);
?>
Here's an example of the "ORDER BY". You should really consider reading atleast this to get the main idea of it.
http://www.w3schools.com/php/php_mysql_order_by.asp
you will make the ratio in mysql like :
ORDER BY CEILING( kills / deaths ) DESC

Categories