Trouble with creating simple MySQL Trigger on Update - php

(Edit: Apologies for the funky formatting. SO was not having my code formatted.)
I feel dumb, but i've been racking my brain for this for longer then I like to admit.
I need a trigger that, when any update to menu_button is made, it updates a field in soa_config to the datetime the update was made (parameterValue is a Varchar). I've tried doing it as simple as setting parameterValue='1', no dice either. Running the update by itself, and the trigger, sans everything, and both work. It's the combination of the two that makes it hard. I get the error
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'END' at line 1".
delimiter |
CREATE TRIGGER imatrigger AFTER UPDATE on `menu_button`
FOR EACH ROW
BEGIN
UPDATE soa_config
SET parameter_value = 'CURRENT_TIMESTAMP'
WHERE parameter_name = last_menu_update_itme
END
|
delimiter ;
I've looked at:
Quick MySQL Trigger Update
Trouble in creating Trigger in MySQL
MYSQL trigger trouble
sql creating a trigger on update
and more googling.

You need a statement delimiter after the WHERE clause and before the END statement
i.e. you should have a semi-colon here: WHERE parameter_name = last_menu_update_itme; <----

Related

PHP / MySQL query stopped working for no apparent reason

I've got a page that alters a large quantity of variables in my MySQL database, and so far they've all worked great, but now all of the queries inside of a single logic-gate have stopped working for no apparent reason.
I've confirmed the following:
- The variable posted and used in the "if" statement of the gate is as it was intended
- The logic gate is triggered as intended (I can echo stuff and etc inside of it).
- The database connection is established, I am successfully running queries of various types before and after this logic gate on the same connection variable.
- The connection user has ALL PRIVILEDGES enabled, the aforementioned queries surrounding this logic gate are using similar functions successfully.
Here's the logic gate:
if (!empty($_POST["addqual"])){
$coladqual = $_POST["addqual"];
$sqlf = "ALTER TABLE users ADD UNIQUE ('$coladqual') INT( 2 ) NOT NULL";
$conn->query($sqlf);
$sqlc = "INSERT INTO competencebonus (competence,bonus)
VALUES ($coladqual,0)";
$conn->query($sqlc);
}
I've tried multiple alterations, but they don't seem to execute no matter what I do. I've got at least 20 other queries in other logic gates before and after these two and there seems to be virtually no difference between them, apart from these two just not working at all.
EDIT - Here's the error (Thanks to all of you who provided me with the error report syntax)
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''TestAA') INT( 2 ) NOT NULL UNIQUE' at line 1
What strikes me as odd is that only the closing parenthesis is around the post input (TestAA). Is it supposed to have both or neither?
I tried changing the syntax and got the following error:
Duplicate entry '0' for key 'TestAB'
The syntax was:
$sqlf = "ALTER TABLE users ADD `$coladqual` INT( 2 ) NOT NULL UNIQUE";
FINAL EDIT:
Made it work. Deleted the "NOT NULL" statement as recommended by Jeff Pucket II. Somehow this combined with the deletion of the parenthesis and use of backticks instead of apostrophe made the thing work.
Thanks for those of you who had the patience to help me with this.
It looks like you're trying to alter an existing table with a unique not null column. I would expect this to fail if any rows already exist in the table, unless your engine imputes zero. Even then this would fail if there were more than one record because of the unique constraint. Also make sure that the column name being added doesn't already exist.
To get the error using MySQLi, try:
$result = $conn->query($sqlf) or die($conn->error);
The 'unique' constraint should go at the end of your query
$sqlf = "ALTER TABLE users ADD ('$coladqual') INT( 2 ) NOT NULL UNIQUE";
Error checking depends on what flavor of MySQL you're running

Error creating a trigger MYSQL PHPMyadmin

Hi this is my first Question here so I'm just posting some of my code here if you need some more information on the problem please ask.
I'm trying to create a trigger is MYSQL via PHPMyadmin (yes I know not the best tool).
The idea is to be able to clean a string before the insert query executes. Simple enough.
My code:
CREATE TRIGGER `CLEAR` BEFORE INSERT ON `TABLE`
FOR EACH ROW BEGIN
SET NEW.LNAME = REPLACE(NEW.LNAME,'?','');
END;
However I keep getting this error message
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3
I have no idea why. any ideas are welcome thanks before hand.
Also excuse my not so good ise of the english language, I'm not a native speaker.
You've got to change the DELIMITER before the CREATE statement and set it back afterwards:
DELIMITER |
CREATE TRIGGER `CLEAR` BEFORE INSERT ON `TABLE`
FOR EACH ROW BEGIN
SET NEW.LNAME = REPLACE(NEW.LNAME,'?','');
END |
DELIMITER ;
otherwise you could write your trigger so it needs no delimiter:
CREATE TRIGGER `CLEAR` BEFORE INSERT ON `TABLE`
FOR EACH ROW
SET NEW.LNAME = REPLACE(NEW.LNAME,'?','')
Because there's only one statement executed in the trigger body, you don't have to enclose it in a BEGIN... END block and have no need of the semicolon to enc the statement too.

