looping a php script to insert data for multiple users - php

I have two tables: phpbb_sn_fms_groups and phpbb_fms_user_groups, which I would like to INSERT into using the two queries below, however the first problem is I can't possibly manually run the two queries ~1000 times for each user_id (56 through 1060). The second problem is I need to INSERT the auto incremented fms_gid from the first query (table: phpbb_sn_fms_groups) into fms_id from the second query (table: phpbb_sn_fms_users_group) when the php script INSERTs each user_id.
// user_id: 56 through 1060
// fms_gid in the table phpbb_sn_fms_users_group needs the unique fms_gid for each row from the table phpbb_sn_fms_groups because it doesn't autoincrement.
$result = mysql_query("INSERT INTO phpbb_sn_fms_groups (fms_gid, user_id, fms_name, fms_clean, fms_collapse) VALUES ('autoincrementednumberthatdoesntneedtobeinserted', '56', 'Staff', 'staff', '0')")
or die(mysql_error());
$result = mysql_query("INSERT INTO phpbb_sn_fms_users_group (fms_gid, user_id, owner_id) VALUES ('inserttheautoincrementednumberfromfms_gidinphpbb_sn_fms_groups', '2', '56')")
or die(mysql_error());
Any help would be appreciated. Thanks!

This is a great time for PDO.
See http://php.net/manual/en/book.pdo.php for connection info but something like
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
// First select the users you need query.
$stmt = $pdo->prepare("SELECT id, name FROM users WHERE id BETWEEN 56 AND 1060");
$stmt->execute();
$result = $stmt->fetchAll();
OR if literally 56 through 1060 you can use a for loop.
Then loop through those results to execute
foreach($result as $row) {
$stmt1 = $pdo->prepare("INSERT INTO phpbb_sn_fms_groups (fms_gid, user_id, fms_name, fms_clean, fms_collapse) VALUES ('autoincrementednumberthatdoesntneedtobeinserted', :user_id , 'Staff', 'staff', '0')");
$stmt1->bindParam(":user_id", $row['id']);
$stmt1->execute();
//get last inserted id.
$inserted_id = $pdo->lastInsertId();
$stmt2 = $pdo->prepare("INSERT INTO phpbb_sn_fms_users_group (fms_gid, user_id, owner_id) VALUES (:last_id, '2', :user_id)");
$stmt2->bindParam(":last_id", $inserted_id);
$stmt2->bindParam(":user_id", $row['id']);
$stmt2->execute();
}
Hope this gets you started. Can also be done in mysqli. Don't want to jump into that debate. I just like naming the parameters for binding.

Related

MySQL INSERT with a field coming from another table fails

I Need to insert data in a table but 1 of the fields will come from another table but not working...
Code as below:
//Save payment to table paylog
$sql = "INSERT INTO `paylog`(`payment_id`, `date_approved`, `newcredit`, `before`) VALUES (?,?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssss',$payment->id,$dateApproved,
$payment->transaction_amount,(SELECT credit from tokens WHERE token=$payment->external_reference LIMIT 1));
$stmt->execute();
$stmt->close();
Assistance welcome
Paulo
Just move that SELECT subquery up inside of $sql, keep $payment->external_reference as a binded parameter.
See https://stackoverflow.com/a/42132551/7977859

PHP - SQL how to select ids from table and insert into another table?

I need to do an inner join with the insert into statement. I need to insert data into 2 tables but the id of the records from the second table should also be stored into a column from the first table.
the first sql section makes a new record for every given dj name in the dj table, the second part is supposed to get the id from the added dj and insert it into a column from table "articles".
$alle_djs = explode(', ', $this->djs);
foreach ($alle_djs as $elke_dj) {
$sql = "INSERT INTO dj (name) VALUES ( :name_dj )";
$st = $conn->prepare($sql);
$st->bindValue( ":name_dj", $elke_dj, PDO::PARAM_STR );
$st->execute();
$sql2 = "INSERT INTO articles (dj_ids) SELECT id FROM dj WHERE name=:name_dj";
$st2 = $conn->prepare($sql2);
$st2->bindValue( ":name_dj", $elke_dj, PDO::PARAM_STR );
$st2->execute();
}
$conn = null
Use the LAST_INSERT_ID() function:
$sql2 = "INSERT INTO articles(dj_ids) VALUES (LAST_INSERT_ID())";

