$mysqli->prepare with SQL Transactions - php

I am pretty new to SQL Transactions and tried to execute following statement which did unfortunately not work...
$stmt = $mysqli->prepare("
BEGIN;
INSERT INTO groups (group_name, group_desc, user_id_fk) VALUES ("'.$groupName.'","'.$groupDesc.'","'.$user_id.'");
INSERT INTO group_users (group_id_fk, user_id_fk) VALUES (LAST_INSERT_ID(), "'.$username.'");
COMMIT;
") or trigger_error($mysqli->error, E_USER_ERROR);
$stmt->execute();
$stmt->close();
Is this even possible what I am trying here or is it completely wrong?
I appreciate every response, thank you!

You are using prepare() wrong way. There is absolutely no point in using prepare() if you are adding variables directly in the query.
This is how your queries have to be executed:
$mysqli->query("BEGIN");
$sql = "INSERT INTO groups (group_name, group_desc, user_id_fk) VALUES (?,?,?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("ssi",$groupName,$groupDesc,$user_id);
$stmt->execute();
$sql = "INSERT INTO group_users (group_id_fk, user_id_fk) VALUES (LAST_INSERT_ID(), ?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s",$username);
$stmt->execute();
$mysqli->query("COMMIT");

Related

How to use PHP prepare with zillions of fields of different types

I am inserting data that has VARCHAR, TIMESTAMP and DECIMAL kinds using prepare.
The data is already in the format needed by mySQL.
My problem is this. Suppose I had only 2 items to insert. I would do like this:
$stmt = $mysqli->prepare("INSERT INTO myTable (name, age) VALUES (?, ?)");
$stmt->bind_param("si", $_POST['name'], $_POST['age']);
My problem is the bind part. How do I do the bind when I have to insert 40 columns at once?
I can deal with the prepare part by doing this:
$sql = "INSERT INTO customers ($columns) VALUES ($values)";
$stmt = $mysqli->prepare($sql);
But the next line will result in a ridiculous long line, impossible to understand and very easy to go wrong.
$stmt->bind_param("ssssiidisisssiidiisssidiisidi", ....);
I don't see how I could build that in a loop for example.
How do I do that?
You can pass an array to the mysqli_stmt::bind_param() function as variable arguments with the ... syntax, introduced in PHP 5.6.
$params = ['name', 42];
$stmt = $mysqli->prepare("INSERT INTO myTable (name, age) VALUES (?, ?)");
$stmt->bind_param(str_repeat('s', count($params)), ...$params);
$stmt->execute();
You don't really need to set the data type individually for each column. You can treat them all as 's'.
I know you're asking about mysqli, but I'll just point out that this is easier with PDO:
$params = ['name', 42];
$stmt = $pdo->prepare("INSERT INTO myTable (name, age) VALUES (?, ?)");
$stmt->execute($params);

Inserting into 2 tables PHP with subquery, last insert id, and prepared statement

So, I have problem with inserting data into 2 tables directly using subquery and last insert id.
i have following codes
if (isset($_POST['recipient']))
$recipient = sanitize($_POST['recipient']);
if (isset($_POST['message']))
$message = sanitize($_POST['message']);
$sql = "INSERT INTO message (senderID, message)
VALUES (?,?)";
if ($stmt = mysqli_prepare($connection, $sql)) {
mysqli_stmt_bind_param($stmt, "is", $userID, $message);
mysqli_stmt_execute($stmt);
$newID = mysqli_insert_id($connection);
$sql2 = "INSERT INTO message_recipient (messageID, recipientID)
SELECT ?, userID
from user
where username = $recipient";
if ($stmt2 = mysqli_prepare($connection, $sql)) {
mysqli_stmt_bind_param($stmt2, "ii", $newID, $recipient);
mysqli_stmt_execute($stmt2);
mysqli_stmt_close($stmt2);
}
}
for the $stmt2 ,it works well in phpmyadmin, but without the prepared statement. The first query works well, it can add data, but can't the second. Also, i dont know why the first query will insert 2 data, with first data correct and second false.
Is the way i get last insert id wrong, or my second query is false?
Any help given really appreciated. thank you so much

MySQLi: How to insert into multiple tables with prepared statements

