Need an alternate solution instead of calling PHP code from a trigger - php

I am having two table consider table1 and table2. I need to do a trigger after inserting into table1.
Trigger has to do some thing like retrieving data from two other tables using select query (it retrieves more than one row) do some calculations with the data retrieved and then it need to insert it into table2 as single row.
I think it's not possible to do these with in a trigger, so I decided to call a php file from that trigger which does all those things. But some persons says calling php from a trigger is not practically good and it has some security risk.

A Simple Example will help you out.
$sql="INSERT INTO `table1` (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";
$result = mysql_query($sql) ;
if($result)
{
// Record successfully inserted , place your code which needs to be executed after successful insertion
}
else
{
// Insertion failed
}
I assume you would be using mysqli and not mysql becuase mysql_query is deprecated as of PHP 5.5.0 but this is just an example to help you understand the logic.

Ok got you .. In this case you need to create a TRIGGER something like this.
CREATE
TRIGGER `event_name` BEFORE/AFTER INSERT/UPDATE/DELETE
ON `database`.`table`
FOR EACH ROW BEGIN
-- trigger body
-- this code is applied to every
-- inserted/updated/deleted row
END;
This Question has already been answered check the link below.
MySQL trigger On Insert/Update events
Hope this helps.

Related

SQL Injection using PHP multi_query to DROP TABLE

I am trying to drop a table within a database using SQL injection through PHP.
The PHP code submits a form to the Database with the following command and multi_query($sql):
$sql = "INSERT INTO Student (StdNumber, FName, LName, DOB, PhoneNumber)
VALUES ('$input1', '$input2', '$input3', '$input4', '$input5')";
So I thought, I can SQL Inject input5. So I use:
');"; $sql .= "DROP TABLE IF EXISTS Student;";-- -
This closes the previous sql statement, then I start another statement with 'sql .=' and then I comment off the rest of it with -- -
However the table isn't dropping. I am not seeing my injection command within input5 (PhoneNumber) in the database, so it is successfully closing the previous statement I would believe.
So I am not sure what is wrong, am I using multi_query incorrectly? or is my injection incorrect?
Thank you
Edit 1:
Additionally, when I submit the form it accepts it and makes another entry into the database.
You are trying to manipulate the sql that is generated by the php, not the php itself.
So you should not add php to your 5th input:
');"; $sql .= "DROP TABLE IF EXISTS Student;";-- -
should be something like:
1234567890'); DROP TABLE IF EXISTS Student; -- the rest here will be comments in sql

MySQL Transaction - BEGIN Issues

