Score board php loop - php

I am fairly new to php so probably my question will sound simple for many, but here is my issue.
I have a table in MySQL holding scoreboard for users.
$connection = mysql_connect('localhost', 'root', '');
$select_db = mysql_select_db('score');
$sql = mysql_query("SELECT * FROM users ORDER BY >score");
function score_table() {
global $sql;
if ($sql) {
$rows_num = mysql_num_rows($sql);
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i <= $rows_num; $i++) {
echo $i;
}
echo $i.$row['name']." ".$row['score']."<br />\n";
}
}
}
the result im getting is :
123456Player1 3
123456Player2 400
123456Player3 784
123456Player4 1500
123456Player5 1642
So there is 5 players. Although firstly $i has 6 results and it is going through the entire loop for each player.
What i am trying to achieve is this:
1Player1 3
2Player2 400
3Player3 784
4Player4 1500
5Player5 1642
where first number is simply position. So whoever has less points is on the first place.

$connection = mysql_connect('localhost' ,'root', '');
$select_db = mysql_select_db('score');
$sql = mysql_query("SELECT * FROM users ORDER BY >score");
function score_table()
{
global $sql;
$i=1;
if($sql)
{
while($row = mysql_fetch_array($sql))
{
echo $i++ . $row['name'] . " " . $row['score'] . "<br />".PHP_EOL;
}
}
}

Related

Check if FK order is numbered correctly

I have some absences, and each absence has an FK to an employee, which I wanna display in a generated HTML table. However, if I delete an employee the order changes from 0, 1, 2 to 1, 2 (for example if the second employee got deleted).
This messed up my code, because I need the FK to check where I have to insert the leave (in which <tr>). Here I count the employees:
$result = mysql_query("select count(1) FROM employee");
$row = mysql_fetch_array($result);
$count_user = $row[0];
Later in my code I make a query in a loop. The loop runs as many times as there are users. And heres the problem: if an employee gets deleted it will not reach the other one ($i goes 0 and then 1 if there are 2 users, but if one is deleted the FK is 3, so it would need to go one further).
to
$result = mysql_query("select start, end, type_FK, employee_FK FROM absences where employee_FK = $i");
while ($row = mysql_fetch_assoc($result)) {
$array_absences[] = $row;
}
Has anyone an Idea that is not based on the FK order?
Also this topic needs a better title so feel free to edit it.
<html>
<head>
<title>Absence System</title>
</head>
<body>
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("absence_system", $con);
$result = mysql_query("select count(1) FROM employee");
$row = mysql_fetch_array($result);
$count_user = $row[0];
$result = mysql_query("select count(1) FROM absences");
$row = mysql_fetch_array($result);
$count_absences = $row[0];
$result = mysql_query("select name, surename, employee_ID FROM employee");
while ($row = mysql_fetch_assoc($result)) {
$array_user[] = $row;
}
for($i = 0; $i < $count_user; $i++){
echo '<table = border = 1px>';
echo '</tr>';
$result = mysql_query("select start, end, type_FK, employee_FK FROM absences where employee_FK = $i");
while ($row = mysql_fetch_assoc($result)) {
$array_absences[] = $row;
}
$count = count($array_absences);
echo $count;
print_r($array_absences);
for($j = 0; $j < 32; $j++){
$true = 0;
if($j == 0){
echo '<td>';
echo $array_user[$i]['name'], " ", $array_user[$i]['surename'] ;
echo '</td>';
}
for($k = 0; $k < $count; $k++)
{
$array_absences[$k]['start'] = substr($array_absences[$k]['start'], -2);
$array_absences[$k]['end'] = substr($array_absences[$k]['end'], -2);
$array_absences[$k]['start'] = ereg_replace("^0", "", $array_absences[$k]['start']);
$array_absences[$k]['end'] = ereg_replace("^0", "", $array_absences[$k]['end']);
if($j == $array_absences[$k]['start'] && $array_absences[$k]['employee_FK'] == $i){
$true = 1;
echo '<td>';
echo $array_absences[$k]['type_FK'];
echo '</td>';
}
}
if($j != 0 && $true == 0){
echo '<td>';
echo "$j";
echo '</td>';
}
}
echo '</tr>';
echo '</table>';
}
?>
</body>
</html>
If employee_ID corresponds to employee_FK, then you should not iterate over $count_user, but rather over $array_user - then your select would looke like this:
$result = mysql_query("select start, end, type_FK, employee_FK FROM absences where employee_FK = {$array_user[$i]['employee_ID']}");
while $i will still represent sequence number, because
$count_user == count($array_user)

