im new on php programming and i've searched the function that i need but didn't found it.
here what exactly i want to do :
i want to select 2 columns from a table
set the order by descending by 1 column that is numeric
and then show in php the first 100 rows that were selected
Here is my code right now php shows all the columns i want it to show the first 100
$result = mysqli_query($con,"SELECT pvpkills,char_name FROM characters ORDER BY pvpkills DESC");
while($row = mysqli_fetch_array($result))
{
echo $row['pvpkills'] . "  " . $row['char_name'];
echo "<br>";
}
SELECT pvpkills,char_name FROM characters ORDER BY pvpkills DESC LIMIT 0,100
Related
This question already has answers here:
PHP: echo number of duplicates in a table by most common
(4 answers)
Closed 4 years ago.
I have a database table of events. Each event has a place assigned to it. I want to display a numbered list of the 10 most used places. I would like to see it in the following format:
eventplace1 (place count)
eventplace2 (place count)
And so on.
Using PHP 7.2.12 and MySQL 5.6, and a beginner in php coding...
I figured out a code (the $query below) that gives the list I want in phpMyAdmin, but I want to use it in a widget on my WordPress homepage.
I know there is a SELECT TOP 10 which in theory should do what I am looking for, but it doesn't seem to work...
<?php
require_once(ABSPATH . 'wp-settings.php');
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysqli_select_db($connection, DB_NAME);
$query = "SELECT count(*), eventplace FROM tng_events GROUP BY eventplace HAVING COUNT(*) > 1 ORDER BY count(*) DESC LIMIT 10";
$result = mysqli_query($connection, $query);
?>
When I do echo $result[0]; I just get the total count of all places.
When I do echo $result[1]; I get nothing, just an empty space.
When I use
SELECT count(), eventplace FROM tng_events GROUP BY eventplace HAVING COUNT() > 1 ORDER BY count(*) DESC LIMIT 10
in phpMyAdmin it gives a table with 10 places and their respective count number.
I want the output to be the same content as in phpMyAdmin, but in a slightly different form (see above). I suppose I need to create two variables ($), one containing the eventplace name, the other containing the count, but I'm not sure how to do that. Then the output would probably be something like:
echo < ol >< li >$eventplace ($placecount)< /li >< /ol >
(without the spaces)
Using the foreach loop, you can iterate through the results and echo each element inside the loop as shown below.
$query = "SELECT count(*) as count , eventplace FROM tng_events GROUP BY eventplace HAVING COUNT(*) > 1 ORDER BY count(*) DESC LIMIT 10";
$result = mysqli_query($connection, $query);
"<ol>";
foreach ($result as $row){
echo "<li>" .$row['eventplace']. ' ('. $row['count']. ')'. "</li>";
}
"</ol>";
I'm having a little trouble with my rand() function. I have the following query:
$listTrainers = mysqli_query($conn, "SELECT emp_id FROM employees;");
while($fetchTrainers = mysqli_fetch_row($listTrainers))
{
echo 'ID: ' . $fetchTrainers['0']. '<br>';
}
This query returns me the id of all employees in the database, is there a way I can randomly select one of these id's and store it in a variable?
I am trying to use the following function:
echo(rand(begin, end));
where begin is the first element from the query and end is the last element
add this to your query:
ORDER BY RAND() LIMIT 1
You can do so within your query easily
SELECT emp_id FROM employees ORDER BY RAND() LIMIT 1
The easiest way is to do this directly in the database, to avoid getting all IDs if you only need one:
SELECT
emp_id
FROM
employees
ORDER BY
RAND()
LIMIT
1
If you do need all IDs, but additionally want to pick a random one, use this to avoid querying the database twice:
$listTrainers = mysqli_query($conn, "SELECT emp_id FROM employees;");
while($fetchTrainers = mysqli_fetch_row($listTrainers))
{
$id = $fetchTrainers[0];
echo 'ID: ' . $id . '<br>';
$ids[] = $id;
}
$randomId = $ids[array_rand($ids)];
I know there are libraries etc that I could use to get this sorted but Im almost there with my code.
A little about the code and what it's trying to do. I have a mysql table where there are various news articles and grouped in categories of news.
I have managed to get a forward button working. So it looks for the next news article that is in the same category. This works and the code is below.
//Gets the next story from the same story type in line.
$query= "SELECT * FROM news WHERE storytype2 = '$storytype2' AND id > '$currentid'";
$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
$row = mysql_fetch_array($result);
$num_results = mysql_num_rows($result);
if ($num_results > 0){
echo "<td width=\"20%\"align=\"right\"><img title=\"Next News\" src=\"webImg/forwardarrow.png\"/></td></tr>";
}else{
echo "<td width=\"20%\"align=\"right\"></td></tr>";
}
//End of the next button
However, when I try do the same for the previous button. All I ever seem to get back is the first id of that category regardless of where my iteration is. For example, if I am on news article 10 and try to go to previous one which say has an id of 7 it will automatically show the first news article within that category, say id 4.
Below is the code.
//Gets the next story from the same story type in line.
$query= "SELECT * FROM news WHERE storytype2 = '$storytype2' AND id < '$currentid'";
$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
$row = mysql_fetch_array($result);
$num_results = mysql_num_rows($result);
if ($num_results > 0){
echo "<td width=\"20%\"align=\"left\"><img title=\"Previous News\" src=\"webImg/backarrow.png\"/></td>";
}else{
echo "<td width=\"20%\"align=\"left\"></td>";
}
//End of the next button
What have I done wrong?
Thanks
Neither of your queries is correct. Your "Next" code selects any row whose ID is higher than the current, not necessarily the next one; if you get the next one, it's just by accident.
You should use ORDER BY and LIMIT to control which row is selected:
Next:
SELECT *
FROM news
WHERE storytype2 = '$storytype2' AND id > '$currentid'
ORDER BY id
LIMIT 1
Previous:
SELECT *
FROM news
WHERE storytype2 = '$storytype2' AND id < '$currentid'
ORDER BY id DESC
LIMIT 1
Without any further information, I don't think you can assume that the first row of your queries will be the ID you're looking for. Ordering by ID first will probably solve your problem; you can also limit your query to one row, since it's the only one you're looking at. Something like the following would probably solve your problem (where x is $storytype2 and y is $currentid:
SELECT * FROM news
WHERE storytype2 = x
AND id < y
ORDER BY id DESC /* <-- THIS */
LIMIT 1
Use ORDER BY id ASC for the other case.
Note that the MySQL family of PHP is deprecated and support thereof will disappear, if it hasn't yet. Please look into PDO or MySQLi.
Note also that you are inserting a variable into SQL code directly, which is never a good idea. I hope you have some good input checks on your variables.
Let's look at the PDO way to get the previous article ID:
$dbh = new PDO(..);
// Use ? where dynamic input will come
$sql = $dbh->prepare('SELECT * FROM news
WHERE storytype2 = ?
AND id < ?
ORDER BY id DESC
LIMIT 1');
// Fill the ? safely with PDO's execute function
$sql->execute(array($storytype2, $currentid));
$result = $sql->fetch(PDO::FETCH_ASSOC);
if($result && isset($result['id'])) {
// Process previous ID
}
Is it possible to limit the results shown from a MYSQL database?
At the moment the results are shown in a html table, how do I only show the newest entries?
<?php
$con = mysql_connect("localhost","cl49-XXX","XXX");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("cl49-XXX", $con)or die("Unable to select database");
$result=mysql_query("SELECT * FROM products") or die('You need enter a category');
echo "<tr>"; // first row beginning
for ($i = 1; $i <= mysql_num_rows($result); $i++)
{
$row = mysql_fetch_array($result);
$prodname = $row['prodname'];
$prodID = $row['prodID'];
$catagory = $row['catagory'];
echo "
<td>$prodID</td>
<td>$prodname</td>
<td>$catagory</td>
<td>
<a href=deleteproduct.php?q=$prodID' class='btn mini red'>
<i class='icon-trash'></i> Delete Item</a>
</td>";
echo "</tr><tr>"; // it's time no move to next row
}
echo "</tr>"; // last row ending
?>
Just switch your query to something like this!
$result=mysql_query("SELECT * FROM products LIMIT 0,10")or die('You need enter a catagory' );
LIMIT 0,10 will show the first 10 results from your DB.
You could even order it by a specific element in your DB.
$result=mysql_query("SELECT * FROM products ORDER BY objectName LIMIT 0,10")or die('You need enter a catagory' );
For further SQL basic help: http://www.sqlcommands.net/
Good luck!
Your question Consists of two parts.
First part: Is it possible to limit the results shown from a MYSQL database?
you can do that by using limitword inside the query.
Example:
mysql_query("SELECT * FROM products limit 1, 5");
The previous code say select all products and start from the product one and show me 5 products only.
Second part: how do I only show the newest entries ?
You can do that by, must first create column called date to your products table, then when add new product, store the time by using time() function into date column.
Then when you want to show the products order by newest products, you can use order by sentence.
Example:
mysql_query("SELECT * FROM products order by date ASC limit 1, 5");
To apply these words on your code, only need to
Add new column in your products table and call it date.
Then change the query that adds the products to products table to add also
the time to the date column by using time() function.
INSERT INTO tableName(date) VALUES('".time()."');
Show the products sorted order by newest by modify the query to
$result=mysql_query("SELECT * FROM products ORDER BY date ASC LIMIT 0, 15") or die('You need enter a category');
First of all, while you're still new, you should look into PDO/Prepared statements instead of mysql_ functions.
Also, you can do this for your SQL:
$result=mysql_query("SELECT * FROM products ORDER BY name DESC LIMIT 0,10")or die('You need enter a catagory ' );
'name' being the name of your products/row name you wish to sort it by
just add a counter and when the counter hits a number use:
break;
to jump out the loop.
for example
for ($i = 1; $i <= mysql_num_rows($result); $i++)
{
if ($i==3) break;
}
Of course you could better limit the loop itself:
use:
for ($i = 1; $i <= 4; $i++)
or use the LIMIT option in the SQL-query
I have a simple mysql select query in my PHP code:
$result = mysql_query("SELECT text FROM example ORDER BY rank DESC");
while($row = mysql_fetch_array($result))
{
echo $row['text'] . "<br>";
}
and this MySql table:
text | rank
--------+--------
google | 245
--------+--------
yahoo | 32
--------+--------
bing | 12
When I get the results from the query, something like this gets displayed:
yahoo
google
bing
I want Google to be in front. I guess Yahoo is in first because it starts with "3".
How could I make the query order the results by the size of the numbers in rank?
Thanks...
I'm guessing the rank field is some kind of string type. Make it a numeric type int and it will order properly
The correct solution, of course, is to use the correct data type. As a workaround you could cast the data to number on the fly:
SELECT text FROM example ORDER BY rank + 0 DESC
or:
SELECT text FROM example ORDER BY cast(rank as unsigned) DESC
What's the data type of rank in your SQL schema? Set it to a numeric type.
Try this:
$result = mysql_query("SELECT * FROM example ORDER BY rank DESC");
while($row = mysql_fetch_array($result))
{
echo $row['text'] . " ". $row['rank'] ."<br>";
}
And see if the ranks are being sorted correctly.
$result = mysql_query("SELECT * FROM `example` ORDER BY `rank` DESC");
while($row = mysql_fetch_array($result))
{
echo $row['text'] ."<br>";
}