I am in a situation where I need to insert into 2 tables in a query. I've searched around web and could not find solution. What I want to do is insert values in user table & insert values in profile simultaneously. I could do one after the other way but I've read that it is not efficient and is considered as poor coding technique.
Current Code:
$statement = $db->prepare("
BEGIN;
INSERT INTO `user`(`username`, `email`, `password_hashed`, `fname`, `lname`, `dob`, `agreement`, `gender`, `access_token`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);
INSERT INTO `profile_picture`(`owner`) VALUES (LAST_INSERT_ID());
COMMIT;
");
if($statement) {
$statement->bind_param("ssssssiss", $username, $email, $hashedPassword, $fname, $lname, $dob, $agreement, $gender, $access_token);
$statement->execute();
$statement->close();
echo "DONE";
exit();
}
else printf("Error: %s.\n", $db->error);
I had issues with this trying to copy answers like Frank's. The proper way to do it is:
<?php
try {
$db->beginTransaction();
$stmt = $db->prepare("QUERY");
$stmt->execute();
$stmt = $db->prepare("ANOTHER QUERY??");
$stmt->execute();
$db->commit();
}
catch(PDOException $ex) {
//Something went wrong rollback!
$db->rollBack();
echo $ex->getMessage();
}
After the first statement is executed, you can then gain access to the insertID from PHP using the following: $last_id = $db->lastInsertId();
Hope this helps!
Try using mysqli_multi_query, Check this link for example http://blog.ulf-wendel.de/2011/using-mysql-multiple-statements-with-php-mysqli/
Maybe this one can help you: MySQL Insert into multiple tables?
I think you need a statement like this:
BEGIN;
INSERT INTO user(column_a,column_b) VALUES('value_a','value b');
INSERT INTO profile(column_x,column_y) VALUES('value_x','value_y');
COMMIT;
If you need the last id from user table, you can use the LAST_INSERT_ID() function.

Mysqli INSERT with $_POST

I have been ripping my hair for days over this problem so any helpful advice would be appreciated. Calling the following function returns nothing. The POST values are set (They print with echo) and the database let me update and extract with other functions. What am i missing?
Oh yea, all the values are strings.
$stmt = $db->prepare("INSERT INTO content_page (name, layout, page_id) VALUES (?,?,?)");
$stmt->bind_param("sss", $_POST['name'], $_POST['layout'], $_POST['page_id']);
$stmt->execute();
$stmt->close();
At glance, there is nothing wrong with this code (in case you are indeed using mysqli). So, the only way to get to know what is going wrong is to get the error message.
Add this line before connect
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
and make sure you can see PHP errors
Try this
$sql = "INSERT INTO content_page (name, layout, page_id) VALUES (?,?,?)";
if (!$stmt = $db->prepare($sql)) {
die($db->error);
}
$stmt->bind_param("ssi", $_POST['name'], $_POST['layout'], $_POST['page_id']);
if (!$stmt->execute()) {
die($stmt->error);
}
$stmt->close();
Or, if, as you said, all your values are strings (given, they are as well defined as varchars/something similar in your database), you can still bind_param("sss"...
Aren't page_id's integers ? Since the asker first tagged the question as PDO, here is the PDO version :
$stmt = $db->prepare("INSERT INTO content_page (name, layout, page_id) VALUES (:name,:layout,:pid)");
$sth->bindParam(':name', $_POST['name'], PDO::PARAM_STR);
$sth->bindParam(':layout', $_POST['layout'], PDO::PARAM_STR);
$sth->bindParam(':pid', $_POST['page_id'], PDO::PARAM_INT);
$stmt->execute();
Or (MySQLi):
$stmt = $db->prepare("INSERT INTO content_page (name, layout, page_id) VALUES (?,?,?)");
$stmt->bind_param("ssi", $_POST['name'], $_POST['layout'], $_POST['page_id']);
$stmt->execute();
Or (PDO) :
$stmt = $db->prepare("INSERT INTO content_page (name, layout, page_id) VALUES (?,?,?)");
$stmt->execute(array($_POST['name'], $_POST['layout'], $_POST['page_id']));
Here you are:
$name = $_POST['layout'];
$layout = $_POST['layout'];
$page_id= $_POST['page_id'];
$stmt = $db->prepare("INSERT INTO content_page (name, layout, page_id) VALUES ('".$name."','".$layout."','".$page_id."')");

Insert into 2 tables from 1 form. Mysql Transaction?

The user will create an article and submit an image with it.
+The article will go to the articles table.
+The image will go to images table (so that it can be used in other areas of the site).
It has been suggested I use TRANSACTIONS but I am getting errors.
$sql ='BEGIN INSERT INTO articles(article_title, article_text, article_date)
VALUES (?, ?, NOW())
INSERT INTO images(article_id, image_caption)
VALUES(LAST_INSERT_ID(),?);
COMMIT';
$stmt = $conn->stmt_init();
if ($stmt->prepare($sql)) {
$stmt->bind_param('sss', $_POST['article_name'], $_POST['description'], $_POST['image_caption']);
$OK = $stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
$stmt->free_result();
} else{
echo "Failure- article not uploaded";
}
$mysqli->query("START TRANSACTION");
$stmt = $mysqli->prepare('INSERT INTO articles(article_title, article_text, article_date) VALUES (?, ?, NOW())');
$stmt->bind_param('ss', $_POST['article_name'], $_POST['description']);
$stmt->execute();
$stmt = $mysqli->prepare('INSERT INTO images (article_id, image_caption) VALUES(LAST_INSERT_ID(),?)');
$stmt->bind_param('s', $_POST['image_caption']);
$stmt->execute();
$stmt->close();
$mysqli->query("COMMIT");
It looks like you are using PDO (nice!). With PDO, you can get your transactions in an easy way with beginTransaction() and commit()
Your code would look like:
$pdo->beginTransaction();
// .. fire your 'normal' queries.
// .. and yet some more queries
$pdo->commit();
Then, I'd personally write separate INSERT queries in just two separate statements. More readable in my opinion.
Example:
$pdo->beginTransaction();
$first = $pdo->prepare('INSERT INTO table (field, otherField) VALUES(?,?)');
$second = $pdo->prepare('INSERT INTO table (field, otherField) VALUES(?,?)');
$first->execute(array( .. your data (values) .. ));
$second->execute(array( .. your data (values) .. ));
$pdo->commit();
$sql ='START TRANSACTION;
INSERT INTO articles (article_id,article_title, article_text, article_date) VALUES (NULL,?, ?, NOW());
INSERT INTO images (article_id, image_caption) VALUES(LAST_INSERT_ID(),?);
COMMIT;';

Categories