Loop through database fields PHP MySQL - php

I am working on an election system and I am having difficulty solving a problem. Following is how my application looks like.
At the moment I get these results by adding the query multiple times on my php file. (for example run it where RaceID = 9, RaceID = 10 .........)
I am sure there should be a way of reading the RaceID as an array or some other way and get the results that way. Since these are JOIN tables I am also looking for a way of retrieving the RaceName (Presidential Names, Justice Supreme Court ... etc) and MainRaceName(Titles with red, blue, gray) as well. I hope I am making some sense so far...
Following is my code for
<!-- MAIN ELECTION TICKET MainID loop should control this -->
<div class="panel panel-red margin-bottom-40">
<div class="panel-heading">
<h2 class="panel-title"> <strong>REPUBLICAN NATIONAL</strong> </h2>
</div>
<!-- End then SUB ELECTION TICKET RaceID loop should control this section-->
<h3 style="background-color:#f5f5f5; margin:30px; padding:5px; font-weight:Bold ">Presidential Race </h3>
<!-- Finally Results section ELECTION RESULTS -->
<table class="table table-hover">
<thead>
<tr>
<th></th>
<th>Candidate</th>
<th>Votes</th>
<th>%</th>
</tr>
<!-- This area gets the sum of the votes for a specific RaceID -->
<?php
$result = mysql_query('SELECT SUM(CandidateVotes) AS value_sum FROM candidates WHERE RaceID =9');
$row = mysql_fetch_assoc($result);
$sum = $row['value_sum'];
?>
</thead>
<tbody>
<?php
$query = "SELECT candidates.CandidateName, candidates.CandidateVotes, candidates.Party, mainrace.MainRaceName, race.RaceName, candidates.win
FROM candidates
JOIN race ON race.RaceID = candidates.RaceID
JOIN mainrace ON mainrace.MainID = candidates.MainID
WHERE candidates.RaceID = 9";
$result = mysql_query($query) or die(mysql_error());
for($i=0; $row = mysql_fetch_array($result); $i++){
?>
<tr>
<!--Show winner Icon if the win field is selected as 1 from database -->
<td width="5px">
<?php if ($row['win']==1)
{
echo "<span class=\"glyphicon glyphicon-check\"></span>";
}
else
{
echo "<span class=\"glyphicon glyphicon-unchecked\" style=\"color:#cccccc\"></span>";
}
?>
</td>
<td><?php if ($row['win']==1){
echo "<strong>";
echo $row['CandidateName'];
echo "</strong>";
}
else {
echo $row['CandidateName'];
}
?>
</td>
<td width="20%"><?php echo $row['CandidateVotes']; ?></td>
<td width="30%"><?php
if ($row['CandidateVotes']>0){
echo number_format((float)(($row['CandidateVotes']/$sum)*100), 2, '.', ''). ' %';
}
else{
echo "N/A";
}
?>
</td>
</tr>
<?php
}
?>
<tr>
<td></td>
<td><strong>Total Votes:</strong></td>
<td><strong><?php echo $sum ?></strong></td>
<td></td>
</tr>
</tbody>
</table>
I really appreciate if you can provide some samples (loops) how I can resolve this problem. Your help is much appreciated. Sincerely,

You should be able to pull down everything you need in one query.
In order to sum up votes by candidate, you need to make sure you GROUP BY the candidate name.
Try something like this:
SELECT
SUM(candidates.CandidateVotes) AS value_sum,
candidates.CandidateName,
candidates.Party,
mainrace.MainRaceName,
race.RaceName,
candidates.win
FROM candidates
JOIN race
ON race.RaceID = candidates.RaceID
JOIN mainrace
ON mainrace.MainID = candidates.MainID
WHERE candidates.RaceID = :raceId
GROUP BY candidates.CandidateName

Related

php/html table structure not working as I want it to

