MySQL Transaction - BEGIN Issues - php

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 )

Related

SQL, how to get the automated ID from the previous INSERT?

I am using PHP and SQL and trying to insert user data into two tables upon registration. First in the user_table and second into the character_table. I'm using an automatically generating user_id to link the tables and need to get the value of the user_id from the first INSERT (into user_table) then add it to a column in the character_table.
I tried a few methods and here is where I ended ($username, $email, $password and $character are defined above);
$sql = "INSERT INTO
user_table (id, username, email, password)
VALUES ('NULL', '".$username."', '".$email."', '".$password."')
INSERT INTO
character_table (name, id)
VALUES ('".$character."', 'LAST_INSERT_ID()')";"
I want "id" from user_table to match with "id" inserted into character_table.
When I run the above, nothing seems to be happening. Previous attempts I always ended with id = 0. What is the correct way I can get the ID from the first INSERT?
Run your statements seperately. You run your insertion into your user_table, then grab the id then run your insertion into your character_table
You can grab the id using mysql_insert_id after running the insert. Note that on the php webpage detailing the mysql_insert_id function that it is deprecated as is all mysql* functions. Which leads to...
For the love of everything holy don't concatenate your variables directly to your INSERT statement. Switch to mysqli* functions or PDO if you haven't already and use prepared statements (parameterizing the query). If you build an application using mysql it means you are not parameterizing your queries which means you are at a huge risk for a sql injection attack.
If/when you switch over to mysqli or PDO functions you will find an equivalent mysqli_insert_id() (or PDO::lastInsertID()) function

Multiple queries in one php script

So I am trying to send data entered in a single form to multiple tables using multiple queries but it is not working. I have the connection thing working right and this way it works fine for one query but the problem comes when I try to use multiple tables, like getting data and sending it to multiple tables
What I have done so far is:
$qry= "INSERT INTO register VALUES (DEFAULT, '".$email."', '".$passw."')";
$qry = "INSERT INTO personalinformation VALUES (DEFAULT, '".$name."',
'".$fname."', '".$age."', '".$gender."', '".$cnic."',
'".$mobileno."','".$address."', '".$appearencestatus."')";
Kindly help.
Thank you so much
With PDO you'd do something like:
$stmt = $db->prepare("INSERT INTO register (email, password) VALUES (:email, passw)";
$stmt->execute(array('name' => $name, 'email' => $email))
Once for each query. It's important to always specify the columns you're inserting against, it avoids ambiguity when your schema changes for some reason plus the crufty DEFAULT junk in there.
Try to prepare directly from a string, don't make intermediate variables for this sort of stuff. Those can easily get confused, over-written, and tangled up in your code.
Did you create a database connection? And did you execute the query with mysqli_query ? Try troubleshooting by echoing out the composed query, and copy pasting it in mysql console or in php myadmin.
Here is a sample:
$con = mysqli_connect('hostname', 'username', 'password', 'dbname');
Your queries composition code: Then
mysqli_query($con, $queryvariablename);
--
P.S make sure you use different variable names for different queries or else the second one will overrite the previous one.

how to insert data from primary key column to foregin key

i am inserting data from a form i want when i will insert data so the first column primary id which is using in second column as a foreign key should be increased
i have tried this code but not working
first table code
$this->db->query("insert into af_ads (ad_title,ad_pic,ad_description)
values ('$title','$filepath','$description')");
second table code
$this->db->query("insert into af_category (cat_type,ad_id_fk)
values ('$category','ad_id')");
NOTE: i want to insert ad_id into ad_id_fk
Try this:
// Your first query
$this->db->query("insert into af_ads(ad_id, ad_title, ad_pic, ad_description)
values ('', '$title', '$filepath', '$description')");
$ad_id = $this->db->insert_id(); // This returns the id that is automatically assigned to that record
// Use the id as foreign key in your second insert query
$this->db->query("insert into af_category (cat_type,ad_id_fk)
values ('$category', $ad_id)");
MySQL provides the LAST_INSERT_ID function as way to retrieve the value generated for an AUTO_INCREMENT column from the immediately preceding INSERT statement.
A lot of client libraries make this conveniently avaiable (e.g. PDO lastInsertId function.)
(I'm not familiar with CodeIgniter or ActiveRecord, so I can't speak to how that's made available.
Your code looks like it's using the PDO interface... but I'm not sure about that.
# either we need to check return from functions for errors
# or we can have PDO do the checks and throw an exception
$this->db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
# attempt insert which will generate AUTO_INCREMENT value
$this->db->query("INSERT (ad_id, ... ) VALUES (NULL, ...)");
# if previous insert successfully inserted a row (or rows)
$ad_id = $this->db->lastInsertId();
You really need to check whether the previous insert was successful or not. If you aren't going to code that check yourself, then PDO does provide a mechanism that performs this checking automatically, and will throw an exception if a MySQL error occurs.
I've avoided copying your original code, which looks like it's vulnerable to SQL Injection. If you're using PDO, you can make effective use of prepared statements with bind placeholders, rather than including values in the SQL text.

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

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.

get id of last inserted record without using mysql_insert_id()

$sql =
'INSERT INTO customer
(first_name,
last_name,
email,
password,
date_created,
dob,
gender,
customer_type)
VALUES(:first_name,
:last_name,
:email,
:password,
:date_created,
:dob,
:gender,
:customer_type)' . ' SELECT LAST_INSERT_ID()' ;
Can anyone tell me if the syntax is right? I am having problems using mysql_insert_id that is why i am using SELECT LAST_INSERT_ID()
the error message:
mysql_insert_id() [function.mysql-insert-id]: Access denied for user 'ODBC'#'localhost'
It will work if you add the closing ; between the two queries (at least MySQL will accept it, I don't know if PHP will complain). But, as above, it's not very good code and, if you separate it, will be a race condition. Figure out your kinks with mysql_insert_id() and use that like it's designed for.
The SELECT doesn't make sense in the context of the query. Execute a separate query for it.
No, it makes no sense whatever. If you really wanted to do select last_insert_id, you should do it in a separate (indeed, typically the next) statement.
But there's no need to do that as you can do it at the API level. Just call your appropriate function for your API to get the last insert ID instead. There's no need for a separate statement.
Firstly, you need to use a semi-colon to separate two queries, secondly mysql_query won't allow you to execute two queries simultaneously, thirdly the "SELECT LAST_INSERT_ID" might become problematic if you have many concurrent users (collisions may happen). What is your problem with the mysql_insert_id?

Categories