PHP - Not echoing data from a MySQL database, but no errors?

So I have this PHP code:
Note: I do use mysqli_connect() further up.
$result = mysqli_query($con,"SELECT * FROM `smf_messages` WHERE `id_board` = 18");
if(!$result) {
echo "<center><p>Couldn't fetch news posts. Error code 2.</p></center>";
mysqli_close($con);
} else {
$posts = array();
$topicbdy = array();
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$posts[$row['id_topic']] = $row['id_topic'];
$topicbdy[$row['id_msg']] = $row['id_msg'];
}
$display = max($posts);
$display2 = min($topicbdy);
$qry = "SELECT * FROM `smf_messages` WHERE `id_board` = 18 AND `id_topic` = " . $display . " AND `id_msg` = " . $display2;
$result2 = mysqli_query($con,$qry);
//echo $qry;
if(!$result2) {
echo "<center><p>Couldn't fetch news posts. Error code 3.</p></center>";
} else {
while($show = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
echo "<center><h1>" . $show['subject'] . "</h1></center><br /><br />";
echo "<center>" . $show['body'] . "</center><br />";
}
}
mysqli_free_result($result);
mysqli_free_result($result2);
mysqli_close($con);
It's supposed to get the latest topic out of the database for my SMF-based forum from the news board, by getting the highest topic id, but the lowest post id. It seems to be doing the query just fine, as I don't get any errors, but it doesn't show the subject or body. What should I do?
Your $result variable is wrong for second query fetch. For your second query
while($show = mysqli_fetch_array($result,MYSQLI_ASSOC))
Should be
while($show = mysqli_fetch_array($result2,MYSQLI_ASSOC))
^

How to Speed Up PHP Script With Huge MySQL Database

I've been working on getting an RSS feed setup and with the help of some people here I got it done. However, I really need some advice from some of you more experienced coders to show me what needs to be changed to keep the same functionality but speed up the page load.
It looks 30 RSS items and gets the URLs from my MySQL database. The problem is that it randomly selects 30 rows out of over 100 million rows in that table. That is what it's supposed to do, but with their being so many rows in the table, it's really slowing down the script and I need help!
<?php header("Content-type: text/xml"); ?>
<?php echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; ?>
<?php include('directory/database.php'); ?>
<rss version="2.0">
<channel>
<title>Website Reviews</title>
<link>http://www.mywebsite.com</link>
<description>Professional Services</description>
<pubDate><?echo date('Y/m/d H:i:s');?></pubDate>
<?php
foreach( range( 1, 30 ) as $i ):
$number = mt_rand( 1, 141754641 );
$query="SELECT * FROM `list` LIMIT $number , 1";
$result = mysql_query($query);
if($result == false)
{
user_error("Query failed: " . mysql_error() . "<br />\n$query");
}
elseif(mysql_num_rows($result) == 0)
{
echo "<p>Sorry, we're updating this section of our website right now!</p>\n";
}
else
{
while($query_row = mysql_fetch_assoc($result))
{
foreach($query_row as $key => $domain)
{
echo "$value";
}
}
}
?>
<item>
<title><?php echo $domain; ?> REVIEW</title>
<pubDate><?echo date('Y/m/d H:i:s');?></pubDate>
<link>http://www.mywebsite.com/review/<?php echo $domain; ?></link>
<description>Looking for a review on <?php echo $domain; ?>? We've got it!</description>
</item>
<?php endforeach; ?>
</channel>
</rss>
Thanks in advance for any help that anyone can give!
Limit has to do table scans, so what you want to do is use indexes to your advantage. So first, let's add an autoincrement ID field to the table named "id".
Then,
<?php
$result = array();
$maxRow = mysql_fetch_assoc(mysql_query("SHOW TABLE STATUS LIKE 'list';"));
$max = $maxRow["Auto_increment"];
$minRow = mysql_fetch_assoc(mysql_query("SELECT id FROM 'list' LIMIT 1;"));
$min = $minRow["id"];
while (count($result) < 30) {
$ids = array();
while (count($ids) < 100) {
$id = mt_rand($min, $max);
$ids[$id] = 1;
}
$res = mysql_query("SELECT * from 'list' WHERE id IN (" . join(',', array_keys($ids)) . ") LIMIT 30");
while (($row = mysql_fetch_assoc($result)) && (count($result) < 30)) {
$result[] = array( ... ); // stuff results here
}
}
// output
?>
You can still select all 30 at once. It shouldn't be that slow to get 30 records.
$numbers=array();
foreach( range( 1, 30 ) as $i ):
$numbers[] = mt_rand( 1, 141754641 );
endforeach;
$query="SELECT * FROM `list` WHERE `whatever_primary_key_is` IN (".implode(',', $numbers).")";
May i suggest a more robust approach.
You have to take in account that the number you go look for may not exist
Only using one MySql query is often faster
Base on url1 and url2
You can have this php code instead :
<?php
// Connecting, selecting database
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password') or die('Could not connect: ' . mysql_error());
mysql_select_db('my_database') or die('Could not select database');
$query = "SELECT `url`
FROM `liste`
ORDER BY RAND()
LIMIT 30" ;
$result = mysql_query($query);
if($result == false)
{
user_error("Query failed: " . mysql_error() . "<br />\n$query");
}
elseif(mysql_num_rows($result) == 0)
{
echo "<p>Sorry, we're updating this section of our website right now!</p>\n";
}
else
{ $query_row = array();
while($query_row = mysql_fetch_assoc($result))
{
echo $query_row['url']; // no need to do the extra foreach
}
}
?>
The values mysql_host,mysql_user,mysql_password,my_database should be replaced by your connection.
As long as you have 30 row in your title table your are ok.