I'm trying to make a table of which it is pulling information from a database. Its suppose to list the module name and then how many assignments are in it. There are two database tables involved, one simply is an id and modulename, other is id, assignment, topic, content, etc. For some reason my table won't appear correctly, it just continues rather than starting on a new line for that table. here's a picture of what it is doing
enter image description here
here's the code(if more is needed let me know):
<div id="module_1" class="row CourseModule">
<a href="#" onclick="showAssignments(1);">
<div class="col-lg-12 columnPad">
<h1-1 class="lead">List of Modules</h1-1>
</a>
<div class="pullright">
<a id="addAssignmentbutton_1" class="btn btn-primary ThemeButton" href="#" onclick="addAssignment(1);"> Add Assignment</a>
</div>
</div>
</div>
<div id="module_Assignments_1" class="row CanvasPad" style="display:none;">
<table class="CanvasTable">
<thead>
<th>
Module
</th>
<th>
Assignments
</th>
</thead>
<?php
while($row = mysqli_fetch_assoc($result)){
$count = 0;
$query = "SELECT module_id FROM module_records";
$result2 = mysqli_query($con, $query);
if(!$result2){
echo "Can't retrieve data " . mysqli_error($con);
exit;
}
while ($modInassignment = mysqli_fetch_assoc($result2)){
if($modInassignment['module_id'] == $row['module_id']){
$count++;
}
}
?>
<td>
<?php echo $row['module_name']; ?>
</td>
<td>
<span class="badge"><?php echo $count; ?></span>
</td>
<?php } ?>
List all assignments
</table>
</div>
.js
function showAssignments(module_id){
var html_id = "#module_Assignments_" + module_id;
if($(html_id).css("display") == 'block'){
$(html_id).css("display", "none");
} else {
$(html_id).css("display", "block");
}
}
You need a table row tr and then the table data td in it
Also, not required but good for grouping without adding divs/class/id; add all these tr inside a tbody if needed. Read more why it's not required here
<table class="CanvasTable">
<thead>
<th>
Module
</th>
<th>
Assignments
</th>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_assoc($result)){
$count = 0;
$query = "SELECT module_id FROM module_records";
$result2 = mysqli_query($con, $query);
if(!$result2){
echo "Can't retrieve data " . mysqli_error($con);
exit;
}
while ($modInassignment = mysqli_fetch_assoc($result2)){
if($modInassignment['module_id'] == $row['module_id']){
$count++;
}
}
?>
<tr>
<td>
<?php echo $row['module_name']; ?>
</td>
<td>
<span class="badge"><?php echo $count; ?></span>
</td>
</tr>
<?php } ?>
</tbody>
List all assignments
</table>
More info: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr

mySQL and PHP to filter $_GET Results from Database

