Array Results in PHP - php

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

Related

Next and previous buttons

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
}

How to show 5 post each page with next & previous button feature?

I have a page named 'job.php', currently this page is showing all posted job. But now I want to show only 5 latest posts. And if anyone want to check the previous posts, they can click next button thus more 5 posts will be seen. There should be a previous button too.
Following is my code:
$result1 = mysql_query("SELECT * FROM job ORDER BY ID DESC");
$num_row = mysql_num_rows($result1);
while($row1 = mysql_fetch_array($result1)){
$cat=$row1['Category'];
$title=$row1['Title'];
echo "Job field: $cat<br/> Title: $title<br/>";
}
N:B: It's not pagination. I don't want to show page numbers, just want to show next & previous button.
There are 100s of articles available on the Internet
Create Awesome PHP/MYSQL Pagination
PHP / MySQL select data and split on pages
If you want to do on your own:
Use LIMIT keywords in your query.
Pass the page and the multiplier to the LIMIT.
Some code
<?php
$limit = 5;
$start = (int)(($page - 1 ) * $limit);
$page = mysql_real_escape_string($_GET["page"]);
$query = "SELECT * FROM `table` LIMIT $start, {(int)$page + $limit}"
?>
There are two ways to achieve this.
1) In the query itself by using LIMIT
$result1 = mysql_query("SELECT * FROM job ORDER BY ID DESC LIMIT 1, 5");
2 ) By using loop
$i = 0;
while($row1 = mysql_fetch_array($result1)){
if($i < 5) {
$cat=$row1['Category'];
$title=$row1['Title'];
echo "Job field: $cat<br/> Title: $title<br/>";
$i++;
}
}
You can pass the current value to URL and get it back by using $_GET..
You can use this query:
Select * from table_name ORDER BY ID DESC LIMIT 5;
I feel its better to use pagination. If you want dont want to show page nos, better hide it or just modify the code. If you planning to do it manually its a bit messy
You can use LIMIT in you mysql query:
$result1 = mysql_query("SELECT * FROM job ORDER BY ID DESC LIMIT 0, 5");

How to retrieve first 2 results from mysql array without querying again?

Each page lists all the coupons available for a specific retailer. I query the database for all the coupon codes in the header since I count the number of rows returned and use that info in the meta title of the page. I now also want to display the titles of the first 2 coupons in the array. How would I go about extracting the first 2 results from the array without querying the database again?
This is what I have so far:
$retailer_coupons = "select C.couponid,C.fmtc_couponid,C.merchantid,C.exclusive,C.label,C.shoppingtip,C.restrictions,C.coupon,C.custom_order,C.link,C.image,C.expire,C.unknown,M.name,M.approved,M.homepageurl,M.category from tblCoupons C,tblMerchants M where C.merchantid=M.merchantid and C.begin < ".mktime()." and C.expire > ".mktime()." and C.merchantid=".$merchantid." and M.display='1' and C.user_submitted='' order by C.custom_order desc, C.coupon desc";
$retailer_coupons_result = mysql_query($retailer_coupons) or die(mysql_error());
$count_coupons=mysql_num_rows($retailer_coupons_result);
$meta_title = ''.$name.' Coupon Codes ('.$count_coupons.' coupons available)';
Suppose I have 3 records in my table. If I execute below query, I will get 2 results however the count(*) will give me 3 as output
SELECT count(*) FROM temp.maxID limit 2
In your case it will be
$retailer_coupons =
"select C.couponid,C.fmtc_couponid,C.merchantid,C.exclusive,C.label,C.shoppingtip,C.restrictions,C.coupon,C.custom_order,C.link,C.image,C.expire,C.unknown,M.name,M.approved,M.homepageurl,M.category
from tblCoupons C,tblMerchants M
where C.merchantid=M.merchantid
and C.begin < ".mktime()." and C.expire > ".mktime()."
and C.merchantid=".$merchantid." and M.display='1'
and C.user_submitted=''
order by C.custom_order desc, C.coupon desc
limit 2";
limit 2 will do the magic... Cheers!!!
Good Luck!!!
Something like this:
$res = mysql_fetch_assoc($retailer_coupons_result);
$i = 0;
while ($i < 2){
echo $res[$i]['label']."\n";
$i++;
}

mysql multiple table query inside php loop

Faily new to php and mysql, this will probably seem very messy.
This is what I came up with:
$query = "show tables like 'whatever%'";
$result = mysql_query($query);
$num_results = mysql_num_rows($result);
for ($i = 0; $i < $num_results; $i++)
{
$row = mysql_fetch_array($result);
$sql=mysql_query("SELECT * FROM ". $row[0] ." WHERE a=(SELECT MAX(a)) AND b=(SELECT MAX(b)) AND c LIKE 'd%' ORDER BY date DESC LIMIT 1");
while($info=mysql_fetch_array($sql)){
echo "...";
}
}
I get the desired value from each table, so x results depending on the amount of tables. What I would like is to have the results of the queried tables but only show the top 10-5 ordered by date/time.
Is this possible with the current script? Is there an easier way (while, number of tables changing constantly)? Is this query method database intensif?
Cheers!
I call constantly changing number of tables having similar structure a design error. also query switch to
$sql=mysql_query("SELECT * FROM $tbl WHERE c LIKE 'd%' ORDER BY a DESC, b DESC, date DESC LIMIT 1");
is a little relief to database.

the query is breaking. How to skip rows PHP

I have a question probably lame but it made me stuck
I have the a db query
$query_Recordset10 = "SELECT * FROM products
WHERE razdel='mix' AND ID='$ID+1' AND litraj='$litri' ORDER BY ID ASC";
$Recordset10 = mysql_query($query_Recordset10, $victor) or die(mysql_error());
$row_Recordset10 = mysql_fetch_array($Recordset10);
$totalRows_Recordset10 = mysql_num_rows($Recordset10);
This is the query for the next product in the line based in the ID of the current product thats on the page.
But if the next product matching the criteria in the query is 2 or more ID's ahead my cycle breaks. So is there a way for skipping this rows and get the next ID matching the criteria.
Thank you very much.
SELECT * FROM products
WHERE razdel='mix' AND ID > $ID AND litraj='$litri' ORDER BY ID ASC";
PROBLEM SOLVED. I still have a lot to learn.
SELECT * FROM products WHERE razdel='mix' AND ID>'$ID' AND litraj='$litri' ORDER BY ID ASC LIMIT 1
this is the wright line but my mistake was how $ID is generated.
Thank you all.
Change your query to this:
$query_Recordset10 = "SELECT * FROM products
WHERE razdel='mix' AND ID > '$ID' AND litraj='$litri' ORDER BY ID ASC LIMIT 1";
So you still only get 1 row returned (if there's anything to return), but you'll be returning the next row (according to ORDER BY ID ASC) versus (potentially) the row with an incremental ID.
Use foreach to loop over an array rather than trying to access by indexes (if you're fetching every value):
foreach ($records as $record) {
}
instead of
for ($i = 0; $i < count($records); $i++) {
}
or
$i = 0;
while ($i < count($records)) {
$i++;
}
or
$i = 0;
do {
} while (++$i < count($records));
Use this query instead:
SELECT * FROM products WHERE razdel='mix' AND ID>$ID AND litraj='$litri' ORDER BY ID ASC LIMIT 1
This will give you the next element after the one with ID of $ID.

Categories