pass array to sql insert query php - php

i have a sql query to insert data without col names :
$sql = "INSERT INTO test_table VALUES (null,1,2,3) ";
if (mysqli_query($conn, $sql)) {echo 'success!';}else {echo 'failed!';}
I want to insert 1,2,3 as array , something like this:
$data = [1,2,3];
$sql = "INSERT INTO test_table VALUES (null,$data) ";
if (mysqli_query($conn, $sql)) {echo 'success!';}else {echo 'failed!';}
I tried php implode function too, but it didn't worked. Any help will be appreciated. Thank you!

You didn't provide the table structure that it is going into, but if all you are wanting to solve for is having the $data array split into constituent parts you could do it several ways:
a) implode(), although you already mentioned trying it, should work just fine:
$data = [1,2,3];
$sql = "INSERT INTO test_table VALUES (null,".implode(',',$data).")";
b) reference each array index:
$data = [1,2,3];
$sql = "INSERT INTO test_table VALUES (null,{$data[0]},{$data[1]},{$data[2]})";
That only works if you have a set amount of values in the array however.
c) loop over the array:
$data = [1,2,3];
$sql = "INSERT INTO test_table VALUES (null"
foreach($data as $value){ $sql .= ",$value"; }
$sql .= ")";
Hope that helps, if not please provide more details about the structure of both the data going in and the database table so we can better understand the issue.

Related

Multiple Insert Data

I have problem my code not working
I need to write 5 columns
can you explain how to can I use this code right
$val="('".implode("'), ('",$student)."')";
$sql = "INSERT INTO `tbl_student`
(`student_name`) VALUES ".$val.";";
I think this is what you're trying to do:
$val = "('".implode("','", $student)."')";
$keys = "(".implode(",", array_keys($student)).")";
$sql = "INSERT INTO tbl_student ".$keys." VALUES ".$val.";";
Warning: you should make sure your code is not subject to mysql injection. Values coming from the $student array should be sanitized if they comes from user input.

Split array into separate columns in mysql php

I am really new at php/mysql, so I hope you will bear with me!
This code is part of a larger script, but I think it is the crucial parts needed to help me further.
$order_id = $_POST['order_ids'];
$order_ids = implode(",",$order_id);
<input type="text" name="order_ids[]" value="123">
<input type="text" name="order_ids[]" value="456">
$query = "INSERT INTO order_list (id,order_id) VALUES (LAST_INSERT_ID(),'$order_ids')";
I would like to get:
id|order_id
10|123
10|456
Instead of what I get now
id|order_id
10|123, 456
UPDATE
The code from #Ido seems to work out of the box, I have one more field input I would like to add as well to the column which in the table is called "amount" which is similar to the order_id field input.
$order_amount = $_POST['order_amounts_field'];
$order_amounts = implode(",",$order_amount);
I tried copying this and changing with the other one, but soon realized I have to execute both inputs in the same query so as to get them in the same row:
$order_ids = array();
foreach($order_id as $id)
$order_ids[] = "(LAST_INSERT_ID(), '". $id ."')";
$order_ids = implode(", ", $order_ids);
$query = "INSERT INTO order_list (id,order_id) VALUES $order_ids";
$order_ids = array();
foreach($order_id as $id)
$order_ids[] = "(LAST_INSERT_ID(), '". $id ."')";
$order_ids = implode(", ", $order_ids);
$query = "INSERT INTO order_list (id,order_id) VALUES $order_ids";
You're explicitly combining the IDs into a string and inserting one row so the results make sense.
You need to loop through each ID submitted and attach them to a dynamically built INSERT query:
$query = "INSERT INTO order_list (id,order_id) VALUES ";
foreach ($_POST['order_ids'] as $order_id) {
$order_id = (int) $order_id; // sanitize numerical value
$query .= "(LAST_INSERT_ID(), $order_id),";
}
$query = rtrim($sql, ',');
This just illustrates a concept. There are multiple ways to do this. Just be sure you sanitize your data as your sample code is very insecure as it is wide open to SQL injection.
$query = "INSERT INTO order_list (id,order_id) VALUES (LAST_INSERT_ID(),'$order_ids')";
In SQL if you want to insert multiple rows you have to do :
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
See details here
So, in your case :
INSERT INTO order_list (order_id) VALUES (123), (456)
We can avoid increment manually "id" if it's an integer autoincrement and the primary key for this table in your database.
I hope that I have made this clear.
Regards

Running a mysql query multiple times using values from an array in the WHERE clause