My code receives a brand from an html form, it then proceeds to generate the search results from the database.
if(isset($_GET['brand'])) {
$brand = mysqli_real_escape_string($db, $_GET['brand']);
echo $brand;
$featuredSql = "SELECT t.*, s.quantity, s.rrp AS nRetailPrice, r.city AS city_name, ts.thumbnail as tread_thumbnail, ts.bigpic as tread_bigpic, t.rating FROM tyres t INNER JOIN stocklevels s
ON t.stockcode=s.stockcode LEFT JOIN tyre_treads ts ON t.treadid=ts.recid LEFT JOIN reseller r ON s.city=r.recid WHERE s.quantity>0 ";
if ($brand != 'Any') $featuredSql .= " AND t.manufacturer='$brand'";
$featuredSql .= "GROUP BY t.diam,t.manufacturer, t.width";
if (!$featured = mysqli_query($db, $featuredSql)) die(mysqli_error());
var_dump($featured);
if (!$tyre1 = mysqli_fetch_object($featured)) echo "<br />No tyres match those parameters. Please try again.";
}
The HTML to represent the data once collected.
<div class="text text-background">
<h4>
<?= $product["profile"] . "/" . $product["width"] . "/" . $product["diam"] . " " . $product['manufacturer']; ?>
</h4>
<p class="brand"><?= $product["part_no"]; ?></p>
<div class="col-md-12 col-sm-12 col-xs-12 text-right">
<div class="txtprice-small">PRICE FROM $<span><?= $product["nRetailPrice"]; ?></span></div>
</div>
<table class="table table-condensed small">
<tbody>
<tr>
<td width="40%">SIZE:</td>
<td width="60%"><?= $product["diam"]; ?></td>
</tr>
<tr>
<td>Width:</td>
<td><?= $product["width"]; ?></td>
</tr>
<tr>
<td>Profile:</td>
<td><?= $product["profile"]; ?></td>
</tr>
<tr>
<td>Stock:</td>
<td><?= $product["quantity"]; ?></td>
</tr>
<tr>
<td>Rating:</td>
<td><?= $product["rating"] ?></td>
</tr>
</tbody>
</table>
if ($brand != 'Any') $featuredSql .= " AND t.manufacturer='$brand'";
$featuredSql .= "GROUP BY t.diam,t.manufacturer, t.width";
if (!$featured = mysqli_query($db, $featuredSql)) die(mysqli_error());
var_dump($featured);
if (!$tyre1 = mysqli_fetch_object($featured)) echo "<br />No tyres match those parameters. Please try again.";
}
Now the problem is the database is poorly maintained and several items are duplicates (hence the GROUP BY diam, manufacturer and width) but each of those items has its own stock, eg
Item part_no abc stock 5,
Item part_no abc stock 7
so there are actually 12, but are both listed as separate items,the GROUP_BY groups them together, but doesn't do anything with the stock level.
My question is how should I handle this? I've looked at trying to use COUNT in the original Query, but the while loop with the fetch assoc breaks if I do that. Although I could have coded it incorrectly (fairly new to PHP and using MySQL).
I could also GROUP BY part_no but this doesn't seem to help either.
Additional Information as recommended
Tyre's Database
RecID is Unique Primary Key
part_no Not Unique
stockCode IS UNIQUE
Sample Data
\/65\/14-4015","thumbnail":null,"bigpic":null,"rating":"82H","tread":null,"profile":"65","width":"175","diam":"14","description":null,"rrp":"0.00","flag":null,"notes":"","treadid":"707","hide":"no","quantity":"1","nRetailPrice":"79.00","city_name":"New Plymouth","tread_thumbnail":"707_thumb.jpg","tread_bigpic":"707_large.jpg"},
{"recid":"3705","part_no":"ALT185\/65\/14","manufacturer":"ALTENZO","supplier":null,"stockcode":"TY-ALT185\/65\/14-3705","thumbnail":null,"bigpic":null,"rating":"86H","tread":null,"profile":"65","width":"185","diam":"14","description":null,"rrp":"0.00","flag":null,"notes":"","treadid":"707","hide":"no","quantity":"1","nRetailPrice":"79.00","city_name":"Palmerston North","tread_thumbnail":"707_thumb.jpg","tread_bigpic":"707_large.jpg"},
{"recid":"4557","part_no":"ALT185\/60\/15","manufacturer":"Altenzo","supplier":null,"stockcode":"TY-ALT185\/60\/15-4557","thumbnail":null,"bigpic":null,"rating":"88H","tread":null,"profile":"60","width":"185","diam":"15","description":null,"rrp":"0.00","flag":null,"notes":"","treadid":"707","hide":"no","quantity":"2","nRetailPrice":"99.00","city_name":"Petone","tread_thumbnail":"707_thumb.jpg","tread_bigpic":"707_large.jpg"},
{"recid":"2827","part_no":"ALT195\/50\/15","manufacturer":"ALTENZO","supplier":null,"stockcode":"TY-ALT195

PHP Script - Activity Description not reflecting record values

I had a need for a system that could track billable tasks for tickets that we processed. I have a script that is almost complete, but I cannot seem to figure out why the tickets_tasks_activity field is not pulling the right enum_short_description when displaying. When I add a task the values are added correctly, its only not displaying them correctly. It seems that I can add one activity... and then every additional activity has the same description even though the values are different in the database. Could someone please help me out.
Here is the script to pull the information from the database.
* Get the tasks associated with a ticket.
*
* #company_id The ID of the company that is being queried.
* #ticket_id The ID of the ticket that is being queried.
*/
function get_ticket_tasks($company_id, $ticket_id)
{
$sql = "SELECT u.user_first_name,
u.user_last_name,
u.user_id,
tn.tickets_tasks_posted_date,
tn.tickets_tasks_task,
tn.tickets_tasks_activity,
(SELECT enum_short_description FROM tbl_enum WHERE enum_id = tn.tickets_tasks_activity) tickets_tasks_activity_description
FROM tbl_tickets_tasks tn,
tbl_user u
WHERE tn.tickets_tasks_company_id = {$company_id}
AND tn.tickets_tasks_ticket_id = {$ticket_id}
AND tn.tickets_tasks_posted_user_id = u.user_id;";
$query = $this->db->query($sql);
// If nothing was returned invalid query.
if($query->num_rows() == 0)
return false;
return $query->result_array();
}
Here is the code for the View Page
<div class="tab-pane" id="tasks">
<div class="row">
<div class="col-lg-12">
<?php
if($tasks)
{ ?>
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>Service Provided</th>
<th>Value</th>
<th>Who?</th>
<th>When?</th>
</tr>
</thead>
<tbody>
<?php
for($i = 0; $i < count($tasks); ++$i)
{ ?>
<tr>
<td><?php echo $tasks[0]['tickets_tasks_activity_description']; ?></td>
<td><?php echo nl2br($tasks[$i]['tickets_tasks_task']); ?></td>
<td><?php echo $tasks[$i]['user_first_name'].' '.$tasks[$i]['user_last_name']; ?></td>
<td><?php echo date("m/d/Y", strtotime($tasks[$i]['tickets_tasks_posted_date'])); ?></td>
</tr>
<?php
} ?>
</tbody>
</table>
<?php
}
else
{ ?>
<p>This ticket does not have any tasks.</p>
<?php
} ?>
</div>
</div>
</div>
Here you have (at the beginning of the loop):
<td><?php echo $tasks[0]['tickets_tasks_activity_description']; ?></td>
you're printing always $task[0], you should print $task[$i]
PS: You should probably state your JOIN in the FROM section of your SQL clause (instead to put it on the WERE section), at first I though you had none :-)

