Reputation: 10413
I am using PHP backend, with MySQLi objects to use prepared statements. However, I have a problem, I need a query like:
IF ( SELECT count(*) FROM table <= 3)
INSERT INTO table2 VALUES(5,2)
// dont do anything if (SELECT count(*) FROM table > 3)
It gives a syntax error at the begining and cannot understand what is wrong?
Upvotes: 1
Views: 2350
Reputation: 5376
Let MySQL to do the dirty work, and avoid as much communication with the database as you can.
Go to 19.2. Using Stored Routines (Procedures and Functions) and learn those tricks similar to PL/SQL. You will find much more easier to get through problems, when you have multiple queries, which depend on each other.
After some learning you will be able to write a stored procedure, that checks for a logical expression before inserting into a table.
Something like that (syntax maybe out of control here - just example):
CREATE PROCEDURE myProcedure(IN myCap INT)
BEGIN
DECLARE rowCount INT;
SELECT count(*) FROM table INTO rowCount;
IF rowCount <= myCap THEN
INSERT INTO [...]
END IF;
END;
Upvotes: 3
Reputation: 146269
$query = mysql_query('SELECT COUNT(*) AS num FROM `myTable`');
$row = mysql_fetch_assoc($query);
$total = $row['num'];
if($total <= 3)
{
// Insert statament
}
Upvotes: 3