hello this my code.
print_r($_POST);
foreach ($_POST as $key => $value){
echo $$key = $value;
}
echo $dpopName1= json_encode($_POST['dpopName']);
echo $dpopPosition1= json_encode($_POST['dpopPosition']);
echo $dpopLocation1= json_encode($_POST['dpopLocation']);
if($sub_cat=='all') {
$sub_cat='';
}
//$sql = mysql_query("INSERT INTO venders(vender_name, contact_personName,category, subcategory,email,contact_no,address,city,state,pin_code) VALUES ('$vendor_name', '$cont_personName','$cat_type','$sub_cat','$vendor_email', '$contact_no','$vendor_address','$state','$city','$vendor_pin')") or die(mysql_error());
$insertQuery=mysql_query("INSERT IGNORE INTO `venders`(`vender_name`, `vendor_ddNo`, `vendor_ddDate`, `vendor_regid`, `dateCorp`, `contact_personName`, `category`, `subcategory`, `email`, `contact_no`, `fax_no`, `website`, `address`, `city`, `taluka`, `state`, `pin_code`, `vendor_Baddress`, `Bstate`, `Bcity`, `Bvendor_pin`, `Btaluka`, `Bcontact_no`, `Bfax_no`, `Bvendor_email`, `Bwebsite`, `govtUndertake`, `stateUndertake`, `publiclCompany`, `privatelCompany`, `copSociaty`, `partnerFirm`, `propritorship`, `anyOtherspecify`, `dpopName`, `dpopPosition`, `dpopLocation`, `panDetails`, `panRequireFor`, `serviceTaxregDetails`, `serviceTaxrequiredFor`, `pfRegisterDetails`, `pfRequireFor`, `excDutyreg`, `excRequireFor`, `labourLicensedetails`, `licencePanrequireFor`, `stvRegNo`, `stvRequireFor`, `stvregDateDetails`, `stvregDateRequiredFor`, `orgStrngth`, `NameofCompany`, `NameofBank`,
`nameOfbankBranch`, `cityofMB`, `accountNo`, `accountType`, `bankBranchIfsccode`, `micodeofBankbranch`, `otherBankerDetails`)
VALUES ('$vendor_name','$vendor_ddNo','$vendor_ddDate','$vendor_id','$dateCorp','$cont_personName','$vendor_address', '$cat_type','$sub_cat','$vendor_email','$contact_no','$fax_no','$website','$vendor_address','$city','$taluka','$state','$vendor_pin', '$vendor_Baddress','$Bstate','$Bcity','$Bvendor_pin','$Btaluka','$Bcontact_no','$Bfax_no','$Bvendor_email','$Bwebsite','$govtUndertake', '$stateUndertake', '$publiclCompany', '$privatelCompany', '$copSociaty', '$partnerFirm', '$propritorship', '$anyOtherspecify', '$dpopName1', '$dpopPosition1', '$dpopLocation1','$panDetails', '$panRequireFor', '$serviceTaxregDetails', '$serviceTaxrequiredFor', '$pfRegisterDetails', '$pfRequireFor', '$excDutyreg', '$excRequireFor', '$labourLicensedetails', '$licencePanrequireFor', '$stvRegNo',
'$stvRequireFor', '$stvregDateDetails', '$stvregDateRequiredFor', '$orgStrngth', '$NameofCompany', '$NameofBank', '$nameOfbankBranch', '$cityofMB', '$accountNo', '$accountType', '$bankBranchIfsccode', '$micrCodeofBankbranch', '$otherBankerDetails'
)") or die(mysql_error());
Array to string conversion error
Column count doesn't match value count at row 1.
I tried following to solve the prooblem:
for solving 1st error i use json encode to convert the array into json string then i place the json string variable into insert table.
for column count error i checked wheather my database id has a primary key or not and it has a primary key then also i count all the value and column and also i cross check all the syntax but i found nothing.
A better way... to insert, when you're inserting alot of columns is... to use INSERT INTO SET, because then you have a better idea of which columns are missing.. than meticulously going through your mapped INSERT, and checking whether you have every column to every value.
INSERT INTO sometable
SET field1 = 'value1',
field2 = 'value2',
field3 = 'value3'
(Milov, 2004).
It also helps, to escape every single value that you are inserting (But keep in mind... it is recommended to use PDO over MySQL Real Escape).
If any of your variables would contain a ' that would destroy your query.
Sure it would be best to use DBO, but since I guess you are trying to implement something here into existing code, you should try to debug this more:
print_r($_POST);
foreach ($_POST as $key => $value){
echo $$key = mysql_real_escape_string($value);
}
echo $dpopName1= mysql_real_escape_string(json_encode($_POST['dpopName']));
echo $dpopPosition1= mysql_real_escape_string(json_encode($_POST['dpopPosition']));
echo $dpopLocation1= mysql_real_escape_string(json_encode($_POST['dpopLocation']));
debug with:
$query="INSERT IGNORE INTO `venders`(`vender_name`, `vendor_ddNo`, `vendor_ddDate`, `vendor_regid`, `dateCorp`, `contact_personName`, `category`, `subcategory`, `email`, `contact_no`, `fax_no`, `website`, `address`, `city`, `taluka`, `state`, `pin_code`, `vendor_Baddress`, `Bstate`, `Bcity`, `Bvendor_pin`, `Btaluka`, `Bcontact_no`, `Bfax_no`, `Bvendor_email`, `Bwebsite`, `govtUndertake`, `stateUndertake`, `publiclCompany`, `privatelCompany`, `copSociaty`, `partnerFirm`, `propritorship`, `anyOtherspecify`, `dpopName`, `dpopPosition`, `dpopLocation`, `panDetails`, `panRequireFor`, `serviceTaxregDetails`, `serviceTaxrequiredFor`, `pfRegisterDetails`, `pfRequireFor`, `excDutyreg`, `excRequireFor`, `labourLicensedetails`, `licencePanrequireFor`, `stvRegNo`, `stvRequireFor`, `stvregDateDetails`, `stvregDateRequiredFor`, `orgStrngth`, `NameofCompany`, `NameofBank`, `nameOfbankBranch`, `cityofMB`, `accountNo`, `accountType`, `bankBranchIfsccode`, `micrCodeofBankbranch`, `otherBankerDetails`) VALUES ('$vendor_name','$vendor_ddNo','$vendor_ddDate','$vendor_id','$dateCorp','$cont_personName','$vendor_address', '$cat_type','$sub_cat','$vendor_email','$contact_no','$fax_no','$website','$vendor_address','$city','$taluka','$state','$vendor_pin', '$vendor_Baddress','$Bstate','$Bcity','$Bvendor_pin','$Btaluka','$Bcontact_no','$Bfax_no','$Bvendor_email','$Bwebsite','$govtUndertake', '$stateUndertake', '$publiclCompany', '$privatelCompany', '$copSociaty', '$partnerFirm', '$propritorship', '$anyOtherspecify', '$dpopName1', '$dpopPosition1', '$dpopLocation1','$panDetails', '$panRequireFor', '$serviceTaxregDetails', '$serviceTaxrequiredFor', '$pfRegisterDetails', '$pfRequireFor', '$excDutyreg', '$excRequireFor', '$labourLicensedetails', '$licencePanrequireFor', '$stvRegNo', '$stvRequireFor', '$stvregDateDetails', '$stvregDateRequiredFor', '$orgStrngth', '$NameofCompany', '$NameofBank', '$nameOfbankBranch', '$cityofMB', '$accountNo', '$accountType', '$bankBranchIfsccode', '$micrCodeofBankbranch', '$otherBankerDetails')";
if (!$insertQuery=mysql_query($query)){
echo $query;
die(mysql_error());
}
I notice this small mistake:
You use
`
instead of
'
which is totally wrong.
Related
I got some error when inserting my data. for data 1-20 , the data inserted well. But after that foreach not inserted all data. Here is the data :
<?php
include "../conn.php";
$source="https://source1.com/json";
$file=file_get_contents($source,true);
$char_parse=json_decode($file,true);
foreach($char_parse['data'] as $a_item){
$item_sold=$char_parse2['item_sold'];
$success=$char_parse2['success'];
$reject=$char_parse2['reject'];
$sqli="INSERT INTO `product` VALUES (NULL, '".$item_sold."', '".$success."', '".$reject."')";
mysqli_query($conn,$sqli);
$i++;
}
$?>
Please help me solve this issues
I don't know enough about your data structure. But based on your code, let's assume...
$char_parse['data'] = array(
array('item_sold'=>'item1', 'success'=>1, 'reject'=>2),
array('item_sold'=>'item2', 'success'=>1, 'reject'=>2)
);
Then,
foreach($char_parse['data'] as $a_item){
$item_sold = $a_item['item_sold'];
$success = $a_item['success'];
$reject = $a_item['reject'];
$sqli = "INSERT INTO `product` VALUES (NULL, '".$item_sold."', '".$success."', '".$reject."')";
mysqli_query($conn,$sqli);
}
If I'm wrong about the data structure, the proposed code won't work.
I am trying to inser json data in MySQL database using the code below but getting values like Array[0][0],0.000 etc. can someone please suggest a solution.
The values in the variables are correct as the echo in loop is displaying the correct values in browser.
Thanks.
[EDIT]
The datatype of 'add' is varchar, for 'SN','imm' its int and rest is all double.
[/EDIT]
for($x=0; $x<$totaladdress; $x++)
{
echo $x;
echo "<br>add=";
echo $json_a[report][$x][0];
$sql = "INSERT INTO `report`.`tempmain` (`SN`, `add`, `last`,`imm`, `lastH`, `pa`, `unex`, `meg`, `bi`, `re`) VALUES (NULL, '$json_a[report][$x][0]','$json_a[report][$x][1][last]', '$json_a[report][$x][1][imm]', '$json_a[report][$x][1][lastH]', '$json_a[report][$x][1][pa]', '$json_a[report][$x][1][unex]', '$json_a[report][$x][1][meg]', '$json_a[report][$x][1][bi]', '$json_a[report][$x][1][re]');";
$result=mysql_query($sql);
}
$sql = "INSERT INTO `report`.`tempmain` (`SN`, `add`, `last`,`imm`, `lastH`, `pa`, `unex`, `meg`, `bi`, `re`) VALUES (NULL, '$json_a[report][$x][0]','$json_a[report][$x][1][last]', '$json_a[report][$x][1][imm]', '$json_a[report][$x][1][lastH]', '$json_a[report][$x][1][pa]', '$json_a[report][$x][1][unex]', '$json_a[report][$x][1][meg]', '$json_a[report][$x][1][bi]', '$json_a[report][$x][1][re]');";
Is inserting $json_a as an array and is not interpreting the rest. Try:
$sql = "INSERT INTO `report`.`tempmain` (`SN`, `add`, `last`,`imm`, `lastH`, `pa`, `unex`, `meg`, `bi`, `re`) VALUES (NULL, '".$json_a['report'][$x][0]."','".$json_a['report'][$x][1]['last']."', '".$json_a['report'][$x][1]['imm']."', '".$json_a['report'][$x][1]['lastH']."', '".$json_a['report'][$x][1]['pa']."', '".$json_a['report'][$x][1]['unex']."', '".$json_a['report'][$x][1]['meg']."', '".$json_a['report'][$x][1]['bi']."', '".$json_a['report'][$x][1]['re']."');";
I.e. rather than doing:
$sql = "some sql $json_a[report][$x][1][pa] other sql"
do
$sql = "some sql ".$json_a['report'][$x][1]['pa'] ." other sql";
I am not sure the best way to do this or if it's even possible. Basically I have a checkbox that looks like this:
php
foreach($clients as $client){
echo'
<input type="checkbox" name="client_data[]" value="'.$class_id.'">
'.$client['first_name'].' ('.$client['nickname'].') '.$client['last_name'].'
<br />';
} // foreach($client
HTML looks like this
<form method="post" action="">
<input type="checkbox" value="?" name="client_data[]">
Dwayne (The Rock) Johnson<br>
<input type="checkbox" value="?" name="client_data[]">
Steve (Puddin) Robinson<br>
<input type="submit" value="Add" name="exist_to_class">
</form>
When the form is submitted I want to insert the
$first_name, $nickname, $lastname
into the db with a query that looks like this:
mysql_query("INSERT INTO `clients` (`user_id`, `first_name`, `last_name`, `nickname` `class_id`)
VALUES ('$user_id', '$first_name, '$last_name', '$nickname', '$class_id')");
Is this possible or am I even close on how I am attempting to set this up? I have not had much luck so far.
My db table looks like this:
I need to be able to enter the client multiple time with different class_id's.
What is the best way to accomplish this?
Here is the code that call the function to insert data into db:
if (isset($_POST['exist_to_class'])){
if (empty($_POST['client_data']) === true){
$errors [] = 'You much select a client to be added to the class.';
} else {
if (isset($_POST['client_data']) && !empty($_POST['client_data']));
list($first_name, $nickname, $last_name) = explode('|', $_POST['client_data']);
exist_client_to_class($class_id);
header('Location: view_class.php?class_id='.$class_id.' ');
}
} //isset
And here is my query:
function exist_client_to_class($class_id, $user_id){
$class_id = (int)$class_id;
$user_id = (int)$user_id;
mysql_query("INSERT INTO `clients` (`user_id`, `first_name`, `last_name`, `nickname` `class_id`)
VALUES ('$user_id', '$first_name, '$last_name', '$nickname', '$class_id')");
}
What am I doing wrong?
You can't pass more than one variable through a single checkbox. Marc B is right, in that if this is a database-backed application then the right way to do it would be to have the checkbox send the ID for the person who's selected, and use the ID to look up whatever information you need about them.
If you're not using a database, a quick-and-dirty way to do this would be to put the information about the person into an array and then run it through serialize() to turn it into a string and use that as the value attribute. On the other end you can run it through unseialize() to get back the array with the values you wanted.
Remember that if you do this, you need to either escape your sql query or (very strongly preferred) use a prepared query.
okay, you may path string in value as Asad suggested and than split it on the server, like this
foreach($clients as $client){
echo'
<input type="checkbox" name="client_data" value="'.$class_id.'|'.$client['first_name'].'|'.$client['nickname'].'|'.$client['last_name'].'">
'.$client['first_name'].' ('.$client['nickname'].') '.$client['last_name'].'
<br />';
} // foreach($client
and on the server have something like
list($class_id, $first_name, $nickname, $last_name) = explode('|', $_POST['client_data'])
mysql_query("INSERT INTO `clients` (`user_id`, `first_name`, `last_name`, `nickname` `class_id`)
VALUES ('$user_id', '$first_name, '$last_name', '$nickname', '$class_id')");
I am not sure where from $class_id variable in template and $user_id in the model, so you have to figure it out, also drawback here is that if in some variable will be placed delimiter | data will be split wrong. To avoid it you may use hidden inputs associated somehow with the main checkbox (javascript, logic or whaterver will play best in your case)
UPD: oh yea you may serialize/unserialize data as array http://us3.php.net/serialize as octern suggestion
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.
I'm using the following snippet to break up an string array, then insert them into the database.
//split tags into individual words
$tag_array = explode(',', $tags);
foreach($tag_array as $tag){
addslashes($tag);
echo $tag." ";
$addTagsQuery = "INSERT INTO `my_blog`.`tags` (`id`, `name`) VALUES
('".$id."', '".$tag."');";
$tagsResult = $db->query($addTagsQuery);
if($tagsResult){
echo "tag added <br />";
}
else {
echo "tag was not added <br />";
}
}
My problem lies within a scenario where multiple tag (strings) are submitted. Unfortunately, only the first string in the array is inserted. Any insight as to why only the first string in the array is inserted into the MySQL database would be appreciated.
$id is not being incremented in the loop. Chances are you are getting a duplicate error, but for whatever reason it is not telling you (poor error handling?).
$addTagsQuery = "INSERT INTO `my_blog`.`tags` (`name`) VALUES
('".$tag."');";
If the ID is auto_incrementing, just omit and it will handle that for you.
You should use an auto-incrementing id instead of setting the id manually.
You don't need to run multiple insert statements. You can do it in one statement:
INSERT INTO my_blog.tags (name) VALUES ('tag1'), ('tag2')
The function addslashes doesn't modify the string so the way you are using it will have no effect.
You should use bind parameters instead of escaping strings.
$id is the id of the blog entry the tags are submitted for? Do you maybe have turned ID into a primary key or otherwise unique? That could cause the problem.
Try it like this:
$tag_array = explode(',', $tags);
$stmt = $db->prepare("INSERT INTO my_blog.tags (id, name) VALUES (?,?)");
foreach($tag_array as $tag){
if ($stmt->execute(Array($id, $tag))){
echo "tag added <br />";
}
else{
echo "tag was not added <br />";
}
$stmt->closeCursor();
}