create horizontal bar chart

I want to make a horizontal bar chart in a web-page using php,mysql,javascript,css,html and 'wamp server',editor: 'Macromedia Dreamweaver',browser: 'Mozilla Firefox';
i want to read data(semister results) from table,and display data through bar chart like,
Database name exam
Table name 'sem_result' contain following columns>> regno[Primary key], uid, reg_date, exam_date, sem, result;
php code is::
<?php
// Connect to server
$cn=mysql_connect("localhost", "root", "");
//Connect to Database
mysql_select_db("exam") or die(mysql_error());
//sql query
$sql="SELECT result FROM sem_result WHERE uid=11111";
//collect results
$result=mysql_query($sql,$cn);
//read data if found
$counter=0;
while($rd=mysql_fetch_array($result))
{
$sem_result[$counter]=$rd[0]; //save sem results into array
$counter=$counter+1;
}
//display
echo "<table>
<tr>
<td>sem1</td>
<td width='100px'>
<img src='img/menu_back.png' width='".$sem_result[0]."%' height='15px'/>
</td>
<td>".$sem_result[0]."%</td>
</tr>
<tr>
<td>sem2</td>
<td width='100px'>
<img src='img/menu_back.png' width='".$sem_result[1]."%' height='15px'/>
</td>
<td>".$sem_result[1]."</td>
</tr>
</table>";
//close database
mysql_close($cn);
?>
if results are 78.95%,78.10% ,bar chart shows both result are equal, i.e 78%; image width become 78%,not 78.95% please help to fix this problem.
change table name and column name and progress.png image.
after that use it.
`
<?php $s="select count(*) as tnum from leakage";
$r=mysql_query($s) or die (mysql_error());
while($rw=mysql_fetch_array($r))
{
echo $tno=$rw['tnum'];
}
?>
<table class="table table-hover">
<thead>
<tr>
<th>DEPARTMENT</th>
<th>No.Of Leakage</th>
</tr>
</thead>
<?php
$sql1="select dept,count(dept) as total from leakage where dept='winding'";
$result1=mysql_query($sql1) or die(mysql_error());
while($row=mysql_fetch_array($result1))
{
$dept=$row['dept'];
$tot=$row['total'];
}
?>
<tr>
<td><?php echo $dept; ?></td>
<td width="100%"><img src="assets/images/progress.png" width="<?php echo (($tot/$tno)*100);?>" height="20px"><?php echo $tot;?>%</td>
</tr>
<?php
$sql2="select dept,count(dept) as total from leakage where dept='spining'";
$result2=mysql_query($sql2) or die(mysql_error());
while($row=mysql_fetch_array($result2))
{
$dept=$row['dept'];
$tot=$row['total'];
}
?>
<tr>
<td><?php echo $dept; ?></td>
<td width="100%"><img src="assets/images/progress.png" width="<?php echo (($tot/$tno)*100);?>" height="20px"><?php echo $tot;?>%</td>
</tr>
<?php
$sql5="select count(dept) as total from leakage";
$result5=mysql_query($sql5) or die(mysql_error());
while($row=mysql_fetch_array($result5))
{
$tot=$row['total'];
}
?>
<tr>
<td>Total</td>
<td width="100%"><img src="assets/images/progress.png" width="<?php echo $tot;?>" height="20px"><?php echo $tot; ?></td>
</tr>
</table>
`
As #hakre already pointed out, you can't get any more precise than a single pixel or percentage, ie you can't have 78.5px or 78.5%... however, you still have some options without javascript. First, I'm not sure why you are using an image for the green bar, why not just pure html/css? Either way, here's my suggestion:
Get the total width of the bar graph, from 0 - 100, in pixels. Just by eyeballing the image you posted, I'm gonna call it 325px:
$total_width = '325';
Then, set each bar's width as such:
$bar_width = round($total_width * ($sem_result[0] / 100));
This way, a stored value of 78.10% will end up as 254px, and 78.95% will be 257px. It is still not the exact percentage, but it is closer. The longer the total width of your graph, the more precise you calculation will be.

