I have four Array consisting of some values. I want to insert Array with same index in same row.
Eg:
$product = [Facebook, Twitter];
$sub_product = [Likes, Boost];
$plan = [10k, 20k];
$months = [3,6];
I want table to be some thing like this
+----+----------+-------------+------+--------+
| id | product | sub_product | plan | months |
+----+----------+-------------+------+--------+
| 1 | Facebook | Likes | 10k | 3 |
+----+----------+-------------+------+--------+
| 2 | Twitter | Boost | 20k | 6 |
+----+----------+-------------+------+--------+
What will be the best way to achieve this such that Index of each array falls in same row? I want to insert in HTML table
If you want to execute mysql_query in single shot then
$product = [Facebook, Twitter];
$sub_product = [Likes, Boost];
$plan = [10k, 20k];
$months = [3,6];
$query = 'insert into TABLE (product,sub_product,plan,months) values';
foreach( $product as $index => $col ){
$query .= "( '".$product[$index]."', '".$sub_product[$index]."', '".$plan[$index]."', ".$months[$index]." ),";
}
$query = rtrim( $query, ',');
mysqli_query(mysql_query);
This will be faster than executing multiple mysql_query function in a loop.
Try This Code,
foreach($product as $key=>$p){
$data = array(
'product'=>$p,
'sub_product'=>$sub_product[$key],
'plan'=>$plan[$key],
'months'=>$months[$key]
);
//Code to insert this array to Database
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql = "INSERT INTO `table`('product','sub_product',...) VALUES ($data['product'],$data['sub_product'],...)";
mysqli_close($conn);
//OR If you are using Codeigniter,
$this->db->insert('table',$data);
}
this code should work,
$product = array("Facebook", "Twitter");
$sub_product = array("Likes", "Boost");
$plan = array("10k", "20k");
$months = array(3,6);
for($i=0;$i<count($product);$i++){
$product_name=$product[$i];
$sub_product_name=$sub_product[$i];
$plan_name=$plan[$i];
$month_no=$months[$i];
echo "insert into table_name (product_name, sub_product_name, plan_name, month_no) values ('$product_name', '$sub_product_name', '$plan_name', '$month_no')";
echo "<br>";
}
Thanks
Amit
Assuming all arrays have the same length and $mysqli is a connection to your database,
for ($i=0; $i < count($product); $i++) {
$query = "INSERT INTO your_table (id, product, sub_product, plan, months)";
$query .= " VALUES ('$i', '{$product[$i]}', '{$sub_product[$i]}', '{$plan[$i]}', '{$months[$i]}')";
$mysqli->query($query);
}
Assuming that the size of all the above arrays are same at a given point of time and their indexing is consistent you can use the following code:
<?php
$product = array('Facebook', 'Twitter');
$sub_product = array('Likes', 'Boost');
$plan = array('10k', '20k');
$months = array(3,6);
/* Connected to a mysql Database */
$i = 0; //initialize a counter
while($i < sizeof($product)) //Run the loop (Twice in this case)
{
//Store the current iteration value in variables
$current_product = $product[$i];
$current_sub_product = $sub_product[$i];
$current_plan = $plan[$i];
$current_months = $months[$i];
//Prepare the SQL statement
$sql = <<<EOD
INSERT INTO table_product(product,subproduct,plan,months)
VALUES ('$current_product','$current_sub_product','$current_plan',$current_months)
EOD;
$i++;
echo $sql . "<br />";
}
?>
Do on this way simple:
$count = count($product);
$index=0;
while($index<$count){
//do your stuff here i.e. insert query
$sql = "INSERT INTO your_table SET product='".$product[$index]."', sub_product='".$sub_product[$index]."', plan='".$plan[$index]."', months='".$months[$index]."' ";
mysql_query($sql);
$index++;
}
Related
I have struggled with this concept for a while and am hoping someone can help, please. I can query database records if all values are stored in one row. The challenge I have is when the quantity values are stored on multiple rows but with a common key (e.g. order_id). I want to store into an array and then assign each value to an on-screen variable to allow user updates so that I can update the table again.
For example, if the table looks as follows:
id line part qty
-- ---- ---- ---
1 1 63 2
1 2 104 3
1 3 54 2
1 4 50 1
I have not had success with the following where I establish the number of rows and then try to build a foreach loop to capture the data:
$sql = 'SELECT *, COUNT(*) as $count FROM Order_Items where order_id = ?';
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
for ($x = 0; $x <= $count; $x++ {
$var($x) = $data['qty'];
}
If I can properly separate the values into an array and then reference them somehow, then I could do the following and get them displayed and easily update back to the database:
$var_1 = $data['63']; // part_id = 63
$var_2 = $data['104']; // part_id = 104
$var_3 = $data['54']; // part_id = 54
$var_4 = $data['50']; // part_id = 50
Change this:
$sql = 'SELECT *, COUNT(*) as $count FROM Order_Items where order_id = ?';
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
for ($x = 0; $x <= $count; $x++ {
$var($x) = $data['qty'];
}
To something that makes sense like this
$sql = 'SELECT * FROM Order_Items where order_id = ?';
$q = $pdo->prepare($sql);
$q->execute(array($id));
while(false !== ($row = $q->fetch(PDO::FETCH_ASSOC))){
echo $row['qty'];
};
UPDATE
$sql = 'SELECT * FROM Order_Items where order_id = ?';
$q = $pdo->prepare($sql);
$q->execute(array($id));
$array = [];
while(false !== ($row = $q->fetch(PDO::FETCH_ASSOC))){
$array['line_'.$row['line']] = $row;
};
UPDATE
The additional code that answers what I was looking for is as follows. Your answer was key to my understanding it all:
$sql = 'SELECT * FROM Order_Items where order_id = ?';
$q = $pdo->prepare($sql);
$q->execute(array($id));
$array = [];
while(false !== ($row = $q->fetch(PDO::FETCH_ASSOC))){
$qty['line_'.$row['line']] = $row['qty'];
};
$var_54 = $qty['line_54'];
$var_63 = $qty['line_63'];
I want to find a value from a column which has multiple values like (23,24,25), Using php mysqli query.
Table:
+-----------------+
id | tag_ids |
+-----------------+
1 | 3,4,5 |
2 | 3,7,8,9 |
3 | 4,5,10 |
Curent query:
$value = '3';
$query = "SELECT tag_ids FROM table WHERE FIND_IN_SET($value, tag_ids)";
$result = mysqli_query($query);
$count = mysqli_num_rows($result);
echo count;
Result will be: YES/NO or 1/0, if the Given value is match any value with tag_ids.
I found the result my self and here is code:
function statusvalues() {
$query = "SELECT tag_ids FROM tblname WHERE tag_ids !=''";
$result = mysqli_query($query, DBCONN);
$idarray = array();
while($row = mysqli_fetch_array($result)) {
array_push($idarray, $row['tag_ids']);
}
return $idarray;
}
function status($ID) { //Passing tag id
$set_of_numbers = statusvalues();
$reset_numbers = implode(", ", $set_of_numbers);
$values = explode(", ", $reset_numbers);
if (in_array($ID, $values)){
return "disabled";
}
}
I have a while loop that is supposed to first get the individual_id from a table called submittedresume using the job_id that it gets from another function. It would then use that id in another while loop to get the first_name and last_name from the individual table. It would then use another while loop to get the submitted_id from the submitted resume table.
I split the first and last while loop to get distinct values from the output.
My first while loop. It first gets the individual_id from a table called submittedresume using the job_id that it gets from another function. It gives me the correct output of two user ids: 9 and 4.
global $database;
$query = "SELECT DISTINCT individual_id FROM submittedresume WHERE job_post_id='$id'";
$output = $database->query($query);
while ($row = mysqli_fetch_array($output)) {
$indvId = $row[0];
}
This is the second inner while loop. It gives me an output of Mary Jane (No repeat) and Tom Sawyer.
$indvId = $row[0];
$sql = "SELECT * FROM individual WHERE individual_id='$indvId'";
$result = $database->query($sql);
while ($details = mysqli_fetch_array($result)) {
$first = $details['first_name'];
$last = $details['last_name'];
echo $first;
echo $last;
}
This is my whole function:
public function displayApplications($id){
global $database;
$query = "SELECT DISTINCT individual_id FROM submittedresume WHERE job_post_id='$id'";
$output = $database->query($query);
while ($row = mysqli_fetch_array($output)) {
$indvId = $row[0];
$sql = "SELECT * FROM individual WHERE individual_id='$indvId'";
$result = $database->query($sql);
while ($details = mysqli_fetch_array($result)) {
$first = $details['first_name'];
$last = $details['last_name'];
$sqlquery = "SELECT DISTINCT resume_title FROM submittedresume WHERE individual_id='$indvId' order by submitted_id";
$data = $database->query($sqlquery);
if (mysqli_num_rows($data) == 0) {
echo "Database is empty <br>";
} else {
while (($name = mysqli_fetch_array($data))) {
echo $first . " " . $last . " "."<a href=handleDownload.php?id=$id>$name[0]</a><br>";
}
}
}
}
}
This is what I'm getting right now:
first_name | last_name | resume_name
Mary | Jane | resume_1
Mary | Jane | resume_2
This is what I'm looking for:
first_name | last_name | resume_name
Mary | Jane | resume_2
Tom | Sawyer | resume_1
I think after while use foreach loop:
For example:
$query = "SELECT DISTINCT individual_id FROM submittedresume WHERE job_post_id='$id'";
$output = $database->query($query);
$details = mysqli_fetch_array($result);
foreach($details as $key => $value){
echo 'Key: '. $key . ' '. 'Value: '. $value;
}
$indvId = $row[0]; is returning the 1st item in the result array
I personally would use a foreach loop but you could do it the way you have it by adding a counter ie: $count = 0; before the loop and $count++; inside the loop and $indvId = $row[$i];
I have this array JSON POST request to a PHP file.
Array
(
[user_id] => 1
[date] => 2014-12-05
[time] => 12:00
[description] => lol
[friends] => "12","9"
[PHPSESSID] => 5ae7c3e6339c528e7804020dd0f0cdbb
)
I try to add the values (12 | 1) and (9 | 1) to a mysql table with a single sql query
Table:
u_id | f_id
1 | 12
1 | 9
What I have so far:
$friendarray = $_POST['Friends'];
foreach( $friends as $friendsarray ) {
$values[] = "(" . $u_id . "," . $friendsarray . ")";
}
$query = "INSERT INTO up2_friends_to_users (u_id , f_id ) VALUES ".implode(',',$values);
$stmt = $db->prepare($query);
$result = $stmt->execute();
As you see this is not working at all. I try to achieve something like this:
$query_params = array(
':u_id' => $_POST['user_id'],
':f_id' => $friendid,
And then would like to send it like this:
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
Is it possible to create a single query with multiple rows like this?
Answer thanks to RobP:
$friendsarray = explode(',',$_POST['friends']);
$placeholders = [];
for($i=0, $len=count($friendsarray); $i < $len; $i++) {
$placeholders[i] .= "(:u_id".$i.", :f_id".$i.")"; // entries like "(:u_id0, :f_id0)"
}
$query = "INSERT INTO up2_friends_to_users (u_id , f_id ) VALUES ".implode(",", $placeholders);
$stmt = $db->prepare($query);
for($i=0, $len=count($placeholders); $i < $len; $i++) {
$stmt->bindParam(':u_id'.$i, $_POST['user_id']);
$nextFriend = $friendsarray[$i];
$stmt->bindParam(':f_id'.$i,trim($nextFriend,'"'));
}
$result = $stmt->execute();
Now f_id is always null.
I agree the best strategy is to use a single query as you were trying to do. This will be much faster for long lists, especially if you don't wrap all the individual inserts into a single commit. This should work:
$friendarray = $_POST['Friends'];
$placeholders = [];
$user_id = $_POST[`user_id`];
for($i=0, $len=count($friendarray); $i < $len; $i++) {
$placeholders[$i] = "(:u_id".$i.", :f_id".$i.")"; // entries like "(:u_id0, :f_id0)"
}
$query = "INSERT INTO up2_friends_to_users (u_id , f_id ) VALUES ".implode(",", $placeholders);
$stmt = $db->prepare($query);
for($i=0, $len=count($placeholders); $i < $len; $i++) {
// each binding must use a separate variable, not an array element
$stmt->bindParam(':u_id'.$i, $user_id);
// use your favorite escape function on the value here
$nextFriend = $db->real_escape_string($friendarray[$i]);
$stmt->bindValue(':f_id'.$i, $nextFriend);
}
EDIT: learned something new from Only variables can be passed by reference - php. Can't pass array elements to bindParam as second parameter! Workaround posted above.
Do this:
$query = "INSERT INTO up2_friends_to_users (u_id , f_id ) VALUES (:u_id, :f_id)";
$stmt = $db->prepare($query);
$stmt->bindParam(':u_id', $_POST['user_id'];
$stmt->bindParam(':f_id', $friendid);
foreach ($_POST['Friends'] as $friendid) {
$stmt->execute();
};
bindParam binds to a reference, so every time you execute the query it will use the value of $friendid from the current iteration of the loop.
Maybe, something like this (using question mark parameters)?
$values = array();
foreach ($_POST['Friends'] as $friendid) {
$values[] = $u_id;
$values[] = $friendid;
}
$conn = new \PDO($dsn, $user, $password);
$query = 'INSERT INTO up2_friends_to_users (u_id , f_id ) VALUES '
. trim(str_repeat('(?, ?),', count($values / 2)), ',');
$conn->prepare($query)->execute($values);
I have 2 tables that look like this
table A table B
id | data id | features
--------- --------------
1 | blue 1A | 1;2
2 | red 2B | 1;2;3
3 | yellow 3B | 3;1
...... ......
What i plan to do is something like this, where i query one table. loop thru the array of results and explode the data with the semicolon delimiter. then loop thru that new array and query it to get the data (note code below not tested)
$sql = "SELECT * FROM `tableB` WHERE `id`= '2B' LIMIT 1";
$query = $db->query($sql);
while ($row = mysql_fetch_array($query)) {
$arr = explode(';', $row['features']);
for ($i = 0; $i < sizeof($arr); $i++)
{
$sql2 = "SELECT * FROM `tableA` WHERE `id`="'.$arr[$i].'"";
$query2 = $db->query($sql2);
while ($row2 = mysql_fetch_array($query2)) {
$r[] = $row2['data'];
}
}
}
print_r($r);
is there a way i can achieve this just in mysql, where i match the column in tableB with the ID's in tableA? or maybe by not using a nested loop? performance is key. coz both tables have more than 25k rows of data.
thanks in advance
Check out this code. Reduced few loops.
$sql = "SELECT * FROM `tableB` WHERE `id`= '2B' LIMIT 1";
$query = $db->query($sql);
$arr = explode(';', $row['features']);
$str = implode(",", $arr);
$sql2 = "SELECT * FROM `tableA WHERE id IN ({$str});";
$query2 = $db->query($sql2);
while ($row2 = mysql_fetch_array($query2)) {
$r[] = $row2['data'];
}
What you are looking for is the IN function
This will take an array of id's and give you every result in a single query.
So your code should look like this after you apply it
while ($row = mysql_fetch_array($query)) {
$new_query = str_replace(";", ",", $row['features']);
$sql2 = "SELECT * FROM `tableA` WHERE `id` IN ($new_query)";
$query2 = $db->query($sql2);
while ($row2 = mysql_fetch_array($query2)) {
$r[] = $row2['data'];
}
}