limit maximum input to the database php mysql? - php

how can i limit the maximum number of rows in mysql. For example, if the number of grade 4, section 1 students is 30 or over, the user cannot add another student.

first count the rows of the given conditions
$res = mysql_query("SELECT count(*) as cnt FROM `your_table` WHERE grade='4' AND section='1'");
$row = mysql_fetch_assoc($res);
if($row['cnt']<30)
{
// insert student
}
else
{
// not to insert student
}

DELIMITER $$
CREATE TRIGGER trigger1
BEFORE INSERT
ON table1
FOR EACH ROW
BEGIN
SELECT COUNT(*) INTO #cnt FROM table1;
IF #cnt > 30 THEN
/**raise an error**/
END IF;
END
$$
DELIMITER ;

Related

how can i find second maximum of my query

Here is my SQL query to find a row in currency_price table grouped by maximum date of inserting to table. My question is how to find the second maximum. I mean how can I change this query to find the second maximum row in each group:
select currency_id,buy,sell
from (select * from currency_price order by `currency_id`, cu_date desc,buy,sell) x
group by `currency_id`
with this query i found a row for each id so for example i have sell and buy for each id .exm:
id sell buy
1000 500 480
1001 20 19
...
but here i want the second maximum date for each id.
I know some query to find second maximum but all does not take me to my answer.
If it is MySql then Use LIMIT 1,1; # Retrieve rows [start with rec]1-[fetch rec count]1
http://dev.mysql.com/doc/refman/5.7/en/select.html
Use ROW_NUMBER()
Sample
SELECT * FROM
(
SELECT *,ROW_NUMBER() OVER (ORDER BY AGE DESC) RNUM FROM TEST_TABLE
) QUERY1 WHERE RNUM=2
You could manually add a group order number to your initial ordered query & then select the second from each row.
The inner query, orders as required & numbers the rows starting from 1, resetting each time the currency_id changes.
set #num := 0, #ci := -1;
select currency_id,buy,sell
from
(select *,
#num := if(#ci = currency_id, #num + 1, 1) as gp_number,
#ci := currency_id as dummy
from currency_price
order by `currency_id`, cu_date desc,buy,sell) x
where gp_number=2
This could be put into a stored procedure from workbench as follows :
DELIMITER $$
CREATE PROCEDURE SecondMaximum()
BEGIN
set #num := 0, #ci := -1;
select currency_id,buy,sell
from
(select *,
#num := if(#ci = currency_id, #num + 1, 1) as gp_number,
#ci := currency_id as dummy
from currency_price
order by `currency_id`, cu_date desc,buy,sell) x
where gp_number=2;
END$$
DELIMITER ;
And from PHP you execute "CALL SecondMaximum();"
If you wanted to be able to change tables and/or fields, then you could pass these as string variables to the procedure & create & execute a prepared statement within the stored procedure. Just do a google search for tutorials on those.

Mysql delete all except 100 new rows

