Insert multiple Mysql record using Array - php

i have an array of company name, i insert each company name as separate record.below is the code
<input type="text" name="company_name[]">
$company_name = $_POST['company_name'];
if($company_name)
{
foreach($company_name as $company)
{
$mycompany[] = $company;
}
}
$val="('".implode("'), ('",$mycompany)."')";
$sql = "INSERT INTO `table`
(`company_name`) VALUES ".$val."";
The above query look like this and it successfully inserted 2 records in table.
INSERT INTO `table` (`company_name`) VALUES ('DELL'), ('IBM')
Now the problem is that with every company_name there is a company_code which i want to insert with each record and there is 3rd values lets suppose order_num which i also want to insert but the order_num should be same in all records,i need the query below
INSERT INTO `table` (`order_num`,`company_name`,`company_code`) VALUES ('123','DELL','axc89'), ('123','IBM','bxc90')

Okay, at last you endeavored to produce something understandable
1) This this code is absolutely useless:
$company_name = $_POST['company_name'];
if($company_name)
{
foreach($company_name as $company)
{
$mycompany[] = $company;
}
}
as $mycompany being an exact duplicate of $company_name
2) To get your "very complex" query
foreach($_POST['company_name'] as $key => $value)
{
$name = mysql_real_escape_string($value);
$code = mysql_real_escape_string($_POST['company_code'][$key]);
$mycompany[] = "(123,'$name','$code')";
}
$sql = "INSERT INTO `table` (order_num,company_name,company_code) VALUES ";
$sql .= implode(",",$mycompany);

INSERT INTO `table` (`order_num`,`company_name`,`company_code`) VALUES ('123','DELL','axc89');
INSERT INTO `table` (`order_num`,`company_name`,`company_code`) VALUES ('123','IBM','bxc90');
You can use an array
$arrray_to_be_inserted=array
(
[0]=>array('123','DELL','axc89'),
[1]=>array('123','IBM','bxc90')
);

Instead of passing value to a new variable in foreach , try to access as $key and $value, try this and see if it can help you
<?php
$company_name = array("DEL","IBM");
$company_code = array("1","2");
$order_num = array("4","5");
if($company_name)
{
foreach($company_name as $key => $value)
{
$mycompany[] = $value;
$mycompanycode[] = $company_code[$key];
$myordernum[] = $order_num[$key];
}
}
?>
Just make sure names and their values are corresponding to each other .

Related

Upload data to mysql with php

I try to upload my data to mysql Its working but it takes 35sec, too many sec.
What do I need to change in my code that it will work faster than 35 sec?
I use php to write my code and SQL query to send the data to my table that called "words" .
At my table in the database I have 4 columns ('word', 'num', 'hit', 'instoplist').
What I can do to fix this problem?
Thanks
This is my code:
<?php
function removeStopWordsFromArray($words)
{
.......
insert($words);
}
function insert($myWords)
{
global $conn;
foreach ($myWords as $key => $value) {
$word = $value['word'];
$number = $value['document'];
$hit = $value['hit'];
$stop = $value['stopList'];
$sql = "INSERT INTO words (word,num,hit,instoplist) VALUES ('$word', '$number', '$hit','$stop')";
if($conn->query($sql)!== TRUE)
{
echo "error". $conn->error;
}
}
fclose($fp);
}
$temp = pareseDocs();
removeStopWordsFromArray($temp);
?>
For every data you are running a query in DB. But the correct way in your case is to insert data in batches. You can write the code is following way:
$sql = "INSERT INTO words (word,num,hit,instoplist) VALUES";
foreach ($myWords as $key => $value) {
$word = $value['word'];
$number = $value['document'];
$hit = $value['hit'];
$stop = $value['stopList'];
$sql .= "('$word', '$number', '$hit','$stop'),";
}
$sql = rtrim($sql,',') //to remove last comma
if($conn->query($sql)!== TRUE)
{
echo "error". $conn->error;
}
This will run only single query in DB. Hence will be faster.
You can try this query outside of loop pass only one query:
INSERT IGNORE INTO MyTable ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
IGNORE FOR HANDLING ERRORS
Your problem is that you are making each query separately in a for loop.
Take a look at https://stackoverflow.com/a/452934/4988637 to find out more on how to insert mutliple rows in a single query.
If you change your method to one single query, you should find your program's run-time to be drastically shortened.
In SQL Server 2008 you can insert multiple rows using a single SQL
INSERT statement.
INSERT INTO MyTable ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
For reference to this have a look at MOC Course 2778A - Writing SQL
Queries in SQL Server 2008.
In your case, you could modify your code to look something like the following.
$sql = "INSERT INTO words (word, num, hit, instoplist) VALUES ";
foreach($myWords as $key => $value) {
$word = $value['word'];
$number = $value['document'];
$hit = $value['hit'];
$stop = $value['stopList'];
$sql .= "('$word', '$number', '$hit','$stop'),";
}
$sql = rtrim($sql, ',');
if($conn->query($sql) !== true) {
echo "error".$conn->error;
}