I need to run a database query multiple times depending in the User ID. Heres my query:
$query1="INSERT INTO wp_scloyalty (userid, value) VALUES ('XXXXX', '01234')";
I have an array of user ID's from a seperate query shown here:
while($rows=mysql_fetch_array($allresult)){
$birthdays_today[] = $rows['user_id'];
}
echo $birthdays_today[0];
I want the query to run, but there the "userid" = XXXXX in the query, I want that to be populated with a user ID from the array. This means the query must be ran multiple times and each time, the next ID is entered into the query..
Does this make sense?
Thanks :)
MySQL has a bulk insert feature.
$query1="INSERT INTO wp_scloyalty (userid, value) VALUES ('XXXXX', '01234'), ('XXX2', '23234'), ('XXXX3', '3434545')"
<?php
$query = "INSERT INTO wp_scloyalty (userid, value) VALUES ";
$usersToInsert = array();
foreach($birthdays_today as $user_id){
$usersToInsert[] = "($user_id, '01234')";
}
$query .= implode(',', $usersToInsert);
?>
Use a for loop and change out the query with sprintf() and string formatting.
<?php
foreach($birthdays_today as $uid){
mysql_query(); // ...
}
?>
but
<?php
while($rows=mysql_fetch_array($allresult)){
mysql_query(); // use $rows['user_id'] here
}
?>
I will only display the script after your $birthdays_today[] has been populated.
foreach( $birthdays_today as $thisID )
{
mysql_query( "INSERT INTO wp_scloyalty (userid, value) VALUES ('{$thisID}', '01234');" );
}

insert php array into mySql

I am looking for some guidance.
I have a data form field which I am inserting into a table and am looking to association the data with the id's of other relevant data. I was wondering if there was recommended way to insert an array of relevant Id's in relation to the information I am referring too.
Below is what Im thinking...
Eg. php reads
<?php
$name = $_POST['name'];
$info = $_POST['information'];
$id = $_POST['id'];
$family = array();
?>
<?php
$select = "SELECT *
FROM `names_family`
WHERE `name` LIKE '$name'
LIMIT 0 , 30";
$selected = mysql_query($select, $connection);
if(!$selected){
die("Hal 9000 says: Dave the select family name ID query failed " . mysql_error());}
while($row = mysql_fetch_array($selected)){
$familyId = $row[0];
$familyName = $row[1];
array_push($family, $familyName => $familyId);
}
$insertInfo = "INSERT INTO `family_info`.`info`
(`name`, `info`, `family`)
VALUES (
'$name', '$info', '$family');";
$insertedInfo = mysql_query($insertInfo, $connection);
if(!$insertedInfo){
die("Hal 9000 says: Dave the insert info query failed " . mysql_error());}
?>
Is this a recommended way to relate information? Or is another way to achieve the same result?
What data type is the "family" column in MySQL?
I'm pretty sure you can't straight up insert php arrays like that into MySQL.
If it's possible, guess it's one of those things I didn't know because I never even tried.
The easiest way to do this is to encode your php array into a JSON string and decode it back into a php array when you read it.
$family = array();
...
$familyJsonString = json_encode($family);
...
$insertInfo = "INSERT INTO `family_info`.`info`
(`name`, `info`, `family`)
VALUES (
'$name', '$info', '$familyJsonString');";
...
$queryString = "SELECT * FROM family_info WHERE name = '$someName'";
$query = mysql_query($queryString, $connection);
$familyData = mysql_fetch_assoc($query);
$decodedFamilyArray = json_decode($familyData['family']);
where the family column should be a varchar or text type depending on how long the family array gets.
A more robust way to do this is to create a separate table to store your family data and use a MySQL JOIN statement to get the values associated to one entry in the family_info table.
here is some info on joins
Joining two tables without returning unwanted row
http://dev.mysql.com/doc/refman/5.0/en/join.html
there is another way
$family=array()
while($row = mysql_fetch_array($selected)){
$familyId = $row[0];
$familyName = $row[1];
$family[]=$familyName.$familyId;
}
$insertInfo = "INSERT INTO `family_info`.`info`
(`name`, `info`, `family`)
VALUES (
'$name', '$info', '$family');";

how to insert array of data into database

here my code-
$things = mysql_real_escape_string(implode(',', $_POST['things']),$link);
$q = "INSERT INTO tblslider(src) VALUES ('".$things."')";
print_r($q);
$result = $mysqli->query($q) or die(mysqli_error($mysqli));
but my query is getting generated
INSERT INTO tblslider(src) VALUES ('4368122.jpg,5440051.jpg,1047428.jpg') but it should be
INSERT INTO tblslider(src) VALUES ('4368122.jpg'),('5440051.jpg'),('1047428.jpg') thats why it is taking it as one record not three.
You could do:
$things = array_map('mysql_real_escape_string', $_POST['things']);
$q = "INSERT INTO tblslider(src) VALUES ('". implode("'),('", $things)."')";
It generates (with my test data):
INSERT INTO tblslider(src) VALUES ('a.jpg'),('b.jpg'),('c.jpg')
I forgot: Only use functions like mysql_real_escape_string on the real data, not the SQL string. In your example you apply the function on the already concatenated data.
You have imploded things which is now an array, so you need to iterate over this with a foreach loop such as...
foreach ($things as $item) {
$q = "INSERT INTO tblslider(src) VALUES ('".$item."')";
echo '<br />'.$q;
$result = $mysqli->query($q) or die(mysqli_error($mysqli));
}
You could echo $q to make sure you're getting the queries right for each item also.
try this:
$formatVals = function($x){$rx = mysql_real_escape_string($x); return "('$rx')";};
$valString = implode(',', array_map($formatVals, $_POST['things']);
$sql = "INSERT INTO tblslider (src) VALUES $valString";

Categories