I've never used Transactions before but I want to ensure that when I the data into the database via my HTML Form, that should there be an issue, there is a rollback.
Sounds awesome, but I'm struggling to fully understand the place and use of them in a MySQL Query.
$sql = "BEGIN
/* Insert the user to the WordPress Database */
INSERT INTO wp_users (user_login, user_pass, user_email)
VALUES ('John', 'Doe', 'john#example.com');
/* Insert the user into our Custom Database */
INSERT INTO users (ID, name)
VALUES (LAST_INSERT_ID(), 'John')
COMMIT";
I've edited some of the code to be easier to read, and I know for example the password isn't secure, but am I doing something wrong with the BEGIN & COMMIT functions for the Transaction?
I'm also trying to use Transactions so that I can make full use of the LAST_INSERT_ID() function. This should then allow me to ensure that between both Databases, the user will share the same ID so I can easily call upon their unique data for various website application reasons.
I've found a few things online, but none really provide an easily understood example. What exactly am I doing wrong? Is my implementation terrible, or am I just missing something? Is the LAST_INSERT_ID() going to work like that?
I'd greatly appreciate any help you can offer. Thank you.
You might use PDO for handling transaction in php. Refer here
For last inserted row id. Refer here
Since you are using Mysqli and you want to rollback if any part of the query failed or commit when queries succeed you can do something like shown in the code below:
( also I assume this part is wrong " INSERT INTO users (ID, name)
VALUES (LAST_INSERT_ID(), 'John') " as you probably want to use "UPDATE" )
//just a temporary variable to store eventual error
$query_ok=true;
//start transaction here
$mysqli->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
$mysqli->query("INSERT INTO wp_users (user_login, user_pass, user_email)
VALUES ('John', 'Doe', 'john#example.com');") ? null : $query_ok=false;
$mysqli->query("UPDATE users SET name ='John' WHERE ID=".$mysqli->insert_id ) ? null : $query_ok=false;
//if $query_ok is still set to true then we commit changes to database otherwise we do rollback
$query_ok ? $mysqli->commit() : $mysqli->rollback();
You can also use procedural style ( mysqli_query, mysqli_insert_id etc )

Conditional Insert in mysql

I am really a beginner in mysql. In oracle we can use triggers , which can detect the insert elements and allows to fully break the insert command if something is wrong. I've found that mysql also supports triggers, but how can we use them for detecting insert parameters and stopping them to be inserted if they don't satisfy rules.
e.g. INSERT INTO accounts (userId, balance) VALUES ('12','450'); // Valid
INSERT INTO accounts (userId, balance) VALUES ('12','-574'); // Invalid
if(balance<0){
Do not insert;
}
else{
Insert;
}
NOTE: I'm dealing with concurrent transactions, so STRICTLY need triggers, i.e. lowest level error detection so that no one can hack.
Any help will be appreciated. Thanks,
Or use an BEFORE INSERT trigger
DELIMITER $$
CREATE TRIGGER au_a_each BEFORE INSERT ON accounts FOR EACH ROW
BEGIN
IF new.balance > 0 THEN
BEGIN
INSERT INTO b (id,balance) VALUES (new.id, new.balance);
END
END $$
DELIMITER ;
More info in the mysql documentation : http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html
PS: Programming lesson number 1(One with capital "o") - Befriend whatever programming/scripting language's documentation
You may use INSERT IGNORE and set ALTER TABLE field constraints in mysql

Fast Insertion in MySQL Table from php

I have to insert 50,000 to 16.000.000 rows in MySQL Table from php. It is taking at least 15-20 min to store in database.
To complete my project i have to do it more faster insertion. do anyone having any flexible opinion.
i am using this code
for($i=$d;$i<=$fd;$i++)
{ $j = $i-$d+1;
$sql1 = "INSERT INTO information(id, redirection, username, pc, date, time,
method,text, http, code, data, request, software) VALUES ('".$i."','"
.$_SESSION["redirection"][$j]."','".$_SESSION["username"]$j]."','"
.$_SESSION["pc"][$j]."','".$_SESSION["date"][$j]."','".
$_SESSION["time"][$j]."','".$_SESSION["method"][$j]."','"
.$_SESSION["text"][$j]."','".$_SESSION["http"][$j]."','"
.$_SESSION["code"][$j]."','".$_SESSION["data"][$j]."','"
.$_SESSION["request"][$j]."','".$_SESSION["software"][$j]."')";
mysql_query($sql1);
}
I agree with Cal. Try this:
$sql1 = "INSERT INTO information(id, redirection, username, pc, date, time,
method,text, http, code, data, request, software) VALUES ";
<?php
for($i=$d;$i<=$fd;$i++)
{
$j = $i-$d+1;
$sql1 .= "('".$i."','"
.$_SESSION["redirection"][$j]."','".$_SESSION["username"]$j]."','"
.$_SESSION["pc"][$j]."','".$_SESSION["date"][$j]."','"
.$_SESSION["time"][$j]."','".$_SESSION["method"][$j]."','"
.$_SESSION["text"][$j]."','".$_SESSION["http"][$j]."','"
.$_SESSION["code"][$j]."','".$_SESSION["data"][$j]."','"
.$_SESSION["request"][$j]."','".$_SESSION["software"][$j]."')";
if($i<=$fd){
$sql1 .= ", ";
}
}
mysql_query($sql1);
?>
In this case you will perform only one insertion instead multiple. Also, as variant, you can store your data into text file (.csv, for example) and then import it into your database. But this is exotic method.
Use extended insert syntax to insert multiple rows per statement:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
http://dev.mysql.com/doc/refman/5.5/en/insert.html
Another trick is to disable/delete indexes and enable/add them after all data has been inserted.
DISABLE KEYS;
INSERT ......
ENABLE KEYS;
If the table supports transactions (InnoDB), you can speed up bulk inserts by doing everything inside a single transaction. Query BEGIN TRANSACTION before all the inserts, and COMMIT after you're done.
Obviously, this is irrelevant if your table doesn't support transactions (MyISAM).
Prepared statements are another way to speed up bulk inserts (with added security benefits), but it's difficult to do that in a project that uses mysql_query() everywhere, so I'll leave that out.
You're not really clear what your limits are, and especially WHY. Other answers assume you are on some sort of time-schedule, and need the insert completed before a certain moment
But when we assume you want to have control over your program back as quickly as possible, but not neccesairily need the insert to be finished, you could use delayed inserts?
http://dev.mysql.com/doc/refman/5.5/en/insert-delayed.html
The DELAYED option for the INSERT statement is a MySQL extension to
standard SQL that is very useful if you have clients that cannot or
need not wait for the INSERT to complete. This is a common situation
when you use MySQL for logging and you also periodically run SELECT
and UPDATE statements that take a long time to complete.
When a client uses INSERT DELAYED, it gets an okay from the server at
once, and the row is queued to be inserted when the table is not in
use by any other thread.

how to use mysql update query and mysql insert query together?

this the condition: there is a form in html and php haivng around 120 fields its for a website i am making this form on submitting goes to a php page where i first retrive all the values using $_REQUEST[]and then using insert query insert all of them in their specific coloums in the same table in my mysql database. Now i will have to do all the process again for updating these values. Becuase syntax for insert query and update query are quite different .
I dont want to write another 100 lines of code . Is there any way to use the code i wrote inside my insert query to use to update the data.?
Actually in MySQL there is an alternative syntax for insert that is very similar to the syntax for update. You can write
insert customer set customerid=12345, firstname='Fred', lastname='Jones
etc.
Personally I prefer this syntax because it's easy to see what value is going into each field. This is especially true on records with long lists of fields.
On the minus side, it's not standard SQL, so if you ever decide to port your app to a different database engine, all your inserts would have to be rewritten.
Another option I've occasionally used is to write a little function to create your insert and update statements. Then the syntax of your function can be the same, no matter how different the generated code is.
Another alternative, and depending on requirements and keys, you could use:
replace into tbl (<cols>) values (<vals>)
which will insert if not exist, or replace based on keys (insert/update in one query)
or if you are only inserting and don't want to insert twice, you could use:
insert ignore into tbl (<cols>) values (<vals>)
where if the record is already inserted based on keys, it is gracefully ignored
for more info http://dev.mysql.com/doc/refman/5.0/en/replace.html
There is a quite similar syntax for INSERT and UPDATE:
INSERT INTO <table> SET
column1 = value1,
column2 = value2,
...
;
UPDATE <table> SET
column1 = value1,
column2 = value2,
...
WHERE <condition>
;
INSERT INTO yourtable (field1, field2, field3, ...)
VALUES ($field1, $field2, $field3, ...)
ON DUPLICATE KEY UPDATE field1=VALUES(field1), field2=VALUES(field2), etc...
Details on this construct here.

Categories