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.
Related
I am writing a Custom Query in WordPress database to get the previous record from the posts table.
Example:
I have an ID of 34975; after I query the database I should get the ID as 34972, which is the previous record ID.
SQL
$results = $wpdb->get_results( "SELECT * FROM agencies_posts WHERE ID = '34975 ' LIMIT 1", OBJECT );
foreach( $results as $item ){
$previous_depature_port = $item->ID;
}
If I'm understanding your question correctly, you need to add ORDER BY and use < instead of =:
SELECT *
FROM agencies_posts
WHERE ID < 34975
ORDER BY ID DESC
LIMIT 1
Pretty sure you want:
select *
from agencies_posts
where id = (select max(id) from agencies_posts where id < '34975')
If the 'current' id is what's known and you just want the one prior.
Select everything with an id less than the one you are interested in, and only grab the first one
SELECT *
FROM agencies_posts
WHERE ID < '34975 '
ORDER BY ID DESC LIMIT 1"
I am getting 10 rows with the highest ID from a table ...
$result = pg_query($dbconn, "SELECT w_news_id, name, w_newsnachricht, w_newsdatum FROM adempiere.w_news ORDER BY w_news_id DESC LIMIT 10");
... then I build 10 divs in a while loop:
while ($row = pg_fetch_row($result)) {
// building divs here
}
BUT I want to also include the name that belongs to the next w_news_id in that same div (as a "teaser" for the "next"-arrow). So I was thinking I have to run a second query with the ID that would be next in the loop.
How is the SQL syntax for that? Or is there maybe a better way to do this?
You can use the lead window function:
SELECT w_news_id, name, w_newsnachricht, w_newsdatum,
LEAD (name) OVER (ORDER BY w_news_id) AS next_name
FROM adempiere.w_news
ORDER BY w_news_id DESC
LIMIT 10
You can select one more record - LIMIT 11, instead of 10, and process it differently in PHP.
$result = pg_query($dbconn, "SELECT w_news_id, name, w_newsnachricht, w_newsdatum FROM adempiere.w_news ORDER BY w_news_id DESC LIMIT 11");
$i = 0;
while ($row = pg_fetch_row($result) and $i < 10) {
$i++;
// building divs here
}
// then process the arrow and teaser separately (if present)
if ($row = pg_fetch_row($result)) {
// show teaser div
}
UPDATE
The window function solution provided by Mureinik is better.
this is my script
<?php
if(isset($_GET['id']))
{
$id = $_GET['id'];
}
else
{
$id = 1;
}
$random = $conn->query("SELECT * FROM records ORDER BY RAND()");
$row = $random->fetch();
$stmt_1 = $conn->prepare("SELECT * FROM records WHERE id > ? ORDER BY id ASC LIMIT 1");
$stmt_1->bindValue(1,$id);
$stmt_1->execute();
$stmt_1->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt_1->fetch();
$id = $row['id'];
$stmt_1 = $conn->prepare("SELECT * FROM records WHERE id < ? ORDER BY id DSC LIMIT 1");
$stmt_1->bindValue(1,$id);
$stmt_1->execute();
$stmt_1->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt_1->fetch();
$id = $row['id'];
?>
But I have a problem with it. For example i have 4 records in database :
ID String
1 Test-1
2 Test-2
3 Test-3
4 Test-4
the query works fine it gives me the next record but not the id which i put like if i put id=1 returns id 2 or id=2 returns info for id 3 and the result is not accurate. So my question is what should I do id to return correct result not +1. I know it starts to count from 0 and i want to fix that in my script i want to make it to start from 1.
replace this
$id = 1;
by
$id = 0;
or replace this
SELECT * FROM records WHERE id > ?
by
SELECT * FROM records WHERE id >= ?
^--//-will look for id equal to 1 or bigger
why don't you change your query to
EDIT: Query will not work as records are deleted.
$stmt_1 = $conn->prepare("SELECT * FROM records WHERE id = ?");
$stmt_1->bindValue(1,$id +1);
$stmt_1->execute();
So you will get the record with the next highest id.
Just a hint to optimize your query.
One further question do you use auto_increment in your table definition. If you do so, you shold keep in mind that this mysql-sequence starts by one to calculate the primary key
Hope it helps
So I'm trying to add a little bit of convenience to a CRUD by adding next and previous links to navigate between records in my database.
Here are my queries:
$id=$_GET['id'];
$id = $currentid;
$prevquery= "SELECT * FROM inventory WHERE id < $currentid ORDER BY id DESC LIMIT 1";
$prevresult = mysql_query($prevquery);
$nextquery= "SELECT * FROM inventory WHERE id > $currentid ORDER BY id ASC LIMIT 1";
$nextresult = mysql_query($nextquery);
?>
Here is my HTML:
Previous
Next
Now I tested these queries in PHPMyAdmin and they produced the result I wanted, but I can't get my hyperlinks to actually be supplied with the correct IDs... they're just blank after the =. What am I doing wrong?
mysql_query() returns a result set (resource). To get the actual rows from the result set, you need to use a function like mysql_fetch_row().
Your code for the "next" link would look something like:
PHP
$nextquery= "SELECT * FROM inventory WHERE id > $currentid ORDER BY id ASC LIMIT 1";
$nextresult = mysql_query($nextquery);
if(mysql_num_rows($nextresult) > 0)
{
$nextrow = mysql_fetch_row($nextresult);
$nextid = $nextrow['id'];
}
HTML
Next
and the previous link would be done similarly.
Obligatory note: For new code, you should seriously consider using PDO.
Advanced note:
You could combine your queries into a single query like:
SELECT
(
SELECT id
FROM inventory WHERE id < $currentid ORDER BY id DESC LIMIT 1
) AS previd,
(
SELECT id
FROM inventory WHERE id > $currentid ORDER BY id ASC LIMIT 1
) AS nextid
And then adjust the logic accordingly.
Okay, It took a little bit but I figured it out...
PHP
$prevquery= "SELECT * FROM inventory WHERE id < $currentid ORDER BY id DESC LIMIT 1";
$prevresult = mysql_query($prevquery) or die(mysql_error());
while($prevrow = mysql_fetch_array($prevresult))
{
$previd = $prevrow['id'];
}
$nextquery= "SELECT * FROM inventory WHERE id > $currentid ORDER BY id ASC LIMIT 1";
$nextresult = mysql_query($nextquery) or die(mysql_error());
while($nextrow = mysql_fetch_array($nextresult))
{
$nextid = $nextrow['id'];
}
HTML
Previous
Next
Thanks for the help, I think it put me on the right course. I'll look into that PDO stuff for the future. I'm just now starting to get a hang of the old MYSQL/PHP syntax and now all the sudden there's a new format... tough to keep up with it all!
The resultant code has a culprit at the very beginning and end of the table. Your code will "die" as you ordered. Instead you might check the query results ($prevresult, $nextresult) and decide NOT to show a link for previous or next item.
SELECT
IFNULL(
(SELECT id FROM inventory WHERE id < $currentid ORDER BY id DESC LIMIT 1 ) , (SELECT id FROM inventory ORDER BY id DESC LIMIT 1 )
) AS previd ,
IFNULL(
(SELECT id FROM inventory WHERE id > $currentid ORDER BY id ASC LIMIT 1 ),
(SELECT id FROM inventory ORDER BY id ASC LIMIT 1 )
) AS nextid
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++;
}