PHP does not insert in mySQL in foreach loop - php

I have a string array and I am trying to insert each data in this array into mySQL inside a foreach loop. But I recognized It doesn't insert all of them. Sometimes insert all, sometimes insert some of them. My code is below. Please let me figure out what my problem here is.
foreach($cbarray as $chvalue){
list($kid, $odemeopt) = explode('-',$chvalue);
$i_tr="trp".$kid;
$i_en="enp".$kid;
$i_fr="frp".$kid;
$tr_kargop=doubleval($_POST[$i_tr]);
$en_kargop=doubleval($_POST[$i_en]);
$fr_kargop=doubleval($_POST[$i_fr]);
if($odemeopt==1){
$ik_tr="trk".$kid;
$ik_en="enk".$kid;
$ik_fr="frk".$kid;
}
$tr_kargoextra=doubleval($_POST[$ik_tr]);
$en_kargopextra=doubleval($_POST[$ik_en]);
$fr_kargopextra=doubleval($_POST[$ik_fr]);
$myquery = "INSERT INTO item_kargo(product_id,kargo_id,kargo_priceTR,kargo_priceEN,kargo_priceFR,odemefarkiTR,odemefarkiEN,odemefarkiFR) VALUES ('$next_increment','$kid','$tr_kargop','$en_kargop','$fr_kargop','$tr_kargoextra','$en_kargopextra','$fr_kargopextra')";
echo "<h2>".$myquery."</h2>";
$kargo_bilgisi=mysql_query($myquery) or die("!!hata kargooo :".mysql_error());
}
This is the result of myquery
INSERT INTO item_kargo(product_id,kargo_id,kargo_priceTR,kargo_priceEN,kargo_priceFR,odemefarkiTR,odemefarkiEN,odemefarkiFR) VALUES ('4','1','1','1','1','','','')
INSERT INTO item_kargo(product_id,kargo_id,kargo_priceTR,kargo_priceEN,kargo_priceFR,odemefarkiTR,odemefarkiEN,odemefarkiFR) VALUES ('4','2','2','2','2','','','')
INSERT INTO item_kargo(product_id,kargo_id,kargo_priceTR,kargo_priceEN,kargo_priceFR,odemefarkiTR,odemefarkiEN,odemefarkiFR) VALUES ('4','4','3','3','3','3','3','3')

If can't you get your error from mysql_error() you can "echo" your data with var_dump(), so you can see how your array is build up. This helps me often to figure out my error in some loops.

Related

Insert array and non array values to database using a single sql statement

