Insert an array to the database like a separate rows - php

Sorry if this is a duplicate, but I can't reached the result using answers in similar questions.
Here is my situation:
I have a table (users_temp) with 1 column - Users_id;
And I have an array of values, for example - $usersIds = [1,2,3,4,5];
I want to Insert this array to my table and create 5 new rows.
I was trying smth like that, but it doesn't work:
$newdata = "'" . implode("','", $usersIds) . "'";
db_query("INSERT INTO db.users_temp (user_id) VALUES ($newdata)");
Can you help me, please?

Assuming that the $userIds field is safe (all INTs) then just amend your implode a touch.
$newdata = implode("),(", $usersIds);
db_query("INSERT INTO db.users_temp (user_id) VALUES ($newdata)");
You might want to add a check that the array has more than 0 elements.

You can do this
$usersIds = [1,2,3,4,5];
foreach ($usersIds as $user_id) {
db_query("INSERT INTO db.users_temp (user_id) VALUES ($user_id)");
}

To insert multiple rows in a single statement:
sql:
insert into users_temp (user_id)
values (?), (?), (?) [...]
php:
$userIds = array(1, 2, 3, 4, 5);
$placeholders = rtrim(str_repeat('(?),', count($userIds)), ',');
$sql = "insert into users_temp (user_id) values ($placeholders)";
$stmt = $pdo->prepare($sql);
$stmt->execute($userIds);
Your code can build up the placeholders string as above.

Related

An easy way to write INSERT INTO table VALUES (value1, value2, ...valueN)

I need to insert values from an array using PHP into my database. The array has 40 positions, each position is a value I have to insert into a table of my database.
I need a quick way to write it down and not write $1,$2,$3 ... $39
I tried:
$query = 'INSERT INTO table VALUES($1,$2, ..... $39)';
$result = pg_query_params($dbh, $s, $a[0]); //$a[0] array with 39 positions
But it's too long to write it down. I have another piece of code where I have 140 positions.
Just build an array range from 1 to the length of the array and add the $ and commas:
$values = '$' . implode(',$', range(1, count($array)));
$query = "INSERT INTO table VALUES($values)";
$result = pg_query_params($dbh, $query, $array);

Pad array values with parentheses to perform insert

