SQL calculate row number - php

I doing league table football and There is a profile of Team (Like : Team.php?team=XXX)
In this page I want to show, What position of TeamXXX in League Table
Page League Table
<?php
$number = 0;
$sql = "SELECT * FROM `leaguetable` WHERE `league` = 'leaguename' ORDER BY pts DESC";
$query = mysql_query($sql);
while($rs=mysql_fetch_assoc($query)){
$number++;
?>
<table>
<thead>
<tr>
<th>Position</th>
<th>Team</th>
<th>Points</th>
</tr>
</thead>
<tbody>
<td><?php echo $number; ?></td>
<td><?php echo $rs['team']; ?></td>
<td><?php echo $rs['pts']; ?></td>
</tbody>
</table>
<?php } ?>
Data in Table leaguetable
id team pts
In team.php I want to show position of TeamXXX
<?php
$getTeam = mysql_fetch_assoc(mysql_query("SELECT * FROM `leaguetable` WHERE `team`='"$_GET['team']"'");
?>
<table>
<thead>
<tr>
<th>Position</th>
<th>Team</th>
<th>Points</th>
</tr>
</thead>
<tbody>
<td>#########</td>
<td><? echo $getTeam['team']; ?></td>
<td><? echo $getTeam['pts']; ?></td>
</tbody>
</table>
How can I know what position of teamXXX in leaguetable?
Any help will be greatly appreciated. Thank you very much

query
select id, team, pts, rnk
from
(
select leag.id, leag.team, leag.pts,
#rnk := if(leag.pts = #lag, #rnk,
if(#lag := leag.pts, #rnk + 1, #rnk + 1)) as rnk
from leaguetable leag
cross join ( select #rnk := 0, #lag := null ) params
where league = 'FA Cup'
order by leag.pts desc
) rankings
where team = 'Chelsea'
;
example.php
<?php
/**
* Mysqli initial code
*
* User permissions of database
* Create, Alter and Index table, Create view, and Select, Insert, Update, Delete table data
*
* #package PhpFiddle
* #link http://phpfiddle.org
* #since 2012
*/
require_once "dBug!.php";
require "util/public_db_info.php";
$short_connect = new mysqli($host_name, $user_name, $pass_word, $database_name, $port);
if (mysqli_connect_errno())
{
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
/*
$sql = "create table leaguetable"
. "("
. " id integer primary key not null,"
. " team varchar(33) not null,"
. " pts integer not null default 0"
. ");";
$result = $short_connect->query($sql);
if(!$result)
{
die("Create table failed : " . mysqli_error($short_connect));
}
$sql = "insert into leaguetable"
. "( id, team, pts )"
. "values"
. "( 1, 'Liverpool', 22 ),"
. "( 2, 'Arsenal', 29 ),"
. "( 3, 'Chelsea', 23 ),"
. "( 4, 'Tottenham', 23)";
$result = $short_connect->query($sql);
if(!$result)
{
die("insert failed : " . mysqli_error($short_connect));
}
*/
//get all tables in the database
//$sql = "SHOW TABLES";
//get column information from a table in the database
//$sql="SELECT COLUMN_KEY, COLUMN_NAME, COLUMN_TYPE FROM information_schema.COLUMNS WHERE TABLE_NAME = 'books'";
//SQL statement for a table in the database
$sql = "select id, team, pts, rnk "
. "from"
. "("
. "select leag.id, leag.team, leag.pts,"
. "#rnk := if(leag.pts = #lag, #rnk,"
. " if(#lag := leag.pts, #rnk + 1, #rnk + 1)) as rnk "
. "from leaguetable leag "
. "cross join ( select #rnk := 0, #lag := null ) params "
. " where league = 'FA Cup' "
. "order by leag.pts desc;"
. ") rankings "
. where team = 'Chelsea';";
//result is boolean for query other than SELECT, SHOW, DESCRIBE and EXPLAIN
$result = $short_connect->query($sql);
if (($result) && ($result->num_rows > 0))
{
echo "<table>" . "<thead>" . "<tr>" . "<th>Position</th>" . "<th>Team</th>" . "<th>Points</th>" . "</tr>" . "</thead>" . "<tbody>";
//convert query result into an associative array
echo "<tr><td>" . $row['rnk'] . "</td><td>" . $row['team'] . "</td><td>" . $row['pts'] . "</td></tr>";
echo "</tbody></table>";
}
else
{
die("select failed : " . mysqli_error($short_connect));
}
$short_connect->close();
?>
output
<table>
<thead>
<tr>
<th>Position</th>
<th>Team</th>
<th>Points</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>Chelsea</td>
<td>23</td>
</tr>
</tbody>
</table>
sqlfiddle

Hope this will help
$number = 0;
$points=0;
$sql = "SELECT * FROM `leaguetable` WHERE `league` = 'leaguename' ORDER BY pts DESC";
$query = mysql_query($sql);
while($rs=mysql_fetch_assoc($query)){
if($points!=$rs['pts'])
$number++;
if($rs['team']==$_GET['team']){
if($points==$rs['pts'])
$position=$number-1;
else
$position=$number;
}
$poins=$rs['pts'];
}

If you don't mind using two queries (I wouldn't mind it), it's pretty easy: Just count how many teams have more points, and add one (so that if three teams are tied in second position, they all get position 2).
$result = mysql_query("SELECT count(*)+1 AS POSTN FROM leaguetable WHERE
league = 'leaguename' AND pts > $points");
$row = mysql_fetch_assoc($result);
$position = $row["POSTN"];
Doing it in one query is a bit messier, since you need to embed this query in your original one:
"SELECT *, (SELECT count(*)+1 FROM leaguetable table2
WHERE league = 'leaguename' AND table2.pts > leaguetable.pts) AS POSTN
FROM leaguetable WHERE team = '$currentteam'"
But why are you using the mysql_* API for new code? Haven't you noticed all the dire warnings in pink boxes in the documentation? Do yourself a favor and switch to mysqli today, starting with this program.
Also: Never just inject $_GET[param] into your query string! You're giving yourself an SQL injection attack waiting to happen... and brittle, error-prone code until then.

Related

PDO - Shows only 1 result in Table, not all with same ID

I have at the moment 2 results in my MySQL Database with same user_id and I want echo all in my HTML table with PDO, but it shows everytime only 1 result, not all.
<?php
$querytest = "SELECT o.output_valu,
p.amount,
p.amount_all,
p.order_id,
p.datetime
FROM allusers a
INNER JOIN order_history o
ON a.account_number = o.account_number
INNER JOIN paymentall p
ON o.output_vl_id = p.output_vl_id
WHERE a.account_number = :account_num
ORDER BY p.datetime";
$statementtest = $conn->prepare($queryoutgo);
$statementtest->bindParam(':account_num', $account_num);
$statementtest->execute();
$test_result = $statementtest->fetchAll();
foreach ($test_result as $row) {
$outputtest = $row['output_valu'];
}
?>
<table>
<tr>
<th>Test</th>
</tr>
<tr>
<td><?php echo $outputtest; ?></td>
</tr>
</table>
With print_r($test_result); it shows my 2 results in array, but why not with my code?
I worked always with mysqli not PDO in the past, maybe someone here can help me :)
In your foreach block you overwrite $outputtest every iteration. This means only the last result will be displayed. Depending on if you want to show each result on a separate row or if you want all the results together in one cell, you should either create the cells in the foreach or concatenate all the results together.
EDIT:
What I think you want is this:
$querytest = "SELECT o.output_valu, p.amount, p.amount_all, " .
"p.order_id, p.datetime " .
"FROM allusers a inner join order_history o " .
"ON a.account_number = o.account_number " .
"INNER JOIN paymentall p " .
"ON o.output_vl_id = p.output_vl_id " .
"WHERE a.account_number =:account_num " .
"ORDER BY p.datetime ";
$statementtest = $conn->prepare($queryoutgo);
$statementtest->bindParam(':account_num', $account_num);
$statementtest->execute();
$test_result = $statementtest->fetchAll();
?>
<table>
<tr>
<th>Test</th>
</tr>
<?php foreach($test_result as $row) { ?>
<tr><td><?= $row['output_valu']; ?></td></tr>
<?php } ?>
</table>

SUM function generates error in SQL query

I'm trying to get information about an SQL table via a php script however, whenever I add a SUM function I get the following error "Notice: Trying to get property 'num_rows' of non-object"
I don't know what's going on but if anyone can please explain/point me in the right direction as to how to fix this problem that would be greatly appreciated
Here's the 'broken' code
<?php
require("connect.php");
$inNo = $_POST["inNo"];
$sql = "SELECT invoice.invoice_no, invoice.date, invoice.cust_id, invoice.emp_id, invoice_line.prod_id,
invoice_line.qty, product.cost_price, (product.cost_price * invoice_line.qty) AS `multi`,
customer.first_name AS `customer_fname`, customer.last_name AS `customer_lname`,
employee.first_name AS `emp_fname`, employee.last_name AS `emp_lname`,
product.name AS `proname`
FROM invoice INNER JOIN invoice_line ON invoice.invoice_no = invoice_line.invoice_no
INNER JOIN product ON invoice_line.prod_id = product.id
INNER JOIN customer ON invoice.cust_id = customer.id
INNER JOIN employee ON invoice.emp_id = employee.id, SUM(multi) AS `invoicetotal`
WHERE cust_id = '" . $inNo . "'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
//open table
echo '<table class="table table-striped" id="outTable">';
echo "<tr><th>Product</th><th>Qty</th><th>Price</th><th>Total cost</th></tr>";
// output data of each row
$ctr = 0;
while($row = $result->fetch_assoc()) {
if ($ctr == 0)
{
echo "<h1>Invoice Number: " . $row["invoice_no"]. "</h1>";
echo "<p>Customer: " . $row["customer_fname"]. " " . $row["customer_lname"]."</p>";
echo "<p>Employee: " . $row["emp_fname"]. " " . $row["emp_lname"]. "</p>";
echo "<p>Date: " . $row["date"]. "</p>";
}
echo "
<tr>
<td>" . $row["proname"]. "</td>
<td>" . $row["qty"]. "</td>
<td>" . $row["cost_price"]. "</td>
<td>" . $row["multi"]. "</td>
</tr>";
$ctr++;
}
} else {
echo "0 results";
}
$conn->close();
?>
You need to insert the SUM() in the SELECT part above FROM:
SELECT
invoice.invoice_no,
invoice.date,
invoice.cust_id,
invoice.emp_id,
invoice_line.prod_id,
invoice_line.qty,
product.cost_price,
(product.cost_price * invoice_line.qty) AS `multi`,
customer.first_name AS `customer_fname`,
customer.last_name AS `customer_lname`,
employee.first_name AS `emp_fname`,
employee.last_name AS `emp_lname`,
product.name AS `proname`,
SUM(multi) AS `invoicetotal`
FROM invoice
INNER JOIN invoice_line
ON invoice.invoice_no = invoice_line.invoice_no
INNER JOIN product
ON invoice_line.prod_id = product.id
INNER JOIN customer
ON invoice.cust_id = customer.id
INNER JOIN employee
ON invoice.emp_id = employee.id` WHERE cust_id = 99
BTW, it's wise to format code - SQL code too - fine.

What can I do with this problem with mysql php and table result?

I have this query to list name categories and avg of each one, but the result is not what I want, how to sove this? if you look to image you see that the table resulta don't show correct
$query = $connMysqli->query("SELECT qc.name as cat_name
FROM fhrw_question_categories qc
...
group by Quiz, cat
ORDER BY u.id");
?>
<table>
<tr>
<?php
while($row = $query->fetch_assoc()){
echo '<th>' . $row['cat_name'] . '</th>';
}?>
</tr>
<!-- table continiuous avg-->
<?
$query = $connMysqli->query("SELECT avg(IFNULL(fraction, 0)) * 10 as Media, u.ud as student, qc.name as cat_name
FROM fhrw_question_attempt_steps qc
...
group by Quiz, u.id, cat
ORDER BY u.id ASC");
?>
<?php
while($row = $query->fetch_assoc()){
echo '<tr><td>' . $row['cat_name'] . ' - ' . round($row['Media'],2) . '</td></tr>';
}?>

Mysql Query Getting Item as ID in 2 different tables

Im sorry for my bad english but this is the best i can.
I am trying to make a script that get's the item values of one line in my
for this example i'll be using the row with ID 2.
The first query is working correctly and getting the 2 values of 1items and 2items and deletes the ; that comes with it.
But the second part seems a little bit harder and i can't solve it.
The query is getting id, base_item from the table
The last 2 Outputs marked red are the one's that are matching 1items & 2items
I'm trying to let the if statement filter the $item1 as id in the item table and output the baseitem of the found row
same goes for item2
I'm using MySQL & MySQLi because this cms doesnt support newer versions of PHP yet.
<?php
$query = "SELECT * FROM logs_client_trade ORDER by id DESC";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$item1 = rtrim($row['1items'],"; ");
$item2 = rtrim($row['2items'],"; ");
echo("<tr>");
echo("<td>" . $row['id'] . "</td>");
echo("<td>" . $row['1id'] . "</td>");
echo("<td>" . $row['2id'] . "</td>");
$userinfo = "SELECT id, base_item FROM items LIMIT 1";
$result2 = mysql_query($userinfo) or die(mysql_error());
while($row2 = mysql_fetch_assoc($result2)){
echo("<td>");
if($row2['id'] == $item1){ echo $row2['baseitem']; } else echo "Not available";
echo ("</td>");
echo("<td>");
if($row2['id'] == $item1){ echo $row2['baseitem']; } else echo "Not available";
echo ("</td>");
}
$tradetime = $row['timestamp'];
$date = date("d M Y - H:i:s", $tradetime);
echo("<td>$date</td></tr>");
}
?>
You forgot the while loop for the second query:
$userinfo = mysql_query("SELECT id, base_item FROM items");
while($get2 = $userinfo->fetch_assoc()) {
$baseid = $get2['id'];
$baseitem = $get2['baseitem'];
echo("<tr>");
[...]
}
In addition to that, your code is a mess. In the second loop you are still listing the rows from the logs table... I suggest you to review carefully your code, being careful on how you are using the different $row and $get2 arrays.
You can use a JOIN to get all of the info with one SQL statement:
SELECT *
FROM `logs_client_trade` a
LEFT JOIN `items` b
ON REPLACE(a.`1items`,';','') = b.`id`
LEFT JOIN `items` c
ON REPLACE(a.`2items`,';','') = c.`id`
ORDER by a.`id` DESC
UPDATE:
Here's the PHP code that will run the query and output the table rows. I've specified the column names based on the code in the original question.
<?php
$query = "SELECT
a.`id`,
a.`1id`,
a.`2id`,
a.`1items`,
a.`1items`,
IFNULL(b.`baseitem`,'Not Available') as `baseitem1`,
IFNULL(c.`baseitem`,'Not Available') as `baseitem2`,
DATE_FORMAT(a.`timestamp`,'%d %m %Y - %H:%i:%s') as `tradetime`
FROM `logs_client_trade` a
LEFT JOIN `items` b
ON REPLACE(a.`1items`,';','') = b.`id`
LEFT JOIN `items` c
ON REPLACE(a.`2items`,';','') = c.`id`
ORDER by a.`id` DESC
";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$item1 = rtrim($row['1items'],"; ");
$item2 = rtrim($row['2items'],"; ");
echo "<tr>\r\n";
echo " <td>" . $row['id'] . "</td>\r\n";
echo " <td>" . $row['1id'] . "</td>\r\n";
echo " <td>" . $row['2id'] . "</td>\r\n";
echo " <td>" . $row['baseitem1'] . "</td>\r\n";
echo " <td>" . $row['baseitem2'] . "</td>\r\n";
echo " <td>" . $row['tradetime'] . "</td>\r\n";
echo("</tr>\r\n");
}
?>

Create HTML table based on Database Values

I have a database that has information on actors, roles, and movies.
On an HTML page I have the user input the first name and last name of an actor.
This form is then submitted to my PHP page where I look through my database, and provide the user with a 3 column html table with the following information: Movie Name the actor has worked in, Role the actor played, and year of movie.
All these information are in separate database tables. Examples of what each table looks like is below:
actor table contains:
'id', 'first_name', 'last_name', and 'gender' stored in the following way - (933,'Actor','Name','M')
role table contains:
'actor_id', 'movie_id', 'role stored in the following way - (16844,10920,'Role')
movies table contains:
'id', 'name', 'year', 'rank' stored in the following way - (306032,'Snatch.',2000,7.9)
I have to look through and correlate all the data into a table. This is what I have so far:
$sql ="SELECT id, first_name, last_name FROM actors";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result)) {
if ($row['first_name'] == $firstname && $row['last_name'] == $lastname) {
$actorID = $row['id'];
echo "$actorID<br>";
}
}//end while
$sql2 = "SELECT actor_id, movie_id, role FROM roles";
$result2 = mysql_query($sql2);
while ($row=mysql_fetch_array($result2)) {
if ($row['actor_id'] == $actorID) {
$movieID = $row['movie_id'];
$actRole = $row['role'];
echo "$movieID <br>";
echo "$actRole <br>";
}
} //end while
$sql3 = "SELECT id, name, year FROM movies";
$result3 = mysql_query($sql3);
while ($row=mysql_fetch_array($result3)) {
if ($row['id'] == $movieID) {
$movieName = $row['name'];
$movieYear = $row['year'];
echo "$movieName <br>";
echo "$movieYear <br>";
}
} //end while
echo '
<table>
<thead>
<tr>
<th> Movie Name </th>
<th> Actor Role </th>
<th> Release Date </th>
</tr>
</thead>
<tbody>
<td>'. $movieName .'</td>
<td>'. $actRole. '</td>
<td>'. $movieYear. '</td>
</tbody>
</table>';
?>
My solution works -- just a mediocre way of doing it
You don't have assign the variables $firstname and $lastname. Apart from that your if condition is wrong true every time.
if ($row['first_name'] = $firstname && $row['last_name'] = $lastname) {
Should be:
if ($row['first_name'] == $firstname && $row['last_name'] == $lastname) {
Also check what you want to do with the echo $row['first_name'][0];
Note that mysql_* functions are deprecated so you better use mysqli or PDO.
EDIT:
You can select all actors that have play in a movie using the following query. You can adjust to take only the information you need changing SELECT clause or using WHERE.
$sql = "
SELECT aa.id AS actor_id, aa.first_name, aa.last_name, cc.name, cc.year
FROM actor AS aa
INNER JOIN role AS bb
ON aa.id = bb.actor_id
INNER JOIN movies AS cc
ON cc.id = bb.movie_id";
EDIT 2: (from comments)
You can use the following code:
$conn = mysqli_connect("localhost", "db_username", "your_password", "your_database");
$query = "
SELECT aa.id AS actor_id, aa.first_name, aa.last_name, cc.name AS movie_name, cc.year AS release_year
FROM actor AS aa
INNER JOIN role AS bb
ON aa.id = bb.actor_id
INNER JOIN movies AS cc
ON cc.id = bb.movie_id";
$result = mysqli_query($conn, $query);
echo '
<table>
<thead>
<tr>
<th>Actor id</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Movie name</th>
<th>Release date</th>
</tr>
</thead>
<tbody>';
while($row = mysqli_fetch_array($result)) {
echo '<td>'.$row['actor_id'].'</td>';
echo '<td>'.$row['first_name'].'</td>';
echo '<td>'.$row['last_name'].'</td>';
echo '<td>'.$row['movie_name'].'</td>';
echo '<td>'.$row['release_year'].'</td>';
}
echo '
</tbody>
</table>';

Categories