Stumped on why MySQL won't accept my query?

Okay, so I'm currently using mysqli_real_escape_string to escape my SQL queries before sending them to MySQL via PHP. Yet, for some reason my queries aren't processing, and when I outputted the MySQL query and pasted it in to PHPMyAdmin, it gave the following error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE ind={A$RTkAIqah0J1N$Fqymnud9s5PwnWw2wC.Y02oDo4H3W8QJPoJ$6$KK8UearuUCDH$FQg' at line 1
Now, the following is my query:
INSERT INTO `db`.table(`colheader`) VALUES ('{\"hey\":[\"Hello world\",\"7\\/9\\/2013\"]}') WHERE ind='$6$RTkAIqah0J1N$Fqymnud9s5PwnWw2wC.Y02oDo4H3W8QJPoJ$6$KK8UearuUCDH$FQgSnLHIlkBOtDTzu9AuZIZTr6GS4Rzr.iW11041994'
Now, I know that the string assigned to 'ind' has some issues, but I tried putting a slash before every period and every dollar sign and it still doesn't work. I tried putting the whole thing in double quotes, even brackets. Nothing. Could anyone point out what I'm clearly missing? I've looked at the documentation and can't seem to find anything. Thank you in advance!!
WHERE serves to filter which records will be affected or retrieved by your query, and INSERT servers to append a whole new record to a table.
An INSERT can never affect existing records, therefore its nonsense to have a WHERE clause. INSERT does not support WHERE.
If you are trying to edit the value of a field on an existing record, use UPDATE instead.
Take a look at the MySQL Reference Manual for details about its usage.
if your trying to make an update to the specified index use
UPDATE `db`.table SET `colheader` = '{\"hey\":[\"Hello world\",\"7\\/9\\/2013\"]}' WHERE ind='$6$RTkAIqah0J1N$Fqymnud9s5PwnWw2wC.Y02oDo4H3W8QJPoJ$6$KK8UearuUCDH$FQgSnLHIlkBOtDTzu9AuZIZTr6GS4Rzr.iW11041994'

Using PHP to run queries that use stored procs and transactions in SQL Server is causing mysterious errors

This is just the strangest thing and I'm not sure why or what is happening. Everything runs fine in SQL Server but results in errors when ran in PHP.
In PHP, I build a dynamic statement that contains one to many queries or statements. It looks like this:
begin try
begin transaction
-- statement 1
UPDATE table_name SET status = 1 WHERE things='stuff';
-- dynamic: to run after inserts
exec [dbo].[SP_TEST_2];
exec [dbo].[SP_TEST_3];
exec [dbo].[SP_TEST_9];
exec [dbo].[SP_TEST_14];
commit
select 'successful' as for_php_success_message
end try
begin catch
rollback
select error_number() as for_php_error_number
,error_severity() as for_php_error_severity
,error_state() as for_php_error_state
,error_procedure() as for_php_error_procedure
,error_line() as for_php_error_line
,error_message() as for_php_error_message;
end catch
This morning, someone came to me because the front page to all of this was throwing errors at them. Warning: mssql_query() [function.mssql-query]: message: The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION. This code has been untouched for several months and hasn't had any problems. The code in the stored procedures probably has changed since then.
I copied the code over to SQL Server Management Studio to test and everything ran fine from a direct copy and paste. No errors, no warnings, just successful.
Next, I looked up transactions online and changed rollback to if ##trancount>0 rollback and this did fix the transaction error; however - I had a new error from PHP:
Array
(
[for_php_error_number] => 50000
[for_php_error_severity] => 16
[for_php_error_state] => 1
[for_php_error_procedure] => SP_TEST_Record
[for_php_error_line] => 247
[for_php_error_message] => spTEST_Record: 515: Cannot insert the value NULL into column 'TEST_DATA', table 'tempdb.dbo.#IDs________________________________________________________________________________________________________________00000001D27E'; column does not allow nulls. INS
)
(still, a reminder: no errors are returned if I run the exact code in SQL Server Mgmt Studio)
The error involves a SP that is called at the end of each of the SP_TEST_# procedures listed in the dynamic query that PHP built. I cannot copy the SP code over to here because this is work stuff and I didn't write them so I'd really prefer to not have to paraphrase them, either, because they are huge and not formatted well. I will however, show the top of SP_TEST_RECORD where the error occurs (which isn't on line 247):
ALTER PROCEDURE [dbo].[SP_TEST_Record] (
#Test_ID real=0, #debug int=1, #create_entry int=0, #autoclose bit=0, #autodelete bit=0
)
AS
BEGIN
SET NOCOUNT ON;
declare #vtest_id real; set #vtest_id=#Test_ID
declare #vdebug int; set #vdebug=#debug
declare #vcreate_entry bit; set #vcreate_entry=#create_entry
declare #vautoclose bit; set #vautoclose=#autoclose
declare #vautodelete bit; set #vautodelete=#autodelete
declare #test_date datetime; set #test_date=getutcdate()
declare #ct int;
begin try
begin tran
if object_id('tempdb..#IDs') is not null drop table #IDs
CREATE TABLE #IDs (TYC_ID int not null, TYC_TYPE_ID int not null, TYC_ENV_ID int not null, TEST_DATA nvarchar(2000) null) ON [PRIMARY]
ALTER TABLE #IDs ADD PRIMARY KEY NONCLUSTERED (TYC_ID, TYC_TYPE_ID, TYC_ENV_ID)
insert into #IDs(TYC_ID, TYC_TYPE_ID, TYC_ENV_ID, TEST_DATA)
select TYC_ID, TYC_TYPE_ID, TYC_ENV_ID, TEST_DATA from SR_TESTING where TEST_ID=#vTest_ID
So - one thing I know... some how, my PHP transaction was being ended by something in one of the stored procedures that was called by the dynamic statement and that is cause of the transaction issue. There are transactions inside of those stored procedures.
But why don't I see the null insert error in SQL Server when I run the same exact code? If there's a null insert, there's a null insert... so why would it make a difference if it was called from PHP or not?
And less importantly, how was my transaction being ended by one of the stored procedures in the beginning?
Why was thetransaction ended by the SP's when the code was ran in PHP but not when it was ran in SQL Server?
Is there some execution-concurrency-order of operations-transaction hierarchy-something going on?
I didn't want to straight delete this question because it was, at the very least, a great learning experience for me. However, it was a very localized question. I figured out the answer a while ago so I can't remember the specifics...
It was definitely caused because of something happening in one of the stored procedures that were being called down the line. I was very surprised to find out that the error bubbled up that way, especially with the PHP. I guess error scope kind of played a part in it... the PHP took the first error it saw but running the code in SQL server allowed it to fail more gracefully (so I didn't see the error there). Dunno. Troubleshooting... when in doubt - go deeper, lol...

MySQLi prepared statements and REPLACE INTO

I have to following code:
http://www.nomorepasting.com/getpaste.php?pasteid=22987
If PHPSESSID is not already in the table the REPLACE INTO query works just fine, however if PHPSESSID exists the call to execute succeeds but sqlstate is set to 'HY000' which isn't very helpful and $_mysqli_session_write->errno and
$_mysqli_session_write->error are both empty and the data column doesn't update.
I am fairly certain that the problem is in my script somewhere, as manually executing the REPLACE INTO from mysql works fine regardless of whether of not the PHPSESSID is in the table.
Why are you trying to doing your prepare in the session open function? I don't believe the write function is called more then once during a session, so preparing it in the open doesn't do much for you, you might as well do that in your session write.
Anyway I believe you need some whitespace after the table name, and before the column list. Without the whitespace I believe mysql would act as if you where trying to call the non-existent function named session().
REPLACE INTO session (phpsessid, data) VALUES(?, ?)
MySQL sees no difference between
'COUNT ()' and 'COUNT()'
Interesting, when I run the below in the mysql CLI I seem to get a different result.
mysql> select count (*);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*)' at line 1
mysql> select count(*);
+----------+
| count(*) |
+----------+
| 1 |
+----------+
1 row in set (0.00 sec)
REPLACE INTO executes 2 queries: first a DELETE then an INSERT INTO.
(So a new auto_increment is "By Design")
I'm also using the REPLACE INTO for my database sessions, but I'm using the MySQLi->query() in combination with MySQLI->real_escape_string() in stead of a MySQLi->prepare()
So as it turns out there are other issues with using REPLACE that I was not aware of:
Bug #10795: REPLACE reallocates new AUTO_INCREMENT (Which according to the comments is not actually a bug but the 'expected' behaviour)
As a result my id field keeps getting incremented so the better solution is to use something along the lines of:
INSERT INTO session(phpsessid, data) VALUES('{$id}', '{$data}')
ON DUPLICATE KEY UPDATE data='{$data}'
This also prevents any foreign key constraints from breaking and potential causing data integrity problems.

Categories