Out of memory, Mysql_query() unable to save resultset

I try to load about 30.000 record to mysql select. than i get this warning.
and than i try to break them into smaller limit. Every 1000. but why i still get this warning?
this is my code :
function processDataDb()
{
$rowIncrement = 1000;
$query = "SELECT count( * ) as totalfield FROM `isc_xml_data` ";
$result = mysql_query($query) or die ("$query" . mysql_error());
if ($result)
{
$row = mysql_fetch_assoc($result);
$total_row = $row['totalfield'];
for($i = 0; $i < $total_row ; $i+=$rowIncrement)
{
$sql_c = "SELECT * FROM isc_xml_data order by id LIMIT " . $i . " , " . ($i + $rowIncrement - 1);
$res_c = mysql_query($sql_c) or die (mysql_error());
while($row = mysql_fetch_object($res_c))
{
echo $row->id."\n";
$this->insertAndUpdateProduct($row->xmldata);
}
unset($res_c);
}
} else {
echo "result is unavailable";
}
}
Thanks for any help.
$sql_c = "SELECT * FROM isc_xml_data order by id LIMIT " .
$i . " , " . ($i + $rowIncrement - 1);
http://dev.mysql.com/doc/refman/5.0/en/select.html#id714605
The second argument to LIMIT is how many you want, not the upper bound; try just $rowIncrement.
unset($res_c); It's not valid, there is mysql_free_result($res_c) function for this.
Also, you can do it without first query with count(*) - just make your cycle queries until at least one row returned.
Because of this line:
$this->insertAndUpdateProduct($row->xmldata);
it's your XML processing being very inefficient memory-wise,
while mysql consumes no more than only one row contents.

Leaderboard from mySQL

How could I add a number starting from 1 to show the leader by total games in this script?
<?php
$result = mysql_query("SELECT gamertag, tgames FROM leader ORDER BY tgames DESC");
while ($row = mysql_fetch_assoc($result)) {
echo "number? ".$row['gamertag']." ".$row['tgames']."<br>\n";
}
?>
You could simply add a variable that increases each time.
<?php
$result = mysql_query("SELECT gamertag, tgames FROM leader ORDER BY tgames DESC");
$index = 1;
while ($row = mysql_fetch_assoc($result)) {
echo $index++ . " " . $row['gamertag'] . " " . $row['tgames'] . "<br>\n";
}
?>
(...)
$i = 1;
while($row = mysql_fetch_assoc($result)) {
echo $i . " " .$row['gamertag']." ".$row['tgames']."<br>\n";
$i++;
}

Categories