Incrementing via MySQL/PHP - php

I am looking for a way to increment and decrement by a step of three records in a table and return them.
Say ID '4' is currently active. I want to get the next 3 and the previous 3 records with IDs and category of 3.2.1 and 5.6.7 (via incrementing and decrementing).
So far I have:
$stmt = $db->query("SELECT id, category FROM test");
$stmt->execute();
while ($results = $stmt->fetch(PDO::FETCH_ASSOC))
{
$current = $results['id'];
$category = $results['category'];
$next = array(array(
'slide_no' => $current,
'category' => $category
));
}
print_r($next);
Using this, I am getting back every row in the table.
I'm getting confused how to increment and decrement the records by a step of 3 and make sure that the category will also increment accordingly.
Thank you very much.

You will need to create a string with the 6 ids that you need.
So if CatID was 4 you would want
$selectIDs = '1, 2, 3, 4, 5, 6, 7";
Then when you perform your SQl you would use
"SELECT id, category FROM test WHERE id IN (" . $selectIDs ."')";

If I understand your question correctly, you want to paginate the displayed data. You need to use the MySQL LIMIT clause.
You'll need to adjust your query, using values generated from your code. See an example below:
$stmt = $db->query("SELECT id, category FROM test LIMIT ?, 3");
#you'll supply the ? parameter depending on your current start index
MySQL Limit clause Tutorial

