I'm pulling a table from a MySQL database, using PHP.
This is roughly the code I'm using, obviously I've got more columns, but this is the demo version of the code.
As you can see, the code is ordered by the Sales Name. Now what I want to do is, show a little icon next to the top ten sellers based on the Sales Count.
So, if a Sales Count is one of the top ten figures, it must show a little image next to it's name.
Can this be done?
<?php
// Get all the data from the "sales" table
$result = mysql_query("SELECT * FROM sales ORDER BY SalesName") or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Sales Name</th> <th>Sales Count</th> </tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr><td>";
echo $row['SalesName'];
echo "</td><td>";
echo $row['SalesCount'];
echo "</td></tr>";
}
echo "</table>";
?>
Yes you can do it:
<?php
$item_no=1 // number of current items
// Get all the data from the "sales" table
$result = mysql_query("SELECT * FROM sales ORDER BY SalesCount desc SalesName ") or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Sales Name</th> <th>Sales Count</th> </tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr><td>";
if($item_no <= 10){
echo 'your image here';
$item_no++;
}
echo $row['SalesName'];
echo "</td><td>";
echo $row['SalesCount'];
echo "</td></tr>";
}
echo "</table>";
?>
Try something like this :
$result = mysql_query("SELECT * FROM sales ORDER BY SalesName") or die(mysql_error());
$result2 = mysql_query("SELECT id FROM sales ORDER BY SalesCount DESC limit 10") or die(mysql_error());
while($savedResult = mysql_fetch_array($result2)) {
$topten[] = $savedResult[0];
}
echo "<table border='1'>";
echo "<tr> <th>Sales Name</th> <th>Sales Count</th> </tr>";
while ($row = mysql_fetch_array($result )) {
echo "<tr><td>";
echo $row['SalesName'];
if (in_array($row['id'],$topten)) {
echo '<img src="star.gif"/>';
}
echo "</td><td>";
echo $row['SalesCount'];
echo "</td></tr>";
}
echo "</table>";
This sends a second query which gets the id column for the top ten orders by sales count. I then store these ids in an array ($topten). While in the loop to display the table I check if the line being processed is in the top ten array - if so add a star !
you could do something like
<?php
// Get all the data from the "sales" table
$result = mysql_query("SELECT * FROM sales ORDER BY SalesName") or die(mysql_error());
$topTen = mysql_query("SELECT SalesName FROM sales ORDER BY SalesCount LIMIT 10") or die(mysql_error());
$topTenArray = array();
while($row = mysql_fetch_array( $result )) {
$topTenArray[] = $row['SalesName'];
}
echo "<table border='1'>";
echo "<tr> <th>Sales Name</th> <th>Sales Count</th> </tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr><td>";
echo $row['SalesName'];
echo "</td><td>";
echo $row['SalesCount'];
if(in_array($row['SalesName'],$topTenArray){
echo "<img src.... />";
}
echo "</td></tr>";
}
echo "</table>";
?>
Related
I am trying to update a specific row in a table; however, when the query runs, it updates the last record added instead of the record selected.
The SQL statement was taken straight from phpmyAdmin. I have tried "UPDATE registration_tbl SET Paid = 'PAID' WHERE ID='$row21'" and that still did not work.
Have I put something wrong in the code?
<table class="table table-striped table-hover table table-responsive-sm table-responsive-md table-responsive-lg">
<tr>
<th>Title</th>
<th>First Name</th>
<th>Last Name</th>
<th>Sex</th>
<th>Age</th>
<th>Address Type</th>
<th>Address 1</th>
<th>Address 2</th>
<th>Home</th>
<th>Work</th>
<th>Cell</th>
<th>Email Address</th>
<th>Congregation</th>
<th>RMC</th>
<th>Auxillary</th>
<th>Occupation</th>
<th>Category</th>
<th>Username</th>
<th>Submission Date</th>
<th>Payment Status</th>
<th>Action</th>
</tr>
<?php
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$result_set = mysqli_query($conn,"SELECT * FROM registration_tbl");
$num_messages = mysqli_num_rows($result_set);
$num = 0;
while($row = mysqli_fetch_array($result_set))
{
$row1 = $row["Title"];
$row2 = $row["FirstName"];
$row3 = $row["LastName"];
$row4 = $row["Sex"];
$row5 = $row["Age"];
$row6 = $row["AddressType"];
$row7 = $row["Address1"];
$row8 = $row["Address2"];
$row9 = $row["Home"];
$row10 = $row["Work"];
$row11 = $row["Cell"];
$row12 = $row["EmailAdd"];
$row13 = $row["Congregation"];
$row14 = $row["RMC"];
$row15 = $row["Auxillary"];
$row16 = $row["Occupation"];
$row17 = $row["Category"];
$row18 = $row["Username"];
$row19 = $row["DateSubmitted"];
$row20 = $row["Paid"];
$row21 = $row["ID"];
$num++;
echo "<tr>";
echo "<td>$row1</td>";
echo "<td>$row2</td>";
echo "<td>$row3</td>";
echo "<td>$row4</td>";
echo "<td>$row5</td>";
echo "<td>$row6</td>";
echo "<td>$row7</td>";
echo "<td>$row8</td>";
echo "<td>$row9</td>";
echo "<td>$row10</td>";
echo "<td>$row11</td>";
echo "<td>$row12</td>";
echo "<td>$row13</td>";
echo "<td>$row14</td>";
echo "<td>$row15</td>";
echo "<td>$row16</td>";
echo "<td>$row17</td>";
echo "<td>$row18</td>";
echo "<td>$row19</td>";
echo "<td>$row20</td>";
if($row20 != "PAID")
{
echo "<td><input type='submit' class='btn btn-success' name='paid' value='PAID' /></td></tr>";
}
}
echo "</table></br>";
echo "<table><tr><td>";
echo $num_messages . " Registration(s) Found!";
echo "</td></tr></table>";
if(isset($_POST['paid']))
{
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$updatePaymentStmt = "UPDATE `registration_tbl` SET `Paid` = 'PAID' WHERE `registration_tbl`.`ID` = $row21;";
if(mysqli_query($conn, $updatePaymentStmt))
{
echo "<script>alert('Payment updated successfully!')</script>";
}
else
{
echo "<script>alert('Error in updating Payment!')</script>";
}
}
I think you're going to want a separate form for each row in the table. And you'll need a hidden field in that form containing the ID so the server knows which ID to process when it receives the submission.
Remove any <form>...</form> tags you may have placed to wrap around the whole table, and instead use:
if($row20 != "PAID")
{
echo "<td><form action='' method='post'><input type='submit' class='btn btn-success' name='paid' value='PAID' /><input type='hidden' name='id' value='".$row["ID"]."'/></form></td></tr>";
}
and then
if(isset($_POST['paid']))
{
$id = $_POST["id"];
///etc, you can now use $id in a parameter in your query, to select the correct row
P.S. The rest of the code could also be greatly simplified, as others have mentioned in the comments, and you should definitely fix the SQL injection issue - that's a serious security problem.
This bug comes about from a flaw in your thinking rather than unexpected behaviour in the code.
Effectively you have a while loop that iterates over the entire results set (from the first query) and updates the $row* variables. What this means is that $row21 is always going to be the last selected record. If you were to chuck an ORDER BY id DESC on the end you'd find that the first record was always updated...
So what you actually want to do is add the id into the button - and make each button it's own form - so that when the form is posted the intended id is in the button's value.
Something like:
<?php
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$registrations = $mysqli->query($conn,"SELECT * FROM registration_tbl");
$num_messages = $registration->num_rows;
while ($row = $registrations->fetch_assoc() {
echo "<tr>";
echo "<td>{$row["Title"]}</td>";
echo "<td>{$row["FirstName"]}</td>";
echo "<td>{$row["LastName"]}</td>";
echo "<td>{$row["Sex"]}</td>";
echo "<td>{$row["Age"]}</td>";
echo "<td>{$row["AddressType"]}</td>";
echo "<td>{$row["Address1"]}</td>";
echo "<td>{$row["Address2"]}</td>";
echo "<td>{$row["Home"]}</td>";
echo "<td>{$row["Work"]}</td>";
echo "<td>{$row["Cell"]}</td>";
echo "<td>{$row["EmailAdd"]}</td>";
echo "<td>{$row["Congregation"]}</td>";
echo "<td>{$row["RMC"]}</td>";
echo "<td>{$row["Auxillary"]}</td>";
echo "<td>{$row["Occupation"]}</td>";
echo "<td>{$row["Category"]}</td>";
echo "<td>{$row["Username"]}</td>";
echo "<td>{$row["DateSubmitted"]}</td>";
echo "<td>{$row["Paid"]}</td>";
echo $row["Paid"]] !== "PAID" ?
"<td><form method='post'><button class='btn btn-success' name='paid' value='{$row["ID"]}'>Paid</button></form></td>" :
"<td></td>";
}
echo "</tr>";
}
echo "</table></br>";
echo "<table><tr><td>";
echo $num_messages . " Registration(s) Found!";
echo "</td></tr></table>";
if ($_POST['paid'] ?? null) {
$sql = "UPDATE `registration_tbl` SET `Paid` = 'PAID' WHERE `registration_tbl`.`ID` = ?";
$query = $mysqli->prepare($sql);
$query->bind_param("i", $_POST["paid"]);
echo $query->execute() ?
"<script>alert('Payment updated successfully!')</script>" :
"<script>alert('Error in updating Payment!')</script>";
}
}
I have following data in my SQL table:
id code day time year
1 PRC-001 0 t-1 2017
2 PRC-001 1 t-2 2017
3 PRC-002 0 t-3 2017
4 PRC-002 1 t-4 2017
5 PRC-003 0 t-5 2017
6 PRC-003 1 t-6 2017
Output should be like this:
day0 day1 code
t-1 t-2 PRC-001
t-3 t-4 PRC-002
t-5 t-6 PRC-003
How can I do this? I was trying something like the following code. But I didn't get any desire output. Here is my code:
$query1 = "SELECT * FROM routine AS tab1,";
$query1.= " GROUP BY code";
$rs = mysql_query($query1);
$numOfRows=mysql_num_rows($rs);
$printed = array();
$resultset = array();
while($row = mysql_fetch_assoc($rs)) {
$resultset[] = $row;
#print_r($row);
}
$q = "<table id='ash'>";
$q.= "<tr id='grey'>";
$q.= "<th rowspan='2'>day0</th>";
$q.= "<th rowspan='2'>day1(s)</th>";
$q.= "<th rowspan='2'>code</th></tr>";
$q.= "</tr>";
foreach ($resultset as $row){
$q.= "<tr>";
$q.= "<tr><td id='clist'>".$row["time"]."</td>";
$q.= "<td id='clist'>".$row["time"]."</td>";
$q.= "<td id='clist'>".$row["code"]."</td></tr>";
}
$q .= "</table>";
echo $q;
Firstly, as mentioned in the comments you should look at using something other than the mysql_ functions.
Second, with you're query you need to remove the GROUP BY.
Then you could do something like:
$rs = mysql_query("SELECT * FROM routine");
$results = [];
while ($row = mysql_fetch_assoc($rs)) {
$code = $row['code'];
if (!isset($results[$code])) {
$results[$code] = [
'day0' => '-',
'day1' => '-',
];
}
$results[$code]['day' . $row['day']] = $row['time'];
}
?>
<table>
<thead>
<tr id="grey">
<th rowspan="2">Day0</th>
<th rowspan="2">Day1(s)</th>
<th rowspan="2">code</th>
</tr>
</thead>
<tbody>
<?php foreach ($results as $code => $result) : ?>
<!--You shouldn't have multiple elements using the same ids-->
<tr>
<td id='clist'><?php echo $result['day0'] ?></td>
<td id='clist'><?php echo $result['day1'] ?></td>
<td id='clist'><?php echo $code ?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
Hope this helps!
according to your desired table, the columns in a row are not in a row in database table! so you can not build table with just a foreach through query results.
for example, t-1, t-2 and PRC-001 are not in a row in database. if day0 is t-1 then day1 would be empty and vice versa.
solution:
you have to put empty or zero for one of days in final table to make sense , and you don't need groupby:
$query1 = "SELECT * FROM routine AS tab1";
$rs = mysql_query($query1);
$numOfRows=mysql_num_rows($rs);
$printed = array();
$resultset = array();
while($row = mysql_fetch_assoc($rs)) {
$resultset[] = $row;
#print_r($row);
}
$q = "<table id='ash'>";
$q.= "<tr id='grey'>";
$q.= "<th rowspan='2'>day0</th>";
$q.= "<th rowspan='2'>day1(s)</th>";
$q.= "<th rowspan='2'>code</th></tr>";
$q.= "</tr>";
foreach ($resultset as $row){
if($row['day'] == 0){
$q.= "<tr>";
$q.= "<tr><td id='clist'>".$row["time"]."</td>";
$q.= "<td id='clist'>"EMPTY!"</td>";
$q.= "<td id='clist'>".$row["code"]."</td></tr>";
} else {
$q.= "<tr>";
$q.= "<tr><td id='clist'>"EMPTY!"</td>";
$q.= "<td id='clist'>".$row["time"]."</td>";
$q.= "<td id='clist'>".$row["code"]."</td></tr>";
}
}
$q .= "</table>";
echo $q;
I want to run two different mysql queries and output results into two different html tables. I'm opening one DB connection and fetching two entirely different result sets.
I have one page that I want to show two different 's in the page, each table is the results from different query.
echo "<table class='table table-striped table-bordered table-hover table-condensed'>";
echo "<thead><tr>";
echo "<th>Last</th><th>First</th><th>MDC</th><th>RADIO</th><th>EPCR</th><th>FH</th>";
echo "</tr></thead></table>";
while ($rowA = mysql_fetch_array($result)) {
echo "<tbody><tr>";
echo "<td>".$rowA['LAST']."</td>";
echo "<td>".$rowA['FIRST']."</td>";
echo "<td>".$rowA['MDC']."</td>";
echo "<td>".$rowA['RADIO']."</td>";
echo "<td>".$rowA['ePCR']."</td>";
echo "<td>".$rowA['Firehouse']."</td>";
}
echo "</tr></tbody></table>";
echo "<table class='table table-striped table-bordered table-condensed'>";
echo "<thead><tr>";
echo "<th>USERNAME</th><th>CLASSNAME</th><th>DATE COMPLETED</th>";
echo "</tr></thead></table>";
while ($rowB = mysql_fetch_array($sql)) {
echo "<tbody><tr>";
echo "<td>".$rowB['UserName']."</td>";
echo "<td>".$rowB['ClassName']."</td>";
echo "<td>".$rowB['DateCompleted']."</td>";
}
echo "</tr></tbody></table>";
mysql_close($dbhandle);
here is my query:
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("tech_training",$dbhandle)
or die("Could not select examples");
$result = mysql_query("SELECT LastName AS LAST, FirstName AS FIRST,
MAX(IF(`ClassName`='MDC (Intro)', DATE_FORMAT(`DateCompleted`, '%m/%d/%Y'), NULL)) AS 'MDC',
MAX(IF(`ClassName`='800 MHz Radio (Intro)', DATE_FORMAT(`DateCompleted`, '%m/%d/%Y'), NULL)) AS 'RADIO',
MAX(IF(`ClassName`='ePCR (Intro)', DATE_FORMAT(`DateCompleted`, '%m/%d/%Y'), NULL)) AS 'ePCR',
MAX(IF(`ClassName`='Firehouse (Incident)', DATE_FORMAT(`DateCompleted`, '%m/%d/%Y'), NULL)) AS 'Firehouse'
FROM EnrollmentsTbl INNER JOIN UsersDataTbl ON EnrollmentsTbl.UserName = UsersDataTbl.UserName
GROUP BY EnrollmentsTbl.UserName
ORDER BY LastName
LIMIT 20;");
//execute the second SQL query and return records
$sql = mysql_query("SELECT UserName, ClassName, DateCompleted FROM EnrollmentsTbl LIMIT 10;");
Somewhere at the top of the page, or preferably use an include statement since according to PSR 1 you should not have output mixed with functions/classes.
Use PDO and here is an example.
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$stmt = $db->query('SELECT * FROM table');
$rowA = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt = $db->query('SELECT * FROM table2');
$rowB = $stmt->fetchAll(PDO::FETCH_ASSOC);
ANSWER
echo "<tbody>"; //this is outside
while ($rowB = mysql_fetch_array($sql)) {
echo "<tr>";
echo "<td>".$rowB['UserName']."</td>";
echo "<td>".$rowB['ClassName']."</td>";
echo "<td>".$rowB['DateCompleted']."</td>";
echo "</tr>";// MOVE THIS INSIDE THE LOOP!!!
}
echo "</tbody></table>";
other loop:
echo "<tbody>"; //outide
while ($rowA = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>".$rowA['LAST']."</td>";
echo "<td>".$rowA['FIRST']."</td>";
echo "<td>".$rowA['MDC']."</td>";
echo "<td>".$rowA['RADIO']."</td>";
echo "<td>".$rowA['ePCR']."</td>";
echo "<td>".$rowA['Firehouse']."</td>";
echo "</tr>"; //move end row here
}
echo "</tbody></table>";
EXPLANATION
//you have some array
$result = [];
echo "<table>" // you only want one of these
foreach($results as $rows){
echo "<tr>";
echo "<td>data</td><td> mode data </td>";
echo "</tr>"; close row each time
}
echo "</table>" //close it ONLY ONCE!
Recommendation
Proper and readable formatting would of saved you. EX:
echo "<table class='table table-striped table-bordered table-hover table-condensed'>
<thead>
<tr>
<th>Last</th><th>First</th><th>MDC</th><th>RADIO</th><th>EPCR</th><th>FH</th></tr>
</thead>
</table>";
OR:
$table = <<<HTML
<table class='table table-striped table-bordered table-hover table-condensed'>
<thead>
<tr>
<th>Last</th><th>First</th><th>MDC</th><th>RADIO</th><th>EPCR</th><th>FH</th></tr>
</thead>
</table>
HTML;
echo $table;
This one is a bit perplexing since it works perfectly on some records, and not on others. I am trying to pull all records with a specific email and only getting one record in about half of the cases. I have two query sets one pulling the data one is pulling it half of the time.
The first that works all the time is:
$tiera = mysql_query("SELECT SUM(datamb) AS tiera FROM maindata2 WHERE dataplan = '2' and email='".mysql_real_escape_string($_POST['email'])."'");
$tiera1 = mysql_fetch_assoc($tiera);
$tiera2 = $tiera1['tiera'];
$tieradata = mysql_query("SELECT SUM(dataplan) as datatotal FROM maindata2 WHERE dataplan = '2' and email='".mysql_real_escape_string($_POST['email'])."'");
$tieradata1 = mysql_fetch_assoc($tieradata);
$tieradata2 = $tieradata1['datatotal'];
echo "<table id='display1'>
<tr>
<th>Tier:</th>
<th>Total Data in Tier:</th>
<th>Data Usage This Period:</th>
<th>Remaining:</th>
</tr>";
echo "<tr>";
echo "<td>A</td> ";
echo "<td>". $tieradata2 . " MB</td> ";
echo "<td>". $tiera2. " MB</td> ";
echo "<td>".($tieradata1['datatotal'] - ROUND ($tiera1['tiera'],2)) . "MB</td></font> ";
echo "</table>";
I cant use this for my second query because I need it in the loop like this:
$sql = "SELECT phonenumber,date,email, dataplan AS currentplan, SUM(datamb) AS value_sum FROM maindata2 WHERE email='".mysql_real_escape_string($_POST['email'])."' GROUP BY dataplan, phonenumber ";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No Data Found For This Email";
exit;
}
$row = mysql_fetch_assoc($result);
$query = mysql_query($sql) or die(mysql_error());
$header_printed = false;
while($row = mysql_fetch_array($query)) {
if ($row['phonenumber']) {
if ($header_printed === false) {
echo "
<table id='display'>
<tr>
<th>Phone Number:</th>
<th>Data Plan:</th>
<th>Data Usage This Period:</th>
<th>Remaining:</th>
<th>Date Reporting:</th>
</tr>";
$header_printed = true;
}
while ($row = mysql_fetch_assoc($result)){
echo "<tr>";
echo "<td>".$row['phonenumber'] . "</td> ";
echo "<td>".$row['currentplan'] . "MB</td> ";
echo "<td>".ROUND ($row["value_sum"],2) . "MB</td> ";
echo "<td><font color=$color>".($row['currentplan'] - ROUND ($row["value_sum"],2)) . "MB</td></font> ";
echo "<td>".$row['date'] . "</td></tr>";
}
}
echo "</table>";
So the question is, what is missing from the second query that is in the first?
I have to following problem, after running script below it prints out an extra header at the end?
What I am doing is getting data from two tables, with certain parameters then placing them into a table. The echo $result at the end is just to see what is still inside $result and it prints out a value before the extra header as well as right after the header.
How can I get around that?
extract(shortcode_atts(array(
"countryid"=>'',
), $atts));
// Setting up variables
// Get all the data from the "example" table
$joburl = "http://www.x.co.za/job/view/";
$result = mysql_query("SELECT wpjb_job.company_name , wpjb_job.job_category , wpjb_job.job_country ,
wpjb_job.job_title , wpjb_job.job_slug ,
wpjb_category.id , wpjb_category.title
FROM wpjb_job
INNER JOIN wpjb_category ON wpjb_job.job_category = wpjb_category.id
WHERE job_country='$countryid'
AND(is_filled='0' AND is_active='1')
ORDER BY job_title")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Job</th> <th>Company</th> <th>Industry</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo ' '.$row['job_title'].' ';
echo "</td><td>";
echo $row['company_name'];
echo "</td><td>";
echo $row['title'];
echo "</td></tr>";
}
echo "</table>";
echo $result;
}
Ok Try as below
Put your header line and close tag of table into below condition
$count = mysql_num_rows($result);
if($count > 0){
echo "<table border='1'>";
echo "<tr> <th>Job</th> <th>Company</th> <th>Industry</th> </tr>";
}
//your while loop
while(...) {
....
}
if($count > 0){
echo "</table>";
}