I have this, working, code, for inserting array to database:
$c = array_map(function ($reqNo,$officer,$product,$quantity){return "'$reqNo','$officer','$product','$quantity'";} , $reqNo,$officer,$product,$quantity);
if(!$insert = mysql_query("INSERT INTO request (RNO,UID,PID,QtyR) VALUES (".implode('),(', $c).")"))
Now, the problems is that i would like also to insert, alongside the array, none array values to the same database table, using the same sql insert statement..here's my code so far,
if(!$insert = mysql_query("INSERT INTO request (RNO,UID,PID,QtyR,Iuse,Designation,QtyA,QtyA1,QtyI,Rdate,Rtime,bar) VALUES (".implode('),(', $c).",'replacement','ICTU','-1','-1','-1',CURDATE(),CURTIME(),'1' )"))
and here's the error i'm getting:
Column count doesn't match value count at row 1
Any ideas on how to go about this?
I did get a way around it, though not sure if it's the correct way..this' how i did it:
//first, i got the length of the array
for($i=0;$i<count($product);$i++){}
//i used array_fill() to duplicate the single values into the length of the array
$new_usage = array_fill(0,$i,$usage);
$new_designation = array_fill(0,$i,$designation);
$QtyA = array_fill(0,$i,"-1");
$QtyA1 = array_fill(0,$i,"-1");
$QtyI = array_fill(0,$i,"-1");
$date = array_fill(0,$i,date("Y-m-d"));
$time = array_fill(0,$i,date("H:i:s"));
$bar = array_fill(0,$i,"1");
//then i put the above new arrays into array_map(), together with the original array
$c = array_map(function ($reqNo,$officer,$product,$quantity,$new_usage,$new_designation,$QtyA,$QtyA1,$QtyI,$date,$time,$bar){return "'$reqNo','$officer','$product','$quantity','$new_usage','$new_designation','$QtyA','$QtyA1','$QtyI','$date','$time','$bar'";} , $reqNo,$officer,$product,$quantity,$new_usage,$new_designation,$QtyA,$QtyA1,$QtyI,$date,$time,$bar);
//from there, i imploded the array_map into the sql insert statement
if(!$insert = mysql_query("INSERT INTO request (RNO,UID,PID,QtyR,Iuse,Designation,QtyA,QtyA1,QtyI,Rdate,Rtime,bar) VALUES (".implode('),(', $c).")")){
...
I still don't know if this' the right way to go about it, but all in all, it did work.

Mysql query within for loop not inserting all values

I have the following for loops, which should insert values into a mysql table. There is a users array and it is looping over the array and calculation statistics, and it should be inserting all the values into the mysql table, but it only inserts the operation done on the first element of the users array and not the rest. It is ignoring the first for loop, and only inserts for the second for loop, even though, I can see that the loops are doing what they are supposed to do, it is just not being inserted into mysql.
for($i=0; $i<count($users); $i++)
{
for($j=$i+1; $j<count($users); $j++)
{
$user1=$users[$i];
$user2=$users[$j];
$dat1=getData($user1);
$dat2=getData($user2);
$union=count(array_unique(array_merge($dat1, $dat2)));
$intersect=count(array_intersect($dat1, $dat2));
$rate=$intersect/$union;
$sql = "INSERT IGNORE into dat_net VALUES ($user1,$user2,$union,$intersect,$rate)";
$sqlresults = mysql_query($sql);
echo " ".$user1." ".$user2." \n";
if ($sqlresults === false) {
// An error has occured...
echo mysql_error();
}
}
}
Solved due to tips in the comments: I had inadvertently set up keys for the columns, so it wasn't inserting due to duplication.
First of all insert all data using one query. Generate it in for loop and call mysql query once.
You can check if your generated query works simply by echo it before execute and try to run it using some sql client.
try this,
$sql = "INSERT IGNORE into dat_net VALUES ('{$user1}','{$user2}','{$union}','{$intersect}','{$rate}')";
But it will be good if you create a insert query in foreach loop and then fire it once after completing foreach loop.

PHP loop to make MYSQL Queries

I have a list of IDs generated from a set of checkboxes as follows:
$list = mysql_real_escape_string(implode(',',$_POST['checkbox']));
which outputs a list like this:
a,b,c
I want to set a column in a MYSQL database that corresponds to each list item, I am unsuccessfully trying to create a query with a foreach loop like so:
$update_query= '';
foreach($list as $item){ //error on this line
$update_query .= "
INSERT INTO t (Col_1, Col_2)
VALUES ('".$item."',now());
";}
It fails telling me I have supplied an invalid argument for foreach(), but I'm not sure, a. what that means, and b. how to fix it; can anyone offer any guidance to get my loop working or a better way of doing this INSERT.
Thanks
$list is a string, not an array. Try passing in the array before you have imploaded it:
$update_query= '';
foreach($_POST['checkbox'] as $item)
{
$update_query .= "INSERT INTO t (Col_1, Col_2) VALUES ('".addslashes($item)."', now());";
}
You'd be much better off using prepared statements, though!

unable to insert into mysql database using php

$db = mysql_connect("localhost","root","123");
mysql_select_db("website_categorization") or die("\n error selecting database" );
$keyword_array = preg_split('/[\s,]+/', $tag);
foreach($keyword_array as $tag1)
{
mysql_query("INSERT INTO category_keyword(ID_Category, Keyword) VALUES(2,$tag1)");
}
echo "\nAffected rows are ".mysql_affected_rows()."\n";
mysql_close($db);
Can u tell me what is the problem with this code??...I intend to insert rows into the category_keyword table from an array $keyword_array. I get errors "Affected rows are -1" and insertion does not work
You should quote and escape string values.
You should also handle errors, to be notified of them.
You should also write distinct statements, to be able to read your code later (as well as let others to read it).
$tag1 = mysql_real_escape_string($tag1);
$sql = "INSERT INTO category_keyword(ID_Category, Keyword) VALUES(2,'$tag1')";
mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
insert multiple rows via a php array into mysql
You need to encapsulte the string $tag in a query, otherwise mysql will think its a column name
mysql_query("INSERT INTO category_keyword(ID_Category, Keyword) VALUES(2,'".mysql_real_escape_string($tag1)."')");
You should quote and escape your string columns
$tag1 =
mysql_real_escape_string($tag1);
mysql_query("INSERT INTO
category_keyword(ID_Category, Keyword)
VALUES(2,'$tag1')");
You should also handle the mysql query errors to know why the query get failed. With the current code you never know why it is failing.It is better to handle mysql errors.
mysql_query('Your query') or trigger_error(mysql_error());
You can use this:
mysql_query("INSERT INTO category_keyword SET ID_Category=2, Keyword=".$tag1.");
Better syntax to understand :)

Insert unknown number of rows into MySQL using PHP

I am trying to insert an unknown number of rows into MySQL using PHP. This is how it should work:
Javascript parses HTML DOM to create a multi-dimensional array based on a css class. The array will have a certain number of rows(or sub-arrays) corresponding to the number of elements that have that class. (This could be any integer 0 or greater... obviously).
Then, on a JavaScript event, the array is sent to a PHP script.
The PHP script will INSERT data from the array into MySQL.
My problem is that I don't know how to tell my PHP script how many values are in the array. And I don't know how to write the mysql_query() without knowing the number of values (or rows) that should be inserted.
You can insert more than one row at a time to MySQL:
INSERT INTO table1 (column1, column2, ...) VALUES (value_col1, value_col2), (value2_col1, value2_col2), ...;
In PHP, you can build your query by looping through rows and adding them to the SQL string:
$sql = "INSERT INTO table1 (col1, col2) VALUES ";
foreach($rows as $i=>$row) {
if ($i>0) {
$sql .= sprintf(",(%s,%s)", $row["col1_value"], $row["col2_value"]);
} else {
$sql .= sprintf("(%s,%s)", $row["col1_value"], $row["col2_value"]);
}
}
mysql_query($sql);
You have to be sure to properly escape your values depending upon what you're actually inserting.
Why don't you prepare a two dimensional array while searching with the css class identifier like this?
//This is jquery code - you can write javascript to do the same
$(`.class`).each(function(i,e){resultsArray.push($(this).val());});
This will save you from the headache of traversing a multidimensional array in the backend and you can simply do a count() in you PHP code and the following query preparation.
Query preparation
Assuming you have a two dimensional array you can use a bulk insert query like this:-
INSERT INTO tablename (a,b)
VALUES
('1', 'one'),
('2', 'two'),
('3', 'three')
And prepare the query dynamically using PHP like this -
$counter = 0;
$valuesPart = NULL;
foreach($_POST as $each)
{
if($counter > 0)
$appendComma = ",";
else
$appendComma ="";
$valuesPart .= $appendComma."(".$each['key1'].",".$each['key2'].")";
$counter++;
}
if(!empty($valuesPart))
$mysql_query = "INSERT INTO tablename (a,b) VALUES ".$valuesPart;
So, you don't need to know how many results are to be actually inserted.
If you stay with the multidimensional array, you will probably need to code or search for a code to traverse the multidimensional array which will probably involve recursion and a lot of complex code. There will be many chances of errors and it will be a slower (may be little but a finite amount which is not necessary).
So I assume the array is getting to PHP successfully, through $_POST or whatever? If you aren't sure then do a var_dump or echo_r so we can see.
EDIT - wow I put explode where I meant implode several times. fixed.
Assuming that it is, and that each 'sub' array is an associative array in form
[0]
'id' => 1
'name' => 'Billy'
'DOB' => .....
[1]
etc.
And the code to build a single query inserting all rows, like this INSERT INTO table ('f1','f2',f3') VALUES ('v11', 'v22', 'v33'), ('v21', 'v22', 'v23'), ......
$escapeAndQuote = function($x) {return "'".mysql_real_escape_string($x)."'";};
$rowwise = function($x) {return '('. implode(', ', array_map($escapeAndQuote, $x)) .')';
$fieldString = $rowwise(array_keys($arr[0]));
$valString = implode(', ', array_map($rowwise, $arr));
$sql = "INSERT INTO table $fieldString VALUES $valString";
mysql_query($sql, $conn);
Use a foreach loop to cycle through the array.
// Example:
foreach($submitted_array as $insert_array)
{
//php and mysql insert query here
}
Perhaps prepared statements would assist you in your endeavors. Essentially you will declare a generic insert statement and then "bind" values to each input. Read more on PHP PDO Prepared Statements.

Categories