How do I use php and mysql to create the following trigger for each table created.
I want to convert the following code to be used as a sql query from php.
DELIMITER $$
CREATE TRIGGER trigger1
BEFORE INSERT
ON table1
FOR EACH ROW
BEGIN
SELECT COUNT(*) INTO #cnt FROM table1;
IF #cnt >= 25 THEN
CALL sth();
END IF;
END
$$
DELIMITER ;
I tried to use the following but it does not work.
if ($method == "T")// method is activated if $_GET["method'] = T method is set to T in script to allways return true
{
$sql = "CREATE TRIGGER TRIGGER1
BEFORE INSERT
ON 49a64d6512
FOR EACH ROW
BEGIN
SELECT COUNT(*) INTO #cnt FROM 49a64d6512;
IF #cnt >=25 THEN
CALL sth();
END IF;
END";
echo '1';
}
Is what i am trying to do even possible?
Related
I have a products table stored inside the database which contains info related to the product.I have a stored procedure that gets the rows with maximum quantity.
Whenever i try to call that stored procedure from the php it returns false while when i run the same query in mysql console, it returns me the rows.
PHP Code:
$resVal=$mysqli->query('CALL get_max_quant_rows("'.$company.'","'.$type.'","'.$limit.'")');
$countVal=$resVal->fetch_row();
$countVal=$countVal[0];
$results = $mysqli->query('CALL get_max_quant_rows("'.$company.'","'.$type.'","'.$limit.'")');
var_dump('CALL get_max_quant_rows("'.$company.'","'.$type.'","'.$limit.'")');
var_dump($results);
The ouput of the var_dump of the above queries give me:
string(72) "CALL get_max_quant_rows("1471941595186287666657bc0bdb1c25d","Cakes","1")" bool(false)
I have shown you the var_dump of the query as to show you that the values are going perfectly inside the stored procedure.
When i ran the same query inside the console,it ran and it gave me the results.What could pe the possible reason for this behaviour?
Stored Procedure:
DELIMITER $$
USE `dboxyz`$$
DROP PROCEDURE IF EXISTS `get_max_quant_rows`$$
CREATE PROCEDURE `get_max_quant_rows`(company VARCHAR(8000),product_type VARCHAR(8000),limiter INT)
BEGIN
DECLARE emptyCheckFirst BIT;
DECLARE emptyCheckSecond BIT;
SET emptyCheckFirst=`dboxyz`.isNullOrEmpty(company);
SET emptyCheckSecond=`dboxyz`.isNullOrEmpty(product_type);
IF (emptyCheckFirst=0 AND emptyCheckSecond=0)
THEN
SELECT p1.id,p1.price,p1.product_code,p1.product_name,p1.quantity,p1.amount,p1.companyId FROM products p1
INNER JOIN (SELECT product_code,MAX(quantity) max_quantity FROM products WHERE companyId=company AND `type`=product_type
GROUP BY product_code) p2 ON p1.product_code=p2.product_code AND p1.quantity=p2.max_quantity LIMIT limiter;
END IF;
IF emptyCheckFirst=1 AND emptyCheckSecond=1
THEN
SELECT p1.id,p1.price,p1.product_code,p1.product_name,p1.quantity,p1.amount,p1.companyId FROM products p1
INNER JOIN (SELECT product_code,MAX(quantity) max_quantity FROM products
GROUP BY product_code) p2 ON p1.product_code=p2.product_code AND p1.quantity=p2.max_quantity LIMIT limiter;
END IF;
END$$
DELIMITER ;
Update:
Error given by the DB
Commands out of sync; you can't run this command now
DELIMITER $$
USE `dboxyz`$$
DROP FUNCTION IF EXISTS `isNullOrEmpty`$$
CREATE FUNCTION `isNullOrEmpty`(xx VARCHAR(8000)) RETURNS BIT(1)
BEGIN
DECLARE somevariable VARCHAR(8000);
SET somevariable=xx;
IF (somevariable IS NOT NULL AND LEN(somevariable)>0)
THEN
RETURN 0;
ELSE
RETURN 1;
END IF;
END$$
DELIMITER ;
MySQL stored procedures can return more than one result set, that is the reason to clear all results before do another query using the same connection.
Just use next_result, and do another query:
$results = $mysqli->query("CALL stored_procedure()");
$mysqli->next_result();
$results2 = $mysqli->query("CALL another_stored_procedure()");
I'm trying to get a value from a stored procedure in php but I can't do it.
My stored procedure:
DROP PROCEDURE IF EXISTS sp_table;
DELIMITER $$
CREATE PROCEDURE sp_table()
BEGIN
SELECT COUNT(*) FROM table;
END$$
DELIMITER ;
My PHP code:
$recordSet_table = $conn->query("CALL sp_table()");
print_r($recordSet_table)."<br><br>";
Please try following code.
$sql = mysqli_query($connectionVariable,"CALL sp_table(#count)");
$result = mysqli_fetch_array($sql);
I'm trying to alt WP tables with the function. Mysql code works fine if I call it from mysql client (adds columns), but when I called it via $wpdb->query() it gave me error pointing to DELIMITER line. Upon some googling, I found out that I should use mysqli for this purpose. Now the error log is empty but columns are still not created. Anyone got an idea of what I'm doing wrong? Function code is below
global $wpdb;
$tables=array(
'wp_users',
'wp_usermeta',
'wp_term_taxonomy',
'wp_term_relationships',
'wp_terms',
'wp_taxonomymeta',
'wp_posts',
'wp_postmeta',
'wp_p2p',
'wp_p2pmeta',
'wp_options',
'wp_fb_user_timezone',
'wp_fb_coaching_call_report_team_user',
'wp_fb_coaching_call_report_team',
'wp_fb_3d_notes',
'wp_comments',
'wp_commentmeta',
'wp_coaching_teams_student',
'wp_coaching_teams_coach',
'wp_coaching_teams',
'wp_coaching_call_count'
);
if (is_array($tables)&&count($tables)>0)
{
foreach ($tables as $table)
{
$aaa=mysqli_multi_query($wpdb->dbh,'DELIMITER $$
DROP PROCEDURE IF EXISTS add_createdat_and_updatedat_fields $$
CREATE PROCEDURE add_createdat_and_updatedat_fields()
BEGIN
IF EXISTS(SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema=DATABASE() AND table_name=\''.$table.'\') THEN
IF NOT EXISTS ((SELECT * FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=\''.$table.'\' AND column_name=\'created_at\')) THEN
ALTER TABLE `'.$table.'` ADD `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP;
END IF;
IF NOT EXISTS ((SELECT * FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=\''.$table.'\' AND column_name=\'updated_at\')) THEN
ALTER TABLE `'.$table.'` ADD `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP;
END IF;
END IF;
END $$
CALL add_createdat_and_updatedat_fields() $$
DROP PROCEDURE IF EXISTS add_createdat_and_updatedat_fields $$
DELIMITER;');
}
}
Do not use multiquery, run each command separately with mysqli_query() instead, that way you don't need manipulating separators at all.
hi i am using mysql trigger to update a table on another table's insertion
this trigger works fine
CREATE TRIGGER `update_pupil_subject` AFTER INSERT ON `pupil_marks`
FOR EACH ROW
BEGIN
UPDATE pupil_subjects SET NumberOfStudens = NumberOfStudens + 1 WHERE NEW.SubjectID = SubjectID;
END$$
but this gives an error
CREATE TRIGGER `update_pupil_subject` AFTER INSERT ON `pupil_marks`
FOR EACH ROW
BEGIN
UPDATE pupil_subjects SET NumberOfStudens = NumberOfStudens + 1 , AverageMarks = (SELECT AVG(Marks) FROM pupil_marks WHERE NEW.StudentID = StudentID ) WHERE NEW.SubjectID = SubjectID;
END$$
how to write this correctly , please help . thanks in advance .
Apparently there were problems when sub-queries were used:
Can you try splitting the SQL statement:
DELIMITER $$
CREATE TRIGGER `update_pupil_subject`
AFTER INSERT
ON `pupil_marks`
FOR EACH ROW
BEGIN
DECLARE avg_marks float;
SELECT AVG(Marks)
INTO avg_marks
FROM pupil_marks
WHERE NEW.SubjectID = SubjectID;
UPDATE pupil_subjects
SET NumberOfStudens = NumberOfStudens + 1, AverageMarks = avg_marks
WHERE NEW.SubjectID = SubjectID;
END
$$
Edit: Use
SHOW TRIGGERS WHERE `table` = 'pupil_marks';
to get all triggers defined on pupil_marks. You can't have multiple triggers on an event as all actions can be covered in single trigger.
NOTE: I think AVG(Marks) is for a given subject, so modified trigger definition accordingly.
declare a variable inside the trigger and assign it with the subquery
declare avg_mark integer default 0;
set avg_mark := (SELECT AVG(Marks) FROM pupil_marks WHERE NEW.StudentID = StudentID);
then use the variable "avg_mark" in your update statement...
it may work...
if not then check the delimiter just below phpmyadmin sql box . It should be "$$"
I have created the following stored procedure in mysql...
DELIMITER //
CREATE PROCEDURE GetMember(IN in_memberID int)
BEGIN
SELECT *
FROM Members
WHERE MemberID = in_memberID;
END//
$result = mysql_query("CALL GetMember(".$memberID.")") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo $row['Name'] . "</br>";
}
But when I call it from php it returns all records in the Members table, what am I doing wrong?
EDIT:
When I try to call the query within phpmyadmin I get this error
CALL GetMember(1);
#1312 - PROCEDURE myDb.GetMember can't return a result set in the given context
what version of PHP?
PHP 5.2.3 and PHP 5.2.4 have a bug with procedures:
https://bugs.php.net/bug.php?id=42548
use Database_Name;
DELIMETER $$
DROP PROCEDURE IF EXISTS Proc$$
CREATE PROCEDURE Proc()
BEGIN
DECLARE x INT;
SET x = 1;
WHILE x <= 110000 DO
INSERT INTO Table_Name (word, mean) VALUES ('a', 'a mean');
SET x = x + 1;
END WHILE;
END$$
DELIMITER ;