Unable to insert data in MySQL from PHP script - php

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";

Related

Foreach error when insert to mysql

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.

Apostrophe causing problems with insert

Hi I am using php to insert some data into a MS Access Database, which works fine in most cases, the only time it doesnt work, as far as I can see is where there is an ' in the field, in this case its an address i.e. St John's Road.
This is the query statement I am using:
$sql = "insert into tempaddress (`id`, `StreetAddress`, `Place`, `PostCode`) values ('".$item["Id"]."', '".$item["StreetAddress"]."', '".$item["Place"]."','$SearchTerm')"; CustomQuery($sql);
And this is the error I am getting http://prntscr.com/58jncv
I'm fairly sure it can only be the ' within the string text that is messing it up, how can i change?
Apostrophes breaks SQL strings. So you should add slashes before each apostrophe in your SQL strings manually or use PHP's built in function addslashes().
Example:
$sql = "INSERT INTO myTable (value) VALUES ('Text that shouldn't break')";
$sql = addslashes($sql); // outputs "INSERT INTO myTable (value) VALUES ('Text that shouldn\\'t break')"
Source : php.net/manual/en/function.addslashes.php
Thanks, in the end I went with str_replace("'", "", $string);
You are using ' ' quote with the php variable $SearchTerm and use a backslash before column name.
Change your query statement to this:
$sql = "insert into tempaddress (\`id\`, \`StreetAddress\`, \`Place\`, \`PostCode`) values ('".$item["Id"]."', '".$item["StreetAddress"]."', '".$item["Place"]."',$SearchTerm)"; CustomQuery($sql);

unable to insert xml string into mysql table

i want to insert below xml string into mysql database
<message to='". $groupMembersArray[$i] . "#crossmessenger.com' type='groupchat' from='$mFrom'><x xmlns='jabber:x:event'><offline/><delivered/><displayed/></x><body>$message</body></message>
so for that i have written below code
$connection = mysqli_connect("localhost","xyz","abc#123","mydb");
for($i = 0 ; $i < $totalMembers ; $i++){
$stanzaToInsert = "<message to='". $groupMembersArray[$i] ."#crossmessenger.com' type='groupchat' from='$mFrom'><x xmlns='jabber:x:event'><offline/><delivered/><displayed/></x><body>$message</body></message>";
$msgSize = strlen($stanzaToInsert);
$insertQuery = "INSERT INTO ofOffline VALUES ('$groupMembersArray[$i]', $messageID, $creationDate, $msgSize, '$stanzaToInsert')";
mysqli_query($connection, $insertQuery);
mysqli_commit($connection);
echo "record $message inserted in table and commited";
}
but nothing is inserting in database. if i replace xml string that means value of stanzaToInsert to some simple text, then it is inserting value into database.
$insertQuery = "INSERT INTO ofOffline VALUES (
$groupMembersArray[$i],
$messageID,
$creationDate,
$msgSize,
'hard coded string'
)";
so problem is with xml string.
so can i know "what's wrong with me"?
you should use mysqli_real_escape_string before inserting the value like this
$stanzaToInsert = mysqli_real_escape_string($connection, $stanzaToInsert);
Please use "N" befor the xml string for inert the xml message like this:--
(NULL,N'<?xml version="1.0" encoding="utf-16" standalone="yes"?><!--This is a test XML file--><filemeta filetype="Audio"><Comments /><AlbumTitle /><TrackNumber /><ArtistName /><Year /><Genre /><TrackTitle /></filemeta>')
Yourcode should be like this:-
$insertQuery = "INSERT INTO ofOffline VALUES (
$groupMembersArray[$i],
$messageID,
$creationDate,
$msgSize,
N'$xmlstring'
)";

PHP - Column count doesn't match value count.

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.

How to properly INSERT INTO MySQL Using PHP Variables

I'm having a problem with my personal server where I'm trying to create a database for the decade old binders I have for the Yu-Gi-Oh! Trading Card Game (haven't played in years). In testing the INSERT INTO, I keep running across a particular problem...
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Magic'(Name, Description, Card_ID, Pack, P_ID, Quantity) VALUES ('Post', 'Post ' at line 1
Now my code outputs properly when I comment out the query function and echo to my webpage, but I keep getting the above mysql_error() message being displayed.
My code snippet is as follows...
if(isset($_SESSION['username'])) {
mysql_connect("localhost", "my_username", "my_password") or die(mysql_error());
mysql_select_db("my_db") or die(mysql_error());
function clean_string($value) {
if(get_magic_quotes_gpc() ) {
$value = stripslashes($value);
}
return mysql_real_escape_string($value);
}
$Show = clean_string($_POST['show']);
$Table = clean_string($_POST['table']);
$Insert_M_T = $_POST['insert_magic_traps'];
$Insert_Monster = $_POST['insert_monster_effect'];
$Insert_Card_Type = clean_string($_POST['I_Type']);
$Insert_Card_Name = clean_string($_POST['I_Card_Name']);
$Insert_Description = clean_string($_POST['I_C_Description']);
$Insert_Card_ID = clean_string($_POST['I_Card_ID']);
$Insert_CardPack = clean_string($_POST['I_C_Pack']);
$Insert_PackID = clean_string($_POST['I_C_P_ID']);
$Insert_Quantity = clean_string($_POST['I_C_Quantity']);
if(isset($Insert_M_T)) {
$sql = "INSERT INTO '$Insert_Card_Type'(Name, Description, Card_ID, Pack, P_ID, Quantity) VALUES ('$Insert_Card_Name', '$Insert_Description', '$Insert_Card_ID', '$Insert_CardPack', '$Insert_PackID', '$Insert_Quantity')";
mysql_query($sql) or die(mysql_error());
echo "<center><h2>Record added to Table: $Insert_Card_Type</h2></center>";
echo "<center><table><tr><th>Name:</th><td>$Insert_Card_Name</td></tr><tr><th>Description:</th><td>$Insert_Description</td></tr><tr><th>Card ID:</th><td>$Insert_Card_ID</td></tr><tr><th>Pack:</th><td>$Insert_CardPack</td></tr><tr><th>Pack ID Number</th><td>$Insert_PackID</td></tr><tr><th>Quantity:</th><td>$Insert_Quantity</td></tr></table></center>";
}
?>
//more html and php code
<?php
} else {
echo "<h1><center><font color=#ff0000 >ACCESS DENIED!!!</font></center></h1>";
echo "<h2><center><a href=index.php >Login Here!</a></center></h2>";
}
?>
Any advice would be helpful. I've tried searching for how to get around this problem, but to no avail. I feel like this is a simple fix, but I'm missing it. Please advise.
Thank you in advance.
~DanceLink
INSERT INTO `$Insert_Card_Type` (Name, Description, Card_ID, Pack, P_ID, Quantity)
VALUES ('$Insert_Card_Name', '$Insert_Description', '$Insert_Card_ID', '$Insert_CardPack', '$Insert_PackID', '$Insert_Quantity')
Backticks around $Insert_Card_Type, not single quotes.

Categories