i need to display mysql table rows one at a time for this i am using in php:
$result = mysqli_query($con,"select * from table limit 0,1");
while($row = mysqli_fetch_array($result)) {
echo "First Name:" . $row['First'] . " " . "Last Name:" . $row['Last'];
echo "<br>";
}
I need to display one row at a time, but display every new row on every php executinon, like first user gets to see first "firstname, lastname" second anonymous user on executing the page gets to see second "firstname, lastname" from the database.
this gives an error :
$result = mysqli_query($con,"select * from voucher limit '$count',1");
(i included $count to the parameters)
On execution it just displays the first row every time. I need modification to it that whenever the code is executed it returns a new row value. For example, first time it will output first row, on seond execution of the script it outputs second row and so on..
i am using php5, mysql on ubuntu server.
Please help.
You can do it in two ways :
The first one is to save the increment value somewhere. I dont know how do you pass it or when and how you exsecute it, but it they run run separately each time (e.g. runs via a cron job or terminal), you can save the value in a simple file or memchache.
First way :
$offset = file_get_contents('my_counter.txt');
$offset++;
$result = mysqli_query($con,"select * from table limit " . (int) $offset . ",1");
file_put_contents('my_counter.txt', $offset);
The next one is to save the the last id from your row:
$lastID = file_get_contents('my_counter.txt');
if($lastID == "") // First call and no last id
$lastID = 0;
$result = mysqli_query($con,"select * from table WHERE ID > " . (int) $lastID . " limit 0,1");
while($row = mysqli_fetch_array($result)) {
echo "First Name:" . $row['First'] . " " . "Last Name:" . $row['Last'];
$lastID = $row['ID']; // Your autoincrement row
}
file_put_contents('my_counter.txt', $lastID);
I hope I understood your question right and this helps you.
Since you want the data to be retrived when php code runs, you need to count the loop inside your code and increment the value like below.
If you want to loop, you need to increment the 0 in LIMIT 0,1
Something like this in a loop
LIMIT " . $loopcount . ",1
LIMIT " . $loopcount . ",1
LIMIT " . $loopcount . ",1
Im not a php programmer so i dont know the exact code.
You could if you just need a random and not the next, use SELECT * FROM table ORDER BY RAND() LIMIT 1.
This just gives a random record, and you wont go outside of the table as it always selects one record from the table.
It will affect your performance a bit if you have a big table. But you will always get a record. If you just loop LIMIT " . $loopcount . ",1 you run the chance of trying to select outside of the table scope. If you have 100 rows, and you try LIMIT 101,1 you will get a empty recordset.
Try this
$result = mysqli_query($con,"select * from table ORDER BY RAND() LIMIT 1");
while($row = mysqli_fetch_array($result)) {
echo "First Name:" . $row['First'] . " " . "Last Name:" . $row['Last'];
echo "<br>";
}
Related
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
I am trying to print out a users name and totalspent value in ascending order of totalspent. I.e, user that has spent the most will be outputed first then the next highest spender etc.
This is my current code, however, this only seems to output a single table row an infinite amount of times.
$query = "SELECT * FROM (
SELECT * FROM `members` ORDER BY `totalspent` DESC LIMIT 10) tmp order by tmp.totalspent asc";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo $row['name'] . " - $" . $row['totalspent'] . "<br/>";
}
select member_name, totalspent from tmp order by totalspent desc;
still can you show snippet of your table and snippet of answer you desire
The best way I can prefer for you to join two tables. The code should like follows-
$query = "SELECT * FROM temp.tmp, mem.members WHERE temp.totalspend = mem.totalspend ORDER by temp.totalspend ASC";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo $row['name'] . " - $" . $row['totalspent'] . "<br/>";
}
I believe, it will work for your smoothly... TQ
I don't understand how to display the first three rows (this number is an example limit) of a mysql database table with php code. I know how to use LIMIT, but in this case it seems not to work. Here is the code:
include("common.php");
$link=dbConnect();
$limit = safe($_POST['limit']);
$i = 1;
$query = mysql_query("SELECT * FROM $dbName . `scores` ORDER by `score` DESC LIMIT $limit");
while($row = mysql_fetch_array($query))
{
echo $i . "\t° \t " . $row['name'] . "\t - \t " . $row['score'] . "\n";
$i += 1;
}
This code produces an output like this: view image.
So it shows all the rows of the db table and not only the first three for example...
Thanks to everyone who will help me!
echo the text: "SELECT * FROM $dbName . scores ORDER by score DESC LIMIT $limit"
See what output it gives is the limit / dbName what you expect it to be
If you don't see what is wrong run the query in for example phpMyAdmin sql section see what errors you get in return.
Check two things $_POST['limit'] value and then $limit value. safe function may make it something different.
That's the function which I'm using to print the contents of 'username' table:
function showtable()
{
ob_start();
$db = new PDO("sqlite:test.db");
$query = "SELECT * FROM " . $_SESSION['username'] . " ORDER BY `a` DESC;";
$result = $db->prepare($query);
$result = $db->query($query);
print "<table>";
print "<tr><td>First Column</td><td>Second Column</td><td>Third column</td></tr>";
foreach ($result as $row)
{
print "<tr><td>" . $row['a'] . "</td><td>" . $row['b'] . "</td><td>Here stays the button</td></tr>";
}
print "</table>";
unset($db);
ob_end_flush();
}
So, how should look a function so when creating each row of the html table, a button for updating the corresponding sqlite table row is inserted in the third cell (named 'Here stays the button' for easier reading)? I'm calling my function when opening the test.php (with added required_once('functions.php')) file in main browser window, nothing special in that.
That's the UPDATE query:
$query = "UPDATE " . $_SESSION['username'] . " SET `c` = '1'" . " WHERE `a` = " . $row['a'] . ";";
a column is integer primary key
b column is text
c column is integer, all fields hold 0 value
P.S. Don't talk about AJAX, I'm not ready for it (and don't like it, a lot of pages that use AJAX lag the browser). Just asking for ideas about a simple php function, that adds UPDATE TABLE functionality through buttons for each row.
Thanks in advance :)
What is the updating for? what will happen if C = 1?
anyway for your question, my suggestion is to use an anchor tag.
i.e
in the "Here stays the button" will be Update
in your test.php
if($_GET['a_new'] != '')
{
$query = "UPDATE " . $_SESSION['username'] . " SET `c` = '1'" . " WHERE `a` = ".$_GET['a_new']."";
}
p.s you have excess ";" in your query. you only add the query on the end of the query statement not inside it i.e $sql = "select * from"; not $sql = "select * from;";
I have a MySQL database called "bookfeather" with several tables that contain list books. Under each table, each book has a given number of votes. The PHP code below allows the user to enter in a book title ($entry), and then returns the total number of votes that book has in all tables ($sum).
How could I use PHP to make a 2-column, 25-row table that lists the 25 books in the database with the highest value for $sum (in descending order)?
Thanks in advance,
John
mysql_connect("mysqlv10", "username", "password") or die(mysql_error());
mysql_select_db("bookfeather") or die(mysql_error());
// We preform a bit of filtering
$entry = strip_tags($entry);
$entry = trim ($entry);
$entry = mysql_real_escape_string($entry);
$result = mysql_query("SHOW TABLES FROM bookfeather")
or die(mysql_error());
$table_list = array();
while(list($table)= mysql_fetch_row($result))
{
$sqlA = "SELECT COUNT(*) FROM `$table` WHERE `site` LIKE '$entry'";
$resA = mysql_query($sqlA) or die("$sqlA:".mysql_error());
list($isThere) = mysql_fetch_row($resA);
$isThere = intval($isThere);
if ($isThere)
{
$table_list[] = $table;
}
}
//$r=mysql_query("SELECT * , votes_up - votes_down AS effective_vote FROM `$table[0]` ORDER BY effective_vote DESC");
if(mysql_num_rows($resA)>0){
foreach ($table_list as $table) {
$sql = "SELECT votes_up FROM `$table` WHERE `site` LIKE '$entry'";
$sql1 = mysql_query($sql) or die("$sql:".mysql_error());
while ($row = mysql_fetch_assoc($sql1)) {
$votes[$table] = $row['votes_up'];
$sum += $row['votes_up'];
//echo $table . ': "' . $row['votes_up'] . " for $entry from $table\"<br />";
}
}
}
else{
print "<p class=\"topic2\">the book \"$entry\" has not been added to any category</p>\n";
}
//within your loop over the DB rows
//$votes[$table] = $row['votes_up'];
//afterwards
if($sum>0){
print "<table class=\"navbarb\">\n";
print "<tr>";
print "<td class='sitenameb'>".'<a type="amzn" category="books" class="links2b">'.$entry.'</a>'."</td>";
print "</tr>\n";
print "</table>\n";
//echo "<p class=\"topic3\">".''.$entry.''. "</p>\n";
echo "<p class=\"topic4\">". number_format($sum) . ' votes in total.'."</p>\n";
Try something like this. All of this hasn't been tested so please add comments for changes. I'll work with you to get the code right.
// After getting your array of tables formated like
$tableArray = array("`tableA`", "`tableB`", "`tableC`");
// create a table statement
$tableStatement = implode(", ", $tableArray);
// create a join statement
$joinStatement = "";
for ($i = 1; $i < count($tableArray); $i++) {
if ($joinStatement != "")
$joinStatement .= " AND ";
$joinStatement .= $tableArray[0] . ".site = " . $tableArray[$i] . ".site"
}
$firstTable = $tableArray[0];
$sql = "SELECT SUM(votes_up) FROM " . $tableStatement . " WHERE " . $joinStatement . " AND " . $firstTable . ".site LIKE '" . $entry . "' GROUP BY " . $firstTable . ".site ORDER BY SUM(votes_up) DESC";
Edit --------
I now realize that the query above won't work perfectly because votes_up will be ambiguous. Also because you probably want to be doing joins that grab records that are only in one table. I think the concept is the right direction even though the query may not be perfect.
You can do something like
$selectStatement = "SUM(tableA.votes_up) + SUM(tableB.votes_up) as total_votes_up"
I did something like this recently. In your database, you'll have to rename each field to a corresponding book name.php like (TaleofTwoCities.php). Now on your page that will display the vote results, you'll need to include some php files that will drive the database query on each load. I called mine "engine1.php" and "engine2.php." These will do all your sorting for you.
$query1 = mysql_fetch_row(mysql_query("SELECT url FROM pages ORDER BY counter DESC
LIMIT 0,1"));
$query2 = mysql_fetch_row(mysql_query("SELECT url FROM pages ORDER BY counter DESC
LIMIT 1,1"));
$query3 = mysql_fetch_row(mysql_query("SELECT url FROM pages ORDER BY counter DESC
LIMIT 2,1"));
and so on.. then..
$num1 = "$query1[0]";
$num2 = "$query2[0]";
$num3 = "$query3[0]";
That part sorts your listings by the number of votes from highest to lowest, with url, in your case, being the name of the books(remember you want it to end in .php - you'll see why in a second), and counter being the field that logs your votes.
Make your second engine.php file and add something like this:
$vquery1 = mysql_fetch_row(mysql_query("SELECT counter FROM pages WHERE
url='book1.php'"));
$vquery2 = mysql_fetch_row(mysql_query("SELECT counter FROM pages WHERE
url='book2.php'"));
$vnum1 = "$vquery1[0]";
$vnum2 = "$vquery2[0]";
and so on... Until you get to 25 for both this and engine 1.
Now, in your results page, after you put in the require_once(engine.php) and require_once(engine2.php) at the start of your body, start an HTML table. You only want two columns, so it'll be something like..
<table border=1 cellspacing=0 cellpadding=0>
<tr>
<?php include $num1; ?>
</tr>
<tr>
<?php include $num2; ?>
</tr>
And so on... By naming your field with "book1.php" and including the engines, $num1 will change to a different .php file depending on votes from high to low. Now all you have to do is make small php files for each book like so - no headers or anything because you're inserting it into the middle of html code already:
<td style="width:650px;"><center><img src="images/book1.jpg" alt="" border="none"
/></a></center></td>
<td style="width:150px;">Votes: <?php echo $vnum1;?></td>
And there you have it. A code that will dynamically give you results from high to low depending on the number of votes each book has.