PDO lastInsertId in the same query

Hello so I have a table named tblcontactlist and have 5 columns (contactID, contactName, contactEmail, contactNumber, hashed_id) and this is my working query
$query = "INSERT INTO tblcontactlist (contactName, contactEmail, contactNumber) VALUES (:cname, :cea, :cnum)";
$stmt = $dbc->prepare($query);
$stmt->bindParam(':cname', $contactName);
$stmt->bindParam(':cea', $emailAdd);
$stmt->bindParam(':cnum', $contactNumber);
$stmt->execute();
$last_id = $dbc->lastInsertId('contactID');
$hashed_id = sha1($last_id);
$query2 = "UPDATE tblcontactlist SET hashed_id=:hid WHERE contactID=:cid";
$stmt2 = $dbc->prepare($query2);
$stmt2->bindParam(':hid', $hashed_id);
$stmt2->bindParam(':cid', $last_id);
$stmt2->execute();
What this basically does is insert a new record then updates the latest inserted record with a hashed id on the hashed_id column. Is there a proper way of doing this? I mean shorter code or better code. Thanks!
lastInsertId presupposes that you have a previous INSERT beforehand, that you don't have. In this case, lastInsertId is the max contactID. So I would perform a query to get and hash the max contactID and then perform one insert query (and no update).
//fetch Max contactID
$res=$dbc->prepare("SELECT MAX(contactID) FROM tblcontactlist");
$res->execute();
$fetchMax=$res->fetch(PDO::FETCH_NUM);
$last_id=$fetchMax[0];
//hash the max contactID
$hashed_id = sha1($last_id);
//for reusability you can create a function with the above code.
And now perform the insert query:
$query = "INSERT INTO tblcontactlist (contactName, contactEmail, contactNumber, hashed_id) VALUES (:cname, :cea, :cnum, :hid)";
$stmt = $dbc->prepare($query);
$stmt->bindParam(':cname', $contactName);
$stmt->bindParam(':cea', $emailAdd);
$stmt->bindParam(':cnum', $contactNumber);
$stmt->bindParam(':hid', $hashed_id);
$stmt->execute();
Is that better for you?

SQL insert into select issue

So i think i'm close to figuring this out but my query won't add the item from the "pending" table to the "items" table. can you guys help me out with this please. Also if i want it to delete after it gets added should i add the code below the INSERT INTO SELECT query? thanks
action.php:
$sql = "INSERT INTO items (photo,title,description, name) SELECT (photo,title,description, name) FROM pending";
$stmt = $conn->prepare($sql);
$stmt->execute();
Example for delete query after it takes the item from the "pending" into items:
$idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT);
//try deleting record using the record ID we received from POST
$sql = "DELETE FROM pending WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $idToDelete, PDO::PARAM_INT);
$stmt->execute();
I think you are leaving yourself open to mistakes doing it this way.
Consider what would happen if a new row is added to the pending queue after you have issued the INSERT SELECT but before you have started your delete.
I think you need to do this in a more controlled way inside a single loop to make sure you are only deleting what you have copied from pending into items.
$sql = "SELECT photo,title,description, name FROM pending";
$select_pending = $conn->prepare($sql);
$select_pending->execute();
$sql = "INSERT INTO items (photo,title,description, name)
VALUES (:photo,:title,:description, :name)";
$insert_items = $conn->prepare($sql);
$sql = "DELETE FROM pending WHERE id = :id";
$delete_pending = $conn->prepare($sql);
// only if you are using INNODB databases.
//$conn->beginTransaction();
while( $row = $select_pending->fetch_object() ) {
$insert_items->bindParam(':photo', $row->photo, PDO::PARAM_STR);
$insert_items->bindParam(':title', $row->title, PDO::PARAM_STR);
$insert_items->bindParam(':description', $row->description, PDO::PARAM_STR);
$insert_items->bindParam(':name', $row->name, PDO::PARAM_STR);
$insert_items->execute();
$delete_pending->bind_param(':id', $row->id, PDO::PARAM_INT);
$delete_pending->execute();
}
// only if you are using INNODB databases.
//$conn->commit();
$sql = "INSERT INTO items (photo,title,description, name)
SELECT photo,title,description, name FROM pending";
remove the () in the SELECT statement.