grouping class names together in my CMS php

I am done with a CMS school system which i created from scratch for practice in php. My question is for example I have Accounting 101, Computer Science 101, however there must multiple times for Accounting 101. For example: Ticket 1035, 1036 are both Accounting 101 and they should appear in the same table, but in my code it shows them in different classes. Here is my code.
if(isset($_GET['id']))
{
$category = $_GET['id'];
$sql = "SELECT * FROM classes WHERE category_id = " . $category;
$query2 = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_object($query2))
{
?>
<center><h3><?php echo $row->class_name . '-' . $row->units; ?> </h3></center>
<table border ="0" wdith="100%">
<tr>
<td>
<strong>Description: </strong>
<?php echo $row->class_description; ?>
</tr>
</td>
</table>
<br/>
<table border="1" width="44%">
<tr>
<td width="60"><b>Ticket</b> </td>
<td width="123"><b>Days</b></td>
<td width="120"><b>Hours</b></td>
<td width="64"><b>Room</b></td>
<td><b>Instructor</b></td>
</tr>
<tr>
<td width="60"> <?php echo $row->ticket; ?> </td>
<td width="123"><?php echo $row->days; ?></td>
<td width="120"><?php echo $row->start_hours . $row->time_format . '-' . $row->end_hours . $row->time_format2 ; ?> </td>
<td width="64"> <?php echo $row->room_number; ?></td>
<td><?php echo $row->instructor_name; ?></td>
</tr>
}//end while
}//end if
Its showing Accounting 101 with different tickets in different tables, but it should be all in 1 table. Thanks.
You need a double loop if you're trying to get records inside of records. For example:
while ($row1 = mysql_fetch_object($query1))
{
echo $row1->ParentName;
$query2 = 'select * from `mytable` where `myForeignKey` = ' . $row1->ParentId;
while ($row2 = mysql_fetch_object($query2))
{
echo $row2->ChildName;
}
}
You could also do a left join. Let me know if you need a sample of that.
Edit:
The left join would be done like this:
$sql = "select * from `classes` as a where category_id = '{$category}' left join `tickets` as b on a.id = b.class_id"
Ref. http://www.w3schools.com/sql/sql_join_left.asp

Categories