Insert data array in SQL after searching from another SQL table - php

I have an array $members that contains some ID(maximum 6 in number) from the table users. Using the following code, I loop through each index of $members, search for the details and store them in another array.
foreach($members as $key=>$value){
$res = mysql_query("SELECT id,name,email FROM users WHERE id='$value'");
if ($res === false) {
echo mysql_error();
die;
}
$row = mysql_fetch_assoc($res);
if($row['id'])
{
$members_name[]=$row['name'];//array for name
}
}
Now I want to insert the ID & names that are stored in the array into another TABLE register in the following format:
(The left side are the rows in my TABLE register)
mem_0_id-->$members[0]
mem_0_name-->$members_name[0]
mem_1_id-->$members[1]
mem_1_name-->$members_name[1]
mem_2_id-->$members[2]
mem_2_name-->$members_name[2]
mem_3_id-->$members[3]
mem_3_name-->$members_name[3]
mem_4_id-->$members[4]
mem_4_name-->$members_name[4]
How can I insert in this way? using just a single INSERT statement?

haven't tried this, but here is my answer anyway :)
$query = "INSERT INTO register(id, name) VALUES ($members[0], $members_name[0])";
for($i=1; $i<count($members); $i++)
{
$query .= ", ($members[$i], $members_name[$i])";
}
then try to execute the query..

Do you do anything else with the array, or are you just retrieving it from one table in order to insert it into another?
If so then you can do the whole thing like this.
$memberIds = implode(',', $members); // comma separated list of member ids
$query = "insert into register (id, name) select id, name from users where id in ($memberIds)";
mysql_query($query); // this will select and insert in one go
If you do need to keep the array in memory, then it's still a good idea to get it all out at once
$memberIds = implode(',', $members); // comma separated list of member ids
$query = "select id, name from users where id in ($memberIds)";
$res = mysql_query($query);
while ($row = mysql_fetch_assoc($res)) {
$memberData[] = $row;
}
That's because running a query inside a loop is very bad for performance. Every time you run a query there is an overhead, so getting all the data at once means you pay this overhead once rather than multiple times.
Then you can build a statement to insert multiple rows:
$sql = "insert into register (id, name) values ";
$sql .= "(" . $memberData[0]['id'] . "," . $memberData[0]['name'] . ")";
for($i = 1; $i < count($memberData); $i++) {
$sql .= ",(" . $memberData[$i]['id'] . ",'" . $memberData[$i]['name'] . "')";
}
mysql_query($sql);
It's a bit nasty because of the commas and quotes but if I've done it correctly then if you do
echo $sql;
you should get something like
insert into register (id, name) values (1, 'john'), (2, 'jane'), (3, 'alice');
You can see that the first way, where you select and insert in one statment, is a lot nicer and easier so if you don't do anything else with the array then I highly recommend doing it that way.

Related

how to select id from one table and insert into other table

