Split array into separate columns in mysql php - 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

Related

pass array to sql insert query 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.

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.

How to INSERT in one table and UPDATE in another in single QUERY?

I'm currently creating some sort of inventory system.
I have master_tbl where in I save the items. In master_tbl, I have column qty_left or the available stock left.
I also have the table issuance_tbl where in I save all the transaction in issuing items.
In this table there is issued_qty.
My problem is how can I INSERT a row into issuance_tbl at the same time UPDATE the master_tbl.qty_left. (master_tbl.qty_left - issuance_tbl.issued_qty).
Is it possible?
I think the best way is using Stored Procedure. You can have bunch of SQL statements with error handling and ACID transactions in one place. This is because if your first query executes and the second fails, you may need to rollback transactions. Stored procedures allow all this fancy but reliable stuff.
You can start here: http://forums.mysql.com/read.php?98,358569
I'm not completely confident that 'If there's any way to do such thing':
You need to do it in steps, LIKE THIS:
$result = $this->db->insert($table);//Example function to insert inventory item
$insert_id = $this->db->insert_id();//Example function to get the id of inserted item
if($result)
$res = $this->db->update($id,$data,$table);//Example function to update data of quantity table
if(!$res)
{
$this->db->delete($insert_id,$table);s
$result = '-1';
}
return $result;
Hope this might help
here is the example:
<form method="post">
QTY:<input type="text" name="qty_left"></input>
<input type="submit" name="submit" value="update"></form>
<?php
////////your config db
$qty = $_POST['qty_left'];
if(isset($_POST['submit']);
$sql = mysql_query("insert into issuance_tbl (issued_qty) values (".$qty.") ");
$sql1 = mysql_query("update master_table set qty_left= ".$qty."");
?>
$con = mysqli_connect($host, $user, $password, $database);
...
$issued_qty = '10'; //some value
$insert_query = "insert into issuance_table (issued_qty, ...) values ('$issued_qty', ... ) ;";
$update_query = "update master_tbl set qty_left = (qty_left - ".$issued_qty.") where ....";
mysqli_multi_query($con, $insert_query.$update_query);

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');";

help with multiple queries (PHP/MySQL)

PLease note I am a beginner.
My situation is thus:
I am trying to run multiple queries, off the back of a dynamic form. So the data is going to end up in two different tables.
I am currently successfully storing in to my item_bank, which has an auto_increment itemId.
I then want to grab the ItemId just created on that last query and insert it into my next query of which I am also inserting an array. (I hope you can follow this)
first off, is it even possible for me to run multiple queries like this on a single page?
Below is my attempt at the queries. Currently the first query works, however I cannot get the ItemId generated from that query.
$answers is an array.
// store item structure info into item_bank_tb
$query = "INSERT INTO item_bank_tb (item_type, user_id, unit_id, question_text, item_desc, item_name)
VALUES('$type','$creator','$unit','$text','$desc','$name')";
mysql_query($query) or die(mysql_error());
$itemid = mysql_insert_id();
//now store different answers
$query = "INSERT INTO answers_tb (item_id, text_value)VALUES('$itemid',' . implode(',', $answers) . ')";
mysql_query($query) or die(mysql_error());
this is the error i get now: "Column count doesn't match value count at row 1"
To get the ID generated by an auto-increment field in PHP/MySQL just use the mysql_insert_id() function.
Edit:
// store item structure info into item_bank_tb
$query = "INSERT INTO item_bank_tb (item_type, user_id, unit_id, question_text, item_desc, item_name)
VALUES('$type','$creator','$unit','$text','$desc','$name')";
mysql_query($query) or die(mysql_error());
$itemid = mysql_insert_id();
//now store different answers
$answers = mysql_real_escape_string(implode(',', $answers));
$query = "INSERT INTO answers_tb (item_id, text_value) VALUES('$itemid','$answers')";
mysql_query($query) or die(mysql_error());
Have a look at mysql_insert_id():
// store item structure info into item_bank_tb
mysql_query($query);
$itemid = mysql_insert_id();
// now store different answers

Categories