Last entry in a PHP database ID colum (primary key) [duplicate] - php

This question already has answers here:
Most efficient way to get table row count
(12 answers)
Closed 8 years ago.
How can I get the highest number in my ID column?
With MySQL I have the connection part done I just need to know how I can display that number using PHP. I got some of my code from a friend:
<?php
$con = mysql_connect("quollcraft.net", "quollcr1_forum", "pw");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("quollcr1_hub", $con);
$result = mysql_query("SELECT * FROM recentplayers ORDER BY id DESC LIMIT 28");
echo "<table>";
while ($row = mysql_fetch_array($result))
echo "<td>";
echo "<center>";
echo '<img class="avatar" src="http://cravatar.eu/avatar/' . $row ['name'] . '/40.png" rel="tooltip" style="display: inline-block" title="' . $row ['name'] . '">';
echo "</td>";
echo "</table>";
mysql_close($con);
?>
<?php
$con = mysql_connect("quollcraft.net", "quollcr1_forum", "pw");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("quollcr1_hub", $con);
$result = mysql_query("SELECT * FROM id ORDER BY id DESC LIMIT 1");
echo "<table>";
while ($row = mysql_fetch_array($result))
echo "<td>";
echo "<center>";
echo "<p>' . $row ['id'] . 'hello</p>";
echo "</td>";
echo "</table>";
mysql_close($con);
?>`
Its supposed to show my latest players then the total players i have.

You can use the aggregate function MAX() to find the maximum value in a column:
SELECT MAX(ID) as ID
FROM TableName

If you want the full row with the highest id not only the id, this would give you that
SELECT * FROM table ORDER BY id DESC LIMIT 1
If you want the id as the only value you can do
SELECT MAX(id) as id FROM table
If you want the total amount of rows in the table, to figure out how many players you have you can do
SELECT COUNT(id) as total_players FROM table

SELECT MAX(YOUR COLUMN) FROM YOUR TABLE

MySQL query should look like this
SELECT id FROM table ORDER BY id DESC LIMIT 1
The solution with MAX may not be the best one when you have multiple records in database.
I don't know how you connect to your MySQL in PHP so it depends how you will display those max id in PHP

You can also use this:
SELECT id FROM YOUR_TABLE WHERE id = LAST_INSERT_ID();

Related

How can I display rank to leaderboard from score

I'm trying to create a leaderboard using a score table from Mysql.
I only use "name" and "score" from my score table.
I can display my leaderboard ordered by best score but can't display the rank with it.
Here is my php file to get datas:
// Connect to server and select database.
$con = mysqli_connect($host, $db_username, $db_password, $db_name);
// Retrieve data from database
$sql = "SELECT *
FROM scores
ORDER BY score DESC
LIMIT 10"; // The 'LIMIT 10' part will only read 10 scores. Feel free to change this value
$result = mysqli_query($con, $sql);
// Start looping rows in mysql database.
while($rows = mysqli_fetch_array($result)){
echo $rows['name'] . "|" . $rows['score'] . "|";
// close while loop
}
// close MySQL connection
mysqli_close($con);
?>
I guess I probably need to have something like this in the end:
while($rows = mysqli_fetch_array($result)){
echo $rows['rank'] . "|" . $rows['name'] . "|" . $rows['score'] . "|";
But can't manage to get it properly…
The result should be displayed like:
<br/> Mardoch 49507
<br/> Gunthylapointe 49504
What am I doing wrong?
Do you want window functions?
select rank() over(order by score desc) rn, s.*
from scores
order by score desc
This adds another column to the resultset, called rn, that contains the rank of each row, ordered by descending score.
Well, I change a bit my code and added this:
// Retrieve data from database
$sql = "SELECT *
FROM scores
ORDER BY score DESC";
//LIMIT 10"; // The 'LIMIT 10' part will only read 10 scores. Feel free to change this value
$result = mysqli_query($con, $sql);
$i = 0;
// Start looping rows in mysql database.
while($rows = mysqli_fetch_array($result)){
$i++;
echo ($i) . "|" . $rows['name'] . "|" . $rows['score'] . "|";
// close while loop
}
It's work a bit better but it stop my leaderboard at a moment and display a lot of 0 after:
screen capture
Seems the problem is because the next score is exactly the same as the previous…So it breaks here

mysql_fetch_array how to display a single value of a column

I have the query fetching 8 rows, I want to be able access the result by single column not the whole row. For example I want to display the Deviceid from row number 7. i can display all of the values of the column but I'm having trouble figuring out how to get just one value. I'm new to PHP so bear with me and thank you for any help.
This the code:
<?php
$con = mysql_connect("uimcswpro", "testmysql", "test123") or die('Could not connect to server');
mysql_select_db("storage", $con) or die('Sorry, could not connect to the database');
$query = "Select distinct a.Deviceid as Deviceid, c.Time as Time, b.devicehostname as devicehostname, ElementName, PoolID,
TotalManagedSpace, RemainingManagedSpace,
TotalDiskCapacity, HotspareCapacity, UnassignedStorageCapacity,
AssignedStorageCapacity
from tt_cim_storage_pool a, devices b, ent_san_storage_current c
where a.Deviceid = b.Deviceid
and (type = 'Unified Pool' or type = 'RAID Group' or type is NULL)
and c.time = (select max(c.Time) from tt_cim_storage_pool where deviceid=
(select deviceid from devices where devicehostname='UIH_8100_L14' and retire=0))
and devicehostname='UIH_8100_L14';";
$result = mysql_query($query,$con);
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
echo "<br/>";
while ($row=mysql_fetch_array($result)) {
echo $row[0]. " - ".$row[1]. " - ".$row['devicehostname']. " - ".$row['ElementName']. " - ".$row['PoolID']
. " - ".$row['TotalDiskCapacity'];
echo "<br/>";
}
mysql_close($con);
?>
You can select desired row via sql using LIMIT keyword, or simple checking number of current row:
$rowNo = 0;
while ($row=mysql_fetch_array($result)) {
$rowNo++;
if ($rowNo == 7) {
echo $row[0]. " - ".$row[1]. " - ".$row['devicehostname']. " - ".$row['ElementName']. " - ".$row['PoolID']
. " - ".$row['TotalDiskCapacity'];
echo "<br/>";
}
}
You should also consider using modern database interface like mysqli

Output distinct values in SQL column with PHP

I have a table with two collumns (shortened), NAME and CATEGORY.
I want to output the number of distinct categorys. For an examle: Sport : 5 , Houses : 10.
I use this one:
$test = mysqli_query($con,"SELECT category, COUNT(category) as count FROM tablename GROUP BY category ORDER BY count DESC");
This work then I run the code in SQL Shell, but I have no clue on how to output it in PHP. I have searced Google up and down without any successfull solution.
Any help?
I want to output it in a table format.
EDIT: Here is my full code: (tablename is changed, and $con is removed)
$test = mysqli_query($con,"SELECT DISTINCT lkategori, COUNT(lkategori) as count FROM tablename GROUP BY lkategori ORDER BY count DESC");
while($row = mysql_fetch_array($test)) {
echo $row['lkategori'] . ":" . $row['count'];
die("test");
}
$test = mysqli_query($con,"SELECT DISTINCT lkategori, COUNT(lkategori) as count FROM tablename GROUP BY lkategori ORDER BY count DESC");
echo "<table border='1'>";
while($row = mysqli_fetch_array($test)) {
echo "<tr>";
echo "<td>" . $row['lkategori'] . "</td>";
echo "<td>" . $row['count'] . "</td>";
echo "</tr>";
}
echo "</table>";
This will output all the categories and the count returned by the sql statement into a table. Also as a sidenote you should look into PDO.
EDIT: to make sure you do get the distinct values you should use the DISTINCT keyword in your sql statement:
$test = mysqli_query($con,"SELECT DISTINCT category, COUNT(category) as count FROM tablename GROUP BY category ORDER BY count DESC");
use this
while($row = mysqli_fetch_array($test)) {
echo $row['lkategori'] . ":" . $row['count'];
die("test");
}
Thanks

How to make a php dynamic table showing only the last 20 values from MySQL?

I have made a php table that displays data from MySQL table. This is working perfectly. However, the MySQL table keeps getting updated and so my php table gets really long and big. I just want to keep it short, so I just want it to display the last 20 items on the table if possible.
Also the table doesn't update dynamically, to see the new updates you have to keep refreshing the page and I would like it if it could keep updating on its own.
Here is the page of how the (long) table looks.
Here is my php code as of now:
<?php
$con = mysql_connect("$host","$username","$pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("$db_name", $con); //database name
$result = mysql_query("SELECT * FROM $db_table"); //table
echo "<table cellpadding='0' cellspacing='0' class='ver-minimalist'>
<tr>
<th>Photoresistor</th>
<th>Accelerometer</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Photoresistor'] . "</td>";
echo "<td>" . $row['Accelerometer'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
I know I'm going to have to make a loop but I'm not sure which one would be the best option. Please, I would really appreciate the help.
The MySQL table does have an ID -primary key if that helps.
Make your query this:
SELECT * FROM $db_table ORDER BY id DESC LIMIT 20
Limit allows you to limit the amount of results you get from a query. By sorting by ID you can get the last 20 results in your table.

How to add up votes in a table and display it on screen

i have a php code which selects and shows data from my 'elections' table. i have another table called 'votes' which contains all the votes by users. how do i select the two tables and show the party that has had the most votes? so if labour had 5 votes for example and lib dems had 3 votes, how would i show on screen that 'labour has won this election with __ votes? my php is as follows:
<?php
$id = $_GET['election'];
$result = mysql_query("SELECT election_id, name_of_election, date, month, year FROM elections WHERE election_id = '$id'")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo '<hr><h3>There Aren\'t Any Elections Setup Yet</h3><hr> ';
} else {
echo '<hr><h3>Vote Count</h3><hr>';
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name_of_election']. "</td>";
echo "<br/><br/><td>" . $info['date']. ' '. $info['month']. ' ' . $info['year']. "</td>";
echo "<br/><br/><td>" . '<hr>' . "</td>";
}
}
echo "</tr>";
echo "</table>";
?>
my database table consists of the following fields:
(dont ask about the date fields)
elections: election_id, name_of_election, date, month, year, party1, party2, party3, status
votes: vote_id, election_id, ni, party
any ideas?
This will give you the party and count for selected election in descending order of count:
$result = mysql_query(
sprintf("
SELECT votes.party, COUNT(votes.vote_id)
FROM votes
WHERE election_id = %d
GROUP BY election_id, votes.party
ORDER BY COUNT(votes.vote_id) DESC",
mysql_real_escape_string($id)
)
);
Edit: To display the first row (which will be the party with the most votes):
list($party, $votes) = mysql_fetch_row($result);
echo '<p>'.$party.' won with '.$votes.'</p>';

Categories