PHP update via textboxes

Right now the update only works if all textboxes are filled out, so the user can't just update productName for example. There isn't an error, but if the other textboxes are left blank then the database is updated with blanks and 0's. I want this to update whatever textboxes receive input, be it one or all, and leave the rest of the info alone if nothing is entered.
If productName for that row is Samsung, description is 'A phone' wholesalePrice is 179.99 and I just update the productName textbox only I still want the description and wholesalePrice to stay the same. Right now if I just update the productName only then the wholesalePrice shows as 0.00 and the description is blank. I tried using OR statements rather than commas in the query and whatever textbox I entered info in returned a 0.
if(isset($_POST['id'])) {
try {
$query = "UPDATE products SET productName = :productName, description = :description, wholesalePrice = :wholesalePrice,
retailPrice = :retailPrice, category = :category, quantityOnHand = :quantityOnHand
WHERE productID = :productID";
$statement = $db->prepare($query);
$statement->bindValue(':productID', $_POST['id']);
$statement->bindValue(':productName', $productName);
$statement->bindValue(':description', $description);
$statement->bindValue(':wholesalePrice', $wholesalePrice);
$statement->bindValue(':retailPrice', $retailPrice);
$statement->bindValue(':category', $category);
$statement->bindValue(':quantityOnHand', $quantityOnHand);
$statement->execute();
$statement->closeCursor();
//reload page after data is entered into the table and display a message if successful for 3 seconds before redirect
$page = $_SERVER['PHP_SELF'];
header('Location: ' . $_SERVER["HTTP_REFERER"] );
exit;
You can use a helper array for your columns to bind values dynamically if each $_POST value is set. Then you can create the update query for only those values.
$fields = array('productName', 'description', 'wholesalePrice', 'retailPrice', 'category', 'quantityOnHand');
$values = array();
$binds = array();
foreach($fields as $key => $value) {
if (isset($_POST[$value])) {
$values[] = $value.' = :'.$value;
$binds[':'.$value] = $_POST[$value];
}
}
if (!empty($values)) {
$query = "UPDATE products SET ";
$query .= implode(', ', $values);
$query .= " WHERE productID = :productID";
$binds[':productID'] = $_POST['id'];
$statement = $db->prepare($query);
$statement->execute($binds);
$statement->closeCursor();
}
EDIT:
If you have the values stored in variables then you can use variable variables:
foreach($fields as $key => $value) {
if (isset($$value)) {
$values[] = $value.' = :'.$value;
$binds[':'.$value] = $$value;
}
}
You need to pass all existing values to form fields so existing data is passed to the sql update if nothing changes. On submit validate the data, then do the update.
<textarea name="description">'.$row['description'].'</textarea>
if(isset($_POST['id'])) {
$productname = $_POST['productname'];
$description = $_POST['description'];
// etc ....
try {
// sql
}catch{
// error
}
}

Input checkbox value that is created dynamically into MySQL if checked

I am pulling in questions from a questions table in MySQL and populating them in a form. This works fine and I am populating checkboxes as well that the value is populated with the QuestionID. The array is properly populating but I want to take the value of the checked checkboxes (which is my question ID) and insert that ID into a table, so that I have the questions that are selceted for use by their ID. Here is what I have so far:
//Declare the QuestionID as a array
$QuestionID = array();
while($row = mysqli_fetch_array($run,MYSQLI_ASSOC)){
echo '<div id="QuestionSelection"><input id="chkQuestion" type="checkbox" value=" '.$row['QuestionID'].'" name=chkQuestion align="left"/><p>' . $row['Question'] .'</p></div><br/><br/>';
//Assign the QuestionID from the table to the var
$QuestionID[] = $row['QuestionID'];
}
if($_POST['submitted']) {
if (isset($_POST['chkQuestion']))
{
//create the query for the score
$sql2 = "INSERT INTO tbl_QuestionSelected (`QuestionID`) VALUES ($QuestionID)";
//Run the query
$run2 = #mysqli_query ($conn,$sql2);
//Confirm message data was entered with a correct response and a graphic
echo '<h1>Submitted!!</h1>';
}
}//End of IF 'submitted
You want to insert multiple records in one statement is what I'm understanding.
$sql2 = "INSERT INTO `tbl_QuestionSelected` (`QuestionID`) VALUES(". implode('),(', $QuestionID) . ")";
This will join each index inside $QuestionID with ),(
If you were to echo $sql2 you would get
INSERT INTO `tbl_QuestionSelected` (`QuestionID`) VALUES(1),(2),(3)
You can use a loop to get the questions that are checked.
for($i=0;$i<count($_POST["chkQuestion"]);$i++) {
"INSERT INTO tbl_QuestionSelected (QuestionID) VALUES('".$_POST["chkQuestion"][$i]."');
}
This way the MySQL statement has the actual values to insert into your table.
try to loop your ids and escape it!!
$ids_list = '';
foreach($_POST["chkQuestion"] as $id)
{
$ids_list .= (strlen($ids_list) > 0 ? ',' : '').mysql_real_escape_string($id);
}
$sql2 = "INSERT INTO tbl_QuestionSelected (`QuestionID`) VALUES (".$ids_list.")";
This will assign the value based on the array for the value and insert it into MySQL:
//Declare the QuestionID as a array
$QuestionID = array();
while($row = mysqli_fetch_array($run,MYSQLI_ASSOC)){
echo '<div id="QuestionSelection"><input id="chkQuestion" type="checkbox" value=" '.$row['QuestionID'].'" name="QuestionID[' . $row['QuestionID'] . ']">' .$row['Question']. '</p></div><br/><br/>';
//Assign the QuestionID from the table to the var
$QuestionID[] = $row['QuestionID'];
}
if($_POST['submitted']) {
$ids_list = '';
foreach($_POST["QuestionID"] as $key=>$value) {
{
$ids_list .= (strlen($ids_list) > 0 ? ',' : '').mysql_real_escape_string($value);
}
$sql2 = "INSERT INTO tbl_QuestionSelected (`QuestionID`) VALUES (".$ids_list.")";
//Run the query
$run2 = #mysqli_query ($conn,$sql2);
}//End of IF 'submitted
}

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)

inserting values from a loop

$sql1 = "SELECT SIDno FROM class WHERE SubjID='$SubjName' and SecID='$SecName'";
$result1 = mysql_query($sql1);
while ($row1 = mysql_fetch_assoc($result1)){
$IDno = $row1["SIDno"];
$sql2="INSERT INTO registered ( ServiceID, IDno, Stype)VALUES('$RecCode','$IDno','$Stype')";
}
this is my code. its working but it only insert one data into the database. How can make it away to insert all the possible data from the loop. Can anyone help me?
You’re probably executing the query after the loop so only the last record is being inserted.
Try to execute the insertion query at the end of the loop:
while ($row1 = mysql_fetch_assoc($result1)) {
$IDno = $row1["SIDno"];
$sql2 = "INSERT INTO registered (ServiceID, IDno, Stype) VALUES ('".mysql_real_escape_string($RecCode)."', '".mysql_real_escape_string($IDno)."', '".mysql_real_escape_string($Stype)."')";
mysql_query($sql2);
}
Or you first collect all data and then do one query to insert all records:
$values = array();
while ($row1 = mysql_fetch_assoc($result1)) {
$IDno = $row1["SIDno"];
$values[] = "('".mysql_real_escape_string($RecCode)."', '".mysql_real_escape_string($IDno)."', '".mysql_real_escape_string($Stype)."')";
}
if (!empty($values)) {
$sql2 = "INSERT INTO registered (ServiceID, IDno, Stype) VALUES ".implode(',', $values);
mysql_query($sql2);
}
But don’t forget to prepare the values for the query (see mysql_real_escape_string function).
If you are not planing to do anything with the fetched data, you could use INSERT .. SELECT .. statement.
Example:
INSERT INTO registered (ServiceID, IDno, Stype)
SELECT field1, field2, field3
FROM class
WHERE SubjID='$SubjName' and SecID='$SecName'"
And like written before me, escape your variables...
Note: make sure you're escaping your variables with mysql_real_escape_string.
$sql1 = "SELECT SIDno FROM class WHERE SubjID='$SubjName' and SecID='$SecName'";
$result1 = mysql_query($sql1);
$sql2 = "INSERT INTO registered (ServiceID, IDno, Stype) VALUES ";
$addComma = false;
while ($row1 = mysql_fetch_assoc($result1)){
$IDno = $row1["SIDno"];
$sql2 .= ($addComma ? ", " : "") . "('$RecCode','$IDno','$Stype')";
$addComma = true;
}
Change this line:
$sql2="INSERT INTO registered..."
to this:
$sql2 .= "INSERT INTO registered..."
inside the loop. You are accidentally overwriting the insert statement each time. If you use .= you will append the next statement to the previous one, creating a batch of insert scripts, one for each record.

Categories