You can use the => and <= operators.
First store the id in a variable:
$intId = 4
Then add and decrement 3
$intAdd = $intId + 3
$intDecr = $intId -3
Then setup your sql string
$stmt = $db->query('SELECT id, category FROM test where id =>'. $intDecr.' and <= '.$intAdd. ');

Related

SQL Use array and use result in select(sum) statement

I am trying to use the selected id's as an array a other statement. It seems it is not counting all the result as it is much lower that it is.. I have tried to find my answer on google but none of the options are working for me or i do not know how to use them in my case. There are no errors and i have error log on!
Here is my code, what am i doing wrong?
$counttheid = array();
$stmt3 = $mysqli->prepare("SELECT
id
FROM account
WHERE level <= '5' AND door = ? AND `group_name` = ? AND betaald = 'Yes'");
$stmt3->bind_param("ss",$usernamesession,$groupname);
$stmt3->execute();
$result3 = $stmt3->get_result(); //only works when nd_mysli is set on the server!
while ($rowid = $result3->fetch_assoc())
{
$counttheid[] = $rowid['id'];
$countid = implode(',', $counttheid);
}
$sql = "SELECT SUM(mobcash) AS totalcash FROM account WHERE id IN (?)
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s",$countid);
$stmt->execute();
$stmt->bind_result($row['totalcash']);
while($stmt->fetch()) $sumcash = $row['totalcash'];
//echo print_r($counttheid);
//echo implode(',', $counttheid);
echo $sumcash;
I am no profesional developer just started learning this, any help is welcome!
Since you have edited the question, my original answer is no longer relevant.
I suggest for you to simplify your two queries into a single query. In your first query you select a bunch of ids and in the second query you sum a different value from the same table using the ids. You can just to that in one query:
SELECT SUM(mobcash) AS totalcash
FROM account
WHERE level <= '5'
AND door = ?
AND `group_name` = ?
AND betaald = 'Yes';
Original answer
You use $result->fetch_all(MYSQLI_ASSOC), meaning each row from the result set will be an associative array with the column names as the keys and the cell values as values. That is also the case, if you only select one column.
That means for this example table
id | name | balance
----+------+---------
1 | acc1 | 12.34
2 | acc2 | 1.23
your variable $dataid will have the following value (for the simplified query SELECT id FROM account):
$dataid = [
[
"id": 1
],
[
"id": 2
]
];
To get more familiar with PHP, you could write some foreach loops yourself, but you can also use the built-in PHP function array_column (php.net: array_column):
$ids = array_column($dataids, "id");
From an SQL perspective I would also suggest for you to learn about nested queries, since you could avoid this PHP logic altogether.

Record query results for use in further queries

I can't explain it properly but I have several different loop queries on a page (news website homepage) to select articles and want to "record" the ID of each article to exclude such ID's from further query results.
Select rand from database ... result = ID's 3, 99, 6
$selected = 3, 99, 6
Select rand from database WHERE ID != $selected ... result = ID 51
$selected = 3, 99, 6, 51
Select rand from database WHERE ID != $selected ... result = ID 4
I can't wrap my head around on how to "record" the already selected ID's incremential and then use it further down to prevent the same article to appear twice.
make an array where you add all result ids into, then explode that array for the next sql. something like this:
$selectedIds = array();
// make first query, get results in loop. im not writing the query execution here, just the loop after
while($row = mysqli_fetch_assoc($res)){
$selectedIds[] = $row['id'];
// do your other stuff here (single article generation)
}
// for further queries you can make the WHERE clause like this
$query = "SELECT rand FROM table WHERE ID not in (".explode(', ', $selectedIds).")";
// this will make the actual query look like this:
// SELECT rand FROM table WHERE ID not in (3, 99, 6)

show row only 100 times PHP

How can I make a limit of showing the results? I need to limit it for 100 views.
In DB I have:
ID|NAME|PAGE|COUNT|DATE
In count I want to count untill 100 and then stop showing that ID. I could do it with count < 100. And then update the specific ID. I could get records with less than 100 views, but I couldn't manage to update count on the specific ID.
Row is showed with:
php code:
foreach($bannerGroups[0] as $ban) {
echo '<li class="right1">'.$ban->html().'</li>';
}
But I just don't know where to put the update in there. I tried, but all I got was to update only one ID. But it shows 4 on one page and randomizes them on refresh. So I don't know what to do.
Also I would like to say I am only learning php. Sorry for all the mess.
Code at http://pastebin.com/A9hJTPLE
If I understand correctly, you want to show all banners that have been previously-displayed less than 100 times?
If that's right, you can just add that to your WHERE clause:
$bannerResult = mysql_query("SELECT * FROM table WHERE page='cat' WHERE `COUNT` < 100");
To update them all, you can either run a query while displaying each individual banner, or "record" the id of each and run a single query at the end, like:
$ids = array();
foreach($bannerGroups[0] as $ban) {
$ids[] = $ban['ID']; // record the ID; don't know how Banner
// class works, assuming uses indexes; maybe ID() method?
echo '<li class="right1">'.$ban->html().'</li>';
}
...
mysql_query('UPDATE table SET `COUNT` = `COUNT` + 1 WHERE ID IN (' . join(',', $ids) . ')');
UPDATE:
Based off of a comment, your Banner class doesn't have a method to retrieve the individual banner's ID. In this case, you can record the ID values when you're building your banners array:
$ids = array();
while($row=mysql_fetch_assoc($bannerResult)) {
$banners[] = new Banner($row);
$ids[] = $row['ID']; // record the ID
}
// update the `count` on each record:
mysql_query('UPDATE table SET `COUNT` = `COUNT` + 1 WHERE ID IN (' . join(',', $ids) . ')');
sorry, but I got your question wrong...
first you have to insert a new sql-column like "viewcount" to the db...
on every read, you have to increment the value in viewcount...
for that behaviour (because, mysql does not allow sub-selects on update-clause on the same table), you have to fetch the results from db, as you do that, and pass all the primary-keys of the records to an array...
after the view-logic you have to fire up a query like:
UPDATE foo SET viewcount = viewcount + 1 WHERE id IN (1,2,3,4,5,6...,100);
where the IN-clause can be easily generated using your primary-keys-array with "implode(',', $arr);"
hope this helps.
$bannerResult = mysql_query("SELECT * FROM table WHERE page='cat' AND `count`<100");
#newfurniturey figured it out. in each foreach($banneruGroups added: $ids = $ban->getValue('id'); and then mysql_query("UPDATE dataa SET COUNT = COUNT + 1 WHERE id = '$ids'"); but is there any way to update them by adding query only once? And if the id is showed already 100 times i get Warning: Invalid argument supplied for foreach() in. Any idea how to fix it? I have 4 ids in DB . If one of them already have 100 views (count) then i get error!
Try to limit your data source for 100 items.
It's like OFFSET x LIMIT 100 in MySQL/PostgreSQL query or TOP 100 in MSSQL.

mysql within Joomla next and previous SQL statement within orderby

I know things are escaped incorrectly, but I am trying to write a previous/next query to get the next id and previous id within an order, but my output does not match the phpmyadmin sorting, which it should. I just have the 'next' written, and would write the previous with reverse conditions. This query seems to give me the next highest ID value number within the order...I need the next or previous in the order index...can anyone help?
$db = JFactory::getDBO();
$query = "SELECT image_id FROM #__jxgallery_images WHERE image_id >".$currentid."' ORDER BY '".$ordering." ".$direction." LIMIT 1";
// Executes the current SQL query string.
$db->setQuery($query);
// returns the array of database objects
$list = $db->loadObjectList();
// create the list of ids
foreach ($list as $item) {
$next = $item->image_id;
echo $next.'<br/>';
}
echo 'The next ID in this sort state is '.$next.'<br />';
?>
This is phpmyadmin and it is right...
SELECT * FROM `jos_jxgallery_images`
ORDER BY `jos_jxgallery_images`.`hits` DESC
LIMIT 0 , 30
I have now matched this query in my code to get the same results. My variables fill in the ($ordering) 'hits' field and the 'desc' ($direction) within my clause. That works fine. The image_ids and hits aren't special...just numbers. When hits are ordered, the image_ids are resored to match. I don't need the next value of image_id as to what is in the field. I need the next row or previous row, regardless of value, based on the current image_id I plugin.
These are actual image_ids LIMIT 5, and these are Ordered by the hits field Descending:
52791
52801
52781
52771
52581`
Now if the current image I'm looking at has an id of 52791, then previous should be nothing and next should be 52801. What my query is doing I think is giving me an image_id of a higher valued number as 'next' because that is the next highest VALUED image_id, not the next row. I can see why in the query, I am asking for greater than...but I just need the next row
I think the problem is with your WHERE condition: WHERE image_id >".$currentid."'
If I understand what you're trying to do, one way to do it is this:
$query = "SELECT image_id FROM `#__jxgallery_images` ORDER BY ".$ordering." ".$direction." LIMIT 2";
$db->setQuery($query);
$list = $db->loadObjectList();
$next_item = $list[1]->image_id;
Notice that the WHERE condition is removed from the query, and I also changed LIMIT 1 to LIMIT 2. This way, the query basically returns your top value and the one with the next highest "hits" value.
I hope this helps.

PHP from database and query

I have a table:
id, affiliate
Each time somebody clicks a link, a new row is inserted,
ID being the ID of the page, and affiliate being the ID of the affiliate.
For example:
Page ID: 9 Affiliate ID: 1
Page ID: 9 Affiliate ID: 2
Page ID: 9 Affiliate ID: 3
I only have 3 affiliates.
I want to select this information, and group them by affiliate, for the ID.
I have tried this query:
SELECT COUNT(*) FROM table
WHERE id = '9' GROUP BY
affiliate
It works fine when I do it in php my admin, how do I get the info in PHP?
I have tried:
$q = mysql_query("SELECT COUNT(*) FROM
table WHERE id = '" . $id . "'
GROUP BY affiliate");
$r = mysql_fetch_array($q);
When trying to print the data onto the page, I am only getting one result.
Do I need to use a foreach/while loop to get all 3? How would I go about doing this?
Thank you!
You should do mysql_fetch_array() (or mysql_fetch_assoc()) in a loop:
while ($row = mysql_fetch_assoc($q)) {
echo $row["id"];
echo $row["affiliate"];
}
UPDATE (in accordance with comment):
If you ALWAYS have 3 rows in your result, probably mysql_result() function would be helpful:
$firstAffiliate = mysql_result($q, 0, "affiliate");
$secondAffiliate = mysql_result($q, 1, "affiliate");
$thirdAffiliate = mysql_result($q, 2, "affiliate");
BTW, be careful and check, whether query actually returns 3 results.
Loop like this:
while($row = mysql_fetch_array($q)) {
print_r($row);
}
If you just want to get list of Affiliate ID, you can consider this query
select group_concat(affiliate)
from table
where id=9;
The above will return a comma separate value like 1,2,3 in single row
So, you can then in PHP explode using ,, and the size of the exploded array is the same as count(*)
you can use a variable to hold state inside the actual mysql statement itself. Try the following:
affiliates:
page_id
afil_id
set #page_id=0;
select page_id, if(#page_id <> page_id, count(*), 0), #page_id:=page_id from clicks group by page_id;
Hope that helps

Categories