Hello I need to empty all table except the x new rows i have already test
How to delete all rows from a table except newest 10 rows
SQL Delete all rows except for last 100
But not work, my mysql version doesn't support limit "IN"
(actual version Ver 14.14 Distrib 5.5.46)
My table is like that
ID (int)
DATE (timestamp)
Who i can empty without loop ? Thanks
Try this
<?php
$mysqli=new mysqli("localhost", "root", "", "db");
$result=$mysqli->query("select id from tabl order by id desc" );
$res=$result->fetch_array();
echo $res[0];
$id=$res[0]-100;
$mysqli->query("delete from table where id < $id");
?>
You can do it with a single SQL DELETE statement that uses variables:
DELETE mytable
FROM mytable
INNER JOIN (
SELECT ID, #rn := #rn + 1 AS rn
FROM mytable
CROSS JOIN (SELECT #rn := 0) AS var
ORDER BY DATE DESC
) AS t ON mytable.ID = t.ID
AND t.rn > 100
The derived tasble t is used to assign each ID of mytable a row number. Numbering uses ORDER BY DATE DESC, hence 100 most recent records are going to have rn in [1-100]. DELETE removes any row of mytable except those having rn in [1-100].
Demo here (Demo keeps 10 more recent records instead of 100)
You can do it by using number of SQL statments one after another.
You can do it by get the first ID that you want to delete, and then delete all the rows newer that ID
// Create the memory table for storing the IDs
create table mem(
first100 integer
);
// Insert to the memory table the list of 100 last ids
insert into mem(first100) select id from table order by id desc limit 100;
// Insert to Mysql variable #a, the id of the first id to delete
set #a=select fist100 from mem order by id limit 1;
// Delete all the id's after the one you want to delete
delete from table where id>=#a
Update:
I posted this answer befor you wroted that the error message is: This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME
Anyway, I keep it, maybe this method will help to someone else .

Using php and Mysql to Order by highest number and confirmation

Well I have this mysql table with numbers in one column and a confirmation boolean of 0 or 1 and I have about 1,000 rows so it's not something I can do manually but anyways...
I want to sort the row by highest value and grab the names of the first 5 people and put those 5 people in another table on a column and then set them to confirmed and continue until there's no one left in the table that isn't confirmed...
ex:
Name:Rank:Confirm
Bob:5000:0
James:34:0
Josh:59:1
Alex:48:0
Romney:500:0
Rolf:24:0
Hat:51:0
so when you run the code it will do the following:
Squad:Name1:Name2:Name3:Name4:Name5
1:Bob:Romney:Hat:Alex:James
(as you can see Josh was excluded and Rolf was too low)
And since Rolf is alone and there are no one else left, he wont be put into a team and will be left unconfirmed...
I'm not really pro at mysql so I was stumped on this and at most was capable of organizing the whole thing by rank and that's it ._.
edit:
The terrible attempt I had at this:
<?php
$parse = mysql_query("SELECT MAX(rank) AS rank FROM users AND confirm='0'");
mysql_query("Insert into squad (nameone)values($parse)");
mysql_query("Update squad set confirm = '1' where name = $parse");
?>
Assuming confirm will have only either 1 or 0.
CREATE TABLE table2 (id INT PRIMARY KEY AUTO_INCREMENT, name varchar(255));
CREATE PROCEDURE rank()
BEGIN
DECLARE count INT DEFAULT 1;
WHILE count > 0 DO
UPDATE table1 SET Confirm=2 WHERE Confirm=0 ORDER BY Rank DESC LIMIT 5;
INSERT INTO table2 (SELECT GROUP_CONCAT(Name) FROM table1 WHERE Confirm=2);
UPDATE table1 SET Confirm=1 WHERE Confirm=2;
SELECT count(*) FROM table1 WHERE Confirm=0;
END WHILE;
END;
Call the procedure rank() when ever you want
CALL rank();

MySQL Trigger doesn't update table

I created the following trigger in a MySQL database. It's for a star rating system. Whenever a row is added to the ratings table, it's supposed to add this to the ratings_totals table.
DELIMITER$$
create trigger update_vote_after_insert_trig before insert
on ratings
for each row begin
if bookID = new.bookID then
update ratings_totals set
total_votes = total_votes + 1,
total_rating = total_rating + new.rating,
overall_rating = total_rating / total_votes;
where
bookID = new.bookID;
ELSE
insert into ratings_totals set bookID = new.bookID, total_votes = total_votes, total_rating = total_rating, overall_rating = overall_rating;
END IF;
END$$
DELIMITER ;
My problem is that the ratings_totals table is incorrectly updated. It contains four rows: bookID, total_votes, total_rating and overall_rating. Only the bookID table is updated; the rest remain at 0.
My goal is to INSERT the row the first time, and update it after that. Am I doing this right?
If you want to insert at the first time and just update after the first time you can try to use "IF" statement.
if(this is the first time)
///your code
else
// your code
you can use "select" to find out if you inserted this row before and this will be your "IF"
shouldn't the "new" be "old"? Like:
DELIMITER $$
create trigger update_vote_after_insert after insert
on ratings
for each row begin
update ratings_totals set
total_votes = total_votes + 1,
total_rating = total_rating + old.rating,
overall_rating = total_rating / total_votes
where
bookID = old.bookID;
end$$
DELIMITER ;

how to get the position of sorted rows using mysql and php

I have a table which stores high-scores, along with player ids. I want to be able to extract a record by a players id, and then get the rank, or position of their score in the table. Means, Basically I want to be able to say "you are in Nth" position, purely based on the players score against all other scores. For Example: if i am at 46th position then to me the position message will be like you are at 46th position out of total scores. Can anyone show me small example?
There are two ways of doing it:
Method 1:
SET #i = 0;
SELECT * FROM
scores s1 INNER JOIN (SELECT *, #i := #i + 1 AS rank FROM scores ORDER BY score DESC) AS s2 USING (id);
Method 2:
SELECT *, (SELECT COUNT(1) AS num FROM scores WHERE scores.score > s1.score) + 1 AS rank FROM scores AS s1
ORDER BY rank asc
This will provide duplicate rank values when there are duplicates:
SELECT t.playerid,
t.highscore,
(SELECT COUNT(*)
FROM TABLE x
WHERE x.playerid = t.playerid
AND x.highscore >= t.highscore) AS rank
FROM TABLE t
WHERE t.playerid = ?
IE: If three players have the same score for second place, they'll all have a rank value of two.
This will give a distinct value - three players tied for second place, only one will be ranked as 2nd:
SELECT x.playerid,
x.highscore,
x.rank
FROM (SELECT t.playerid,
t.highscore,
#rownum := #rownum + 1 AS rank
FROM TABLE t
JOIN (SELECT #rownum := 0) r
ORDER BY t.highscore DESC) x
WHERE x.playerid = ?
Here is an example.
You want to store the user's ID when they log in, like so...
$_SESSION['username'] = $usernamefromdb;
$_SESSION['id'] = $userid;
And then you want to open a session on every page on yoru website that you will be pulling dynamic information depending on the $_SESSION['id']
session_start();
Then find the row of data in the datebase according to the userID
$userid = $_SESSION['id'];
$rank_query = "SELECT * FROM table_name WHERE id='$userid'";
$rank_result = mysqli_query($cxn, $rank_query) or die("Couldn't execute query.");
$row = mysqli_fetch_assoc($rank_result)
Then using PHP, declare the nth postiion as a variable. And pull the total amount of rows from the DB
$rank = $row['rank'];
$all = $numrows = mysqli_num_rows($result);
echo out the players rank.
echo $rank . "out of" . $all;

Categories