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.
Related
I have a php script that displays records from a database. It's probably not the best script, as I'm very new to php.
I've added an additional column in my table and would like to keep a count in that column to show me how many times each of the records have been viewed.
Heres the part of the code I think i need to add the code to... if i need to post the entire page i will, but i just figured i could add the line to this part.
//Get the details from previous page
$SelectedCounty = $_POST["result"];
//set variable for next SEARCH
$option = '';
// Get the county names from database - no duplicates - Order A-Z
$query = "SELECT DISTINCT tradingCounty FROM offers ORDER BY tradingCounty ASC";
// execute the query, $result will hold all of the Counties in an array
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)) {
$option .="<option>" . $row['tradingCounty'] . "</option>";
}
}
the new column name is 'views' and i just want to add 1 to it each time a record from the database is viewed.
any help greatly appreciated.
Add a new field views to the table.
When, user views the page, fire the SQL.
$query = "UPDATE offers SET views = views + 1";
mysqli_query($con,"update offers set views = views + 1");
If you have added the column, it probably has a NULL value. Either set the value to 0, by doing:
update offers
set views = 0;
Or use:
update offers
set views = coalesce(views, 0) + 1;
You can change your code with this rewritten code assuming that your Table has a column views (datatype int).
//Get the details from previous page
$SelectedCounty = $_POST["result"];
//set variable for next SEARCH
$option = '';
// Get the county names from database - no duplicates - Order A-Z
$query = "SELECT DISTINCT tradingCounty FROM offers ORDER BY tradingCounty ASC";
// execute the query, $result will hold all of the Counties in an array
$result = mysqli_query($con,$query);
if($result){
$query2 = "UPDATE offers SET views=views+1;
mysqli_query($con,$query2);
}
while($row = mysqli_fetch_array($result)) {
$option .="<option>" . $row['tradingCounty'] . "</option>";
}
Or if you need to track the view counts for individual records, you need to modify your code a bit. And probably you need to add one more field in the database for eg. id (datatype int) which can distinguish between different records.
Please clear your problem properly.
As far as i have analysed your code it brings out the following case.
There are different records for tradingConty, and whenever a user views that particular record(one of the tradingCounty record) by clicking that or any other action specified, the php script is set to increament the view count for that particular entry(we can get that by id) in the database.
If thats the scenario, we can easily generate a code accordingly.
I have insert in table any time when users open any post on my site, in this way im get real time 'Whats happend on site'
mysql_query("INSERT INTO `just_watched` (`content_id`) VALUES ('{$id}')");
but now have problem because have over 100K hits every day, this is a 100K new rows in this table every day, there is any way to limit table to max 100 rows, and if max is exceeded then delete old 90 and insert again or something like that, have no idea what's the right way to make this
my table just_watched
ID - content_id
ID INT(11) - AUTO_INCREMENT
content_id INT(11)
Easiest way that popped into my head would be to use php logic to delete and insert your information. Then every time a user open a new post you would then add the count the database. (this you are already doing)
The new stuff comes here
Enter a control before the insertion, meaning before anything is inserted you would first count all the rows, if it does not exceed 100 rows then add a new row.
If it does exceed 100 rows then you before inserting a new row you, first do a delete statement THEN you insert a new row.
Example (sudo code) :
$sql = "SELECT COUNT(*) FROM yourtable";
$count = $db -> prepare($sql);
$count -> execute();
if ($count -> fetchColumn() >= 100) { // If the count is over a 100
............... //Delete the first 90 leave 10 then insert a new row which will leave you at 11 after the delete.
} else {
.................. // Keep inserting until you have 100 then repeat the process
}
More information on counting here. Then some more information on PDO here.
Hopefully this helps :)
Good luck.
Also information on how to set up PDO if you haven't already.
What I would do? :
At 12:00 AM every night run a cron job that deletes all rows from the past day. But thats just some advice. Have a good one.
Use this query for deleting old rows except last 100 rows:
DELETE FROM just_watched where
ID not in (SELECT id fromjust_watched order by ID DESC LIMIT 100)
You can run it by CRON in every n period where (n= hours, or minutes, or any)
$numRows = mysql_num_rows(mysql_query("SELECT ID FROM just_watched"));
if ($numRows > 100){
mysql_query("DELETE FROM just_watched LIMIT 90");
}
mysql_query("INSERT INTO `just_watched` (`content_id`) VALUES ('{$id}')");
I guess this should work fine.
You can get the number of rows in your table with:
$size = mysql_num_rows($result);
With the size of the table, you can check, if it's getting to big, and then remove 90 rows:
// Get 90 lines of code
$query = "Select * FROM just_watched ORDER BY id ASC LIMIT 90";
$result = mysql_query($query);
// Go through them
while($row = mysql_fetch_object($result)) {
// Delete the row with the id
$id = $row['id'];
$sql = 'DELETE FROM just_watched
WHERE id=$id';
}
Another way would be to just delete an old row if you add a new row to the table. The only problem is, that if something get's jammed, the table might get to big.
You may use
DELETE FROM just_watched ORDER BY id DESC LIMIT 100, 9999999999999999;
So, it'll delete all the rows from the offset 100 to a big number (for end of the tables). if you always run this query before you insert new one then it'll do the job for you.
Anyone who could help me it will be greatly appreciated.
Goal: I want to display the id from one table randomly as well as to make sure it has not been seen by the current user.
Two tables: offers, has_seen
I want to pick a random id from offers, check it against the has_seen table.
If the ID exists in the has_seen, it need to re pick another random id. The same ID should never be seen by any one user of the current session.
I cannot seem to figure out how to pick a random one, check the other table, and loop back if found.
I have tried this
$query = $this->db->query("SELECT * FROM ".$this->offer_table." WHERE NOT EXISTS (SELECT * FROM ".$this->shown_table." WHERE ".$this->shown_table.".camp_id = ".$this->offer_table.".camp_id AND ".$this->shown_table.".usercode = ".$this->session->userdata("table")." LIMIT 1 ");
I think that this can be achieved in plain SQL by doing a left join and then checking for null.
Something along the lines of
SELECT * FROM table1 LEFT JOIN table2 USING (shared_key) WHERE table2.id IS NULL ORDER BY rand() LIMIT 1
Here's how you could do it using CI's db class:
// the maximum ID that is acceptable
$max = $this->db->get('first_table')->count();
while(true) {
// get a random number
$randomID = rand(0,$max);
// the condition for which we will check the has_seen table
$condition = array(
'id' => $randomID
);
// if count is 0, it has not been seen. We add it to the table and return
// if it has been seen, the loop will repeat
if ($this->db->get_where('has_seen', $condition)->count() === 0) {
$this->db->insert('has_seen', array(
'id' => $randomID
));
return $randomID;
}
}
SELECT * FROM `offers` WHERE `camp_id` NOT IN (SELECT `camp_id` FROM `has_seen` WHERE `user code` = 1) ORDER BY RAND() LIMIT 1
I always prefer reading the contents of a table into an array and working with them from there. Depending on how you plan to use the results, you could cut down on db accesses by reading it all only once and then serving from the array (and then, I presume, updating the has_seen table for next session).
I must apologize for the pseudocode as it's been years since I've written any PHP.
Once you've got your array, the algorithm looks like this:
var array
var end = array.length
function getNextRandomUnseen
{
var i = rand(end)
var temp = array[i]
array[i] = array[end--]
return temp
}
If you want, you can even stick the seen values at the end of the array so they aren't lost.
array[end+1] = temp
Thanks for the answers. I redid the way it is going to be brought to the user and believe the new way is much more efficient when it comes to hundreds of people on my site at once.
Thanks!
I try to build a variable that integrates some other variable.
one of that will be the number of an auto-increment-field where later on an insert-query will happens.
I tried to use:
$get_num = $db/*=>mysqli*/->query("SELECT COUNT (*) auto_increment_column FROM table1");
$num = $query->fetch_assoc($get_num);
$end = $num + 1;
I don't have any update/insert query before that so I can't use
$end = $db->insert_id;
that's why i thought i can just count the numbers of the auto_increment rows and have my last variable that is necessary to build my new variable.
for a reason this wonT count the entries and outputs 0. i dont understand why this happens.
i really would appreciate if there is someone who could tell me what am i doing wrong. thanks a lot.
UPDATE
For everyone who likes to know about what's the goal:
I like to create a specific name or id for a file that later on will be created by the input of the fields from the insert query. I like to have an unique key. this key consists of an user_id and a timestamp. at the end of this generated variable it should be placed the auto_increment nr. of the query that will be placed in the table. so the problem is, that I create an variable before the insert query happens so that this variable will be part of the insert query like:
$get_num = $db->query("SELECT COUNT (*) FROM tableA");
$num = $query->fetch_assoc();
$end = $num + 1;
$file_id = $id .".". time() .".". $end;
$insert = $db->query("INSERT INTO tableA ( file_id, a, b, c) VALUES('".$file_id."','".$a."','".$b."','".c."')");{
hope now, it will be clear what I like to approach.
If you need an auto-incrementing column in MySQL then you should use AUTO_INCREMENT. It implements it all for you and avoids race conditions. The manual way you are trying to implement it has a couple of flaws, namely
If two scripts are trying to insert concurrently they might both get the same COUNT (say 10) and hence both try to insert with ID 11. One will then fail (or else you will have duplicates!)
If you add 10 items but then delete item 1, the COUNT will return 9 but id 10 will already exist.
try
SELECT COUNT(*) FROM table1
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