Better solution for sequential statement executions with PDO and PHP

I have 3 tables which I have to add a record to them after registration of a new user:
List of Tables:
I. users
... ... ... id (auto_increment, primary)
... ... ... email (email address of new user)
II. blogs
... ... ... id (auto_increment, primary)
... ... ... owner_id (= 'id' in 'users')
III. events
... ... ... id (auto_increment, primary)
... ... ... owner_id (= 'id' in 'users')
... ... ... blog_id (= 'id' in 'blogs')
In this situation I found 2 solutions for adding sequential records:
Solution 1: Using lastInsertId
<?php
try {
// Step 1: add a record to 'users' table and get lastInsertId
$query = $conn->prepare("INSERT INTO users (email) VALUES (:email)");
$query->bindParam(':email', $email);
$query->execute();
$user_id = $conn->lastInsertId();
// Step 2: add a record to 'blogs' table and get lastInsertId
$query = $conn->prepare("INSERT INTO blogs (owner_id) VALUES (:owner)");
$query->bindParam(':owner', $user_id);
$query->execute();
$blog_id = $conn->lastInsertId();
// Step 3: add a record to 'events' table
$query = $conn->prepare("INSERT INTO events (owner_id, blog_id) VALUES (:owner, :blog)");
$query->bindParam(':owner', $user_id);
$query->bindParam(':blog', $blog_id);
$query->execute();
} catch (PDOException $e) {
echo $e->getMessage();
}
?>
Solution 2: Using single execute()
<?php
try {
// Step 1
$query = $conn->prepare("INSERT INTO users (email) VALUES (:email);" .
"INSERT INTO blogs (owner_id) VALUES ((SELECT id FROM users WHERE email = :email));" .
"INSERT INTO events (owner_id, blog_id) VALUES ((SELECT id FROM users WHERE email = :email), (SELECT id FROM blogs WHERE owner_id = (SELECT id FROM users WHERE email = :email)));");
$query->bindParam(':email', $email);
$query->execute();
} catch (PDOException $e) {
echo $e->getMessage();
}
?>
Which solution should I choose for a better performance and security? Is there a better solution for my purpose?
Note: the connection created using PDO:
<?php
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$conn = new PDO("mysql:host=" . App::DB_HOST . ";dbname=" . App::DB_NAME . ";charset=utf8", App::DB_USERNAME, App::DB_PASSWORD, $options);
} catch (PDOException $e) {
echo $e->getMessage();
}
?>
I would use transactions as a modification of 1st option.
$conn->beginTransaction();
try {
// Step 1: add a record to 'users' table and get lastInsertId
$query = $conn->prepare("INSERT INTO users (email) VALUES (:email)");
$query->bindParam(':email', $email);
$query->execute();
$user_id = $conn->lastInsertId();
// Step 2: add a record to 'blogs' table and get lastInsertId
$query = $conn->prepare("INSERT INTO blogs (owner_id) VALUES (:owner)");
$query->bindParam(':owner', $user_id);
$query->execute();
$blog_id = $conn->lastInsertId();
// Step 3: add a record to 'events' table
$query = $conn->prepare("INSERT INTO events (owner_id, blog_id) VALUES (:owner, :blog)");
$query->bindParam(':owner', $user_id);
$query->bindParam(':blog', $blog_id);
$query->execute();
$conn->commit();
}
catch (PDOException $e) {
// roll back transaction
$conn->rollback();
echo $e->getMessage();
die();
}
If you do some benchmarks you will see most time will be lost making the request.
From personal benchmarks on simple queries like this the execution time is very low.
The only thing that realy took time is the initialisation/prepare function.
There for making 3 requests will be slower then creating one large one.
EDIT:
Option 1 is the correct one because you do need to use id's, never link using a string or somethign else allways use id's.
Appart from that 1 (prepared) big query is better then 3x a prepare.
Edit. I misread the question at first, thought you are using exec(), not execute().
So, in fact you can combine both, as lastInsertId is just a PHP wrapper for Mysql's LAST_INSERT_ID()
But, as you need two ids, it will require additional mess with setting a variable. So, I doubt second option would worth, although feasible.
Just note that second would work only if PDO emulation mode is turned off
And surely there is no such question like "performance". Both will go perfectly.

Categories