I want to have each array value inside a paranthesis
$id = $_POST['id'];
$test2 = array($id);
$id_list = implode(',', $test2);
$sql .= "INSERT INTO tmp (id) VALUES ({$id_list});";
for example: I'm performing an insert so the output of the list should be (5),(10),(15) not '5','10','15'
Any suggestions on how I can insert using an array?
MySQL's extended insert syntax is
INSERT INTO sometable (...fields...) VALUES (value set #1), (value set #2), (value set #3), etc...
Note how each value set is in its own (). You're not doing that. you're just passing a bunch of values in a SINGLE () set, which means you're providing values for fields that are NOT present in the field list.
You need to do
$id_list = '(' . implode('),(', $_POST['id']) . ')';
producing
(5),(10),(15)
instead of
(5, 10, 15)
You also need to realize that you're vulnerable to sql injection attacks.

PHP - Select & Update statement to return and update a multi dimensional array

I have a database that looks like the following
In my database both id & fb_user_id are unique. Id is an auto incremented number.
First i would like to insert a new row for arguments say with the following
$new_first_name = "John";
$new_last_name = "Nolan";
$new_email = "John#Nolan.com";
$new_link_url = "Johns_Link";
$new_signups = 0;
$new_order = $num_rows;
$referred_by = 2;
$new_fb_user_id = 4;
I use this insert statement
$New_Member = mysql_query("INSERT INTO `rotator`.`rotator` (`id`, `fb_user_id`, `first_name`, `last_name`, `email`, `link_url`, `referred_by`, `signups`, `order`) VALUES (NULL, '$new_fb_user_id', '$new_first_name', '$new_last_name', '$new_email', '$new_link_url', '$referred_by', '$new_signups', '$new_order');");
And because the person was referred by fb_user_id number 2 i want to update signups as follows
$update_sponsor_order = mysql_query("UPDATE `rotator`.`signups` = `rotator`.`signups` + 1 WHERE `rotator`.`fb_user_id` = $referred_by;");
This is where i am stuck. Maybe there is a better way to do it than inserting and updating the table as abovee.
What i would like to do now is something like the following select statement but assigning the returned values to a multi dimensional array. Basically i return columns fb_user_id and order where signups is less than 2
$get_link = mysql_query("SELECT `rotator`.`fb_user_id`, `rotator`.`order` FROM `rotator`.`rotator` WHERE `rotator`.`signups` < 2);
Now with my array i want to rotate everything that is in the column order and update the database of what entry is next in line....
Check the following question and replys to see what i am trying to do
Original Question
You're new best friend the pdo class. I know this doesn't exactly answer your question, but if you start using it now, you will thank me later.
Overview here http://www.php.net/manual/en/class.pdostatement.php
And to retreive results: http://php.net/manual/en/pdostatement.fetch.php

Loop into PHP Array, then loop into SQL Insert... or something different... help please

Lets say I have two tables. In table “category_name”, there are fields category_id and category name. In table “category_subscriptions” there are fields userid and category_number.
What I want to be able to do is to insert a row into category_subscriptions for each category_id using the same userid.
Consider “category_name” having the following values: 4, cars, 5, trucks, 6, trains
The ideal output table for “category_subscriptions (for userid=99) would have values: 99,4,99,5,99,6
Rather than use:
INSERT INTO category_subscriptions
VALUES (99,4)
INSERT INTO category_subscriptions
VALUES (99,5)
INSERT INTO category_subscriptions
VALUES (99,6)
I think I should be using a loop, as category.id won’t always be 4,5, &6. I’m just not sure if this is right and am hoping somebody can help. This is part of a plugin for Joomla 1.7/php.
Assuming you have an array $Categories including all your category_id's, you can do:
$user_id = 99;
$Categories = array(4, 5, 6);
$sql = "INSERT INTO category_subscriptions VALUES ";
$i = 0;
foreach ($Categories as $categorie) {
if ($i++) $sql .= ", ";
$sql .= "({$user_id}, {$categorie})";
}
The output of this code is
INSERT INTO category_subscriptions VALUES (99, 4), (99, 5), (99, 6)
Please note, that this builds a single query. You can insert multiple lines with one INSERT statement using VALUES (<line1>), (<line2>) ...
EDIT
If you really want to link your user to every existing category, you can also do it in plain SQL.
INSERT INTO `category_subscriptions` (`userid`, `category_number`)
SELECT 99, `category_id` FROM `category_name`
Maybe something like this :
<?php
$userID = '99';
$catID = array(4,5,6);
foreach($catID as $cid)
{
$value[] = '('.$userID,$cid.')';
}
mysql_query('INSERT INTO category_subscriptions (user_id,category_id) VALUES '.implode(',', $value));
?>
The script above will run mysql query :
INSERT INTO category_subscriptions VALUES (99,4), (99,5), (99,6)

how to add multiple records in mysql using php

how to add multiple records in mysql using php. Is using array the only solution to this problem. Because I tried using array but the record that would be added in the database would look like this:
array
You can use a multivalue insert statement (INSERT... VALUES (record1), (record2) etc)
(see http://dev.mysql.com/doc/refman/5.1/en/insert.html)
This is how you can construct such a statement from array of records
$values = array();
foreach($records_array as $record)
$values[] = sprintf("( '%s' , '%s' )", addslashes($record['name']), addslashes($record['email']));
$sql = "INSERT INTO users(name, email) VALUES " . implode(",", $values);
mysql_query($sql);
You need to go through each member of the array:
foreach($array as $record)
{ ... }
and perform an INSERT query for each member or - better for performance - insert all records in one statement as outlined in user187291's answer.

Categories