$select = "SELECT MAX(order_id) FROM `order`";
mysql_query($select);
foreach ($_COOKIE['item'] as $key12 => $value) {
$value22 = explode("__", $value);
$query1 = "INSERT INTO `cart`(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`) VALUES ('',$value22[5],'$select','$value22[3]','$value22[4]')";
$result2 = mysql_query($query1);
The output of this is SELECT MAX(order_id) FROM order, so what is the solution of this selection and insertion of the id
$select="SELECT MAX(order_id) FROM `order`";
$row = mysqli_query($con,$select);
if(mysqli_num_rows($row)>0)
{
while($data = mysqli_fetch_assoc($row))
{
$order_id = $data['order_id'];
}
}
//This way you can fetch data
Then use this while inserting value for order_id in your query as in
$query1="INSERT INTO `cart`(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`) VALUES ('',$value22[5],'$select','$order_id','$value22[4]')";
one another way to find last inserted id from the db connection:
mysql_query('INSERT INTO order(a) VALUES('b'));
$id = mysql_insert_id();
then $id will be last inserted id
Recommendation:
Use only one batch INSERT query. It gives you the opportunity to insert multiple rows at once, e.g. by running only one query. And is a lot faster.
Used method:
Extract maximum of order_id from order and assign to $maxOrderId.
Iterate through cookie items and build corresponding rows
part of the INSERT sql statement. Then add it to the array $insertRowValues.
In the end implode the $insertRowValues array into the batch INSERT statement.
Run the batch INSERT query - only once.
<?php
$select = "SELECT MAX(order_id) FROM `order`";
$maxOrderId = mysql_query($select);
$insertRowValues = array();
foreach ($_COOKIE['item'] as $key12 => $value) {
$value22 = explode("__", $value);
$insertRowValues[] = "('', " . $value22[5] . ", '" . $maxOrderId . "', '" . $value22[3] . "', '" . $value22[4] . "')";
}
$query1 = "INSERT INTO `cart`
(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`)
VALUES " . implode(', ', $insertRowValues);
$result2 = mysql_query($query1);
Other recommendations:
Use mysqli or PDO instead of mysql, because mysql is already removed as of PHP 5.5.0 (see MySQL Library - Introduction);
Use exception handling;
Use prepared statements to avoid MySQL injection.
P.S: I couldn't test anything.
Good luck!

How to store insert array values as separate record

i've one field in mySql table i.e Expanse and another field called Amount.
now i want to break string in expanse and amount field on the basis of ';' and store each as a seperate record such that data in other fields i.e id and name remains unchanged. such that
I am fetching record from orignal table and want to store this desired result in temporary table. while fetching record from orginal table i'm exploding expanse and amount string on the basis on ';'.
$query="SELECT * FROM table";
$result=mysql_query($query);
while ($row=mysql_fetch_array($result))
{
$newid=$row["id"];
$temp=explode(';',$row["expanse"]);
$new=array_unique($temp);
//what to do after this ?
$temp2=explode(';',$row["amount"]);
$new2=array_unique($temp2);
//what to do after this ?
$query2="INSERT INTO table2 (id, $expanse,$amount) VALUES ('$newid','$new',$new2);
$result2=mysql_query($query2);
}
//after this i'll be inserting values in these variables into new temporary table that is having same structure so that my orignal data remain unchanged and new data as my need inserted into temporary table.
Hope you get my question.
You need to iterate threw each record and again iterate threw each ; delimitted values. id and name will be same for each record but expanse and amount will vary. Number of insert queries is depends on number of ; delimitted values
$query="SELECT * FROM table";
$result=mysql_query($query);
while ($row=mysql_fetch_array($result))
{
$id = $row["id"]; // duplicating for each
$name = $row['name']; // duplicating for each
$expance_array = explode(';',$row["expanse"]);
$amount_array = explode(';',$row["amount"]);
/* count of expance_array and amount_array will be same always as per your idea */
for($i=0;$i<count($expance_array);++$i) {
$expanse = $expance_array[$i];
$amount = $amount_array[$i];
/* now insert $id $name $expanse $amount into the table*/
$query2="INSERT INTO table2 (id, name , expanse, amount) VALUES ($id,'$name','$expanse' , $amount");
$result2=mysql_query($query2);
}
}
You will need a separate INSERT for every item in the array.
function getInsertQueries($id, $expanse, $amount){
$insertQueries = array();
$expanses = array_unique(explode(";", $expanse));
$amounts = array_unique(explode(";", $amount));
if(count($expanses) == count($amounts)){
for($i=0;$i<count($expanses);$i++){
$insertQueries[] = "INSERT INTO table2 (id, expanse, amount) VALUES ('$id', '$expanses[$i]', '$amounts[$i]')";
}
}
return $insertQueries;
}
$query="SELECT * FROM table";
$result=mysql_query($query);
while ($row=mysql_fetch_array($result)){
$insertQueries = getInsertQueries($row["id"], $row["expanse"], $row["amount"]);
foreach($insertQueries as $query){
mysqli_query($query);
}
}

Comma-separated values from database

I'm trying to make an associate array to loop through.
Both values I want come from query2 but the second one is a column with numbers from 1-40. When I normally make an combine_array it says that the arrays are not equally long as PHP treats the for example number 10 as two values somehow. But I want to connect the numbers with the names equally.
I've tried the foreach loop but that didn't work out so far.
How can I make such an array?
PS. I need the array to combine with the values from $query to get the Artikelnaam values from another table.
$query = "SELECT * FROM orders WHERE klantnummer = '{$_SESSION['userid']}'";
$query2 ="SELECT Artikelnaam, Artikelnummer FROM products";
$stmt = $db->prepare($query);
$stmt2 = $db->prepare($query2);
$stmt->execute();
$stmt2->execute();
while($row = $stmt2->fetch(PDO::FETCH_ASSOC)) {
$combined = "";
foreach($row["Artikelnummer"] as $row['Artikelnummer'] => $row['Artikelnaam']) {
$combined = $row['Artikelnummer'] . $row['Artikelnaam'] . ",";
echo $combined;

Query a table by one or multiple array values

I am trying to run a query to determine if a column A is true. If its true, get the contents of a different column B (possible array separated by ",") and use those contents to query a different table. My problem is, column B may be one number or may be 10 numbers all separated by "," and I need to query the second table for a column for each of the numbers of the previous query. If someone can help that would be great.
edit: I tried to use the array explode function but can't figure out how to query the next table to include those values.
I picture it being something like
query = select * from table where location = arrayValue[1] or location = arrayValue[2]
Adaptation of Telmo Marques here but improved :
<?php
//Let's say $bcolumn is a string with the values of B column, separated by colons
$bcolumnArray = explode(",", $bcolumn);
array_walk($bcolumnArray, 'htmlentities');
//Build SQL query
$SQL = 'SELECT * FROM table';
if(count($bcolumnArray)){
$SQL.= ' WHERE IN ("'.implode('", "', $vbcolumnArray).'")';
}
//Query your second table here
$Qry = mysql_query($sql);
// Results here :
while($Res = mysql_fetch_assoc($Qry)){
print_r($Res);
}
?>
I would suggest PDO also... take a look : PDO.
Use PHP's explode() function to transform your string into an array.
<?php
//Let's say $bcolumn is a string with the values of B column, separated by colons
$bcolumnArray = explode(",", $bcolumn);
//Build SQL query
$sql = "SELECT * FROM table WHERE ";
for($i=0; $i < count($bcolumnArray); $i++)
{
$sql .= "location = " . $value;
if($i != count($bcolumnArray)-1)
{
$sql .= " or ";
}
}
//Query your second table here
mysql_query($sql);
?>
Documentation: http://php.net/manual/en/function.explode.php

Deleting Database Entries Not in Array

I have an array that grabs checkbox data and posts certain information into the database if the checkbox data isn't a copy of something already in the database. What I would like to know is how can I create a code that scans through the database and finds data that wasn't part of my checkbox data and delete it from the database.
Okay, for example let's say I have values 1,2,3,4 in my database, but in my checkboxes I only get back 1,2,4. I would like a code that scans my database and deletes that value(s) (in this case 3) from the database.
Here is my current code:
foreach($_POST['publish'] as $index => $val){
$matches = mysql_query("SELECT * FROM `$blog_table` WHERE `postID` = '$val");
if (mysql_num_rows($matches) > 0)
{
// do nothing
} else {
$query3 = "insert into `$blog_table`
(`postID`)values
('$val')";
mysql_query($query3);
}
}
Here would be the code I would use with escaped input
if (!empty($_POST['publish']))
{
$inserts = array();
$deletes = array();
foreach ($_POST['publish'] as $val)
{
$deletes[] = intval($val);
$inserts[] = '('.intval($val).')';
}
$delete = "DELETE FROM `".$blog_table."` WHERE postID NOT IN (".implode(',',$deletes).");";
$insert = "INSERT INTO `".$blog_table."` (`postID`) VALUES ".implode(',',$inserts)."";
}
you should use query like this:
delete from table where id NOT in (3)
in php like:
$query = "DELETE FROM `$blog_table` WHERE `postID` NOT IN (" . implode(',', $array) . ")";
For the MySQL query, you can use NOT IN:
DELETE FROM tablename
WHERE col1 NOT IN (1, 2, 4)

Categories