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.
Related
I've created this script to insert some data from PHP to MySQL, but it doesen't work, and I don't know why.
if (isset($_SESSION['userSession'])!="") {
$session_created=1;
$session_query = "SELECT * FROM users WHERE user_id=".$_SESSION['userSession'];
$session_query_result = $DBcon->query($session_query);
$user_row=$session_query_result->fetch_array();
}
if(isset($_POST['create_post_button'])){
$post_name = $DBcon->real_escape_string(strip_tags($_POST['post_title']));
$post_content = $DBcon->real_escape_string(strip_tags($_POST['post_content']));
date_default_timezone_set('Europe/Athens');
$post_date=date("Y-m-d h:i:sa");
$post_categ_id = $DBcon->real_escape_string(strip_tags($_POST['post_category']));
$post_creator = $user_row['user_name'];
$pass_flag=0;
$error_msg_cp = "Posted!";
$create_post_query = "INSERT INTO posts(post_name,post_content,post_date,
post_categ_id,post_user_name) VALUES ('$post_name','$post_content','$post_date','
$post_categ_id','$post_creator')";
echo "<br><br><br><br>".$create_post_query;
if($DBcon->query($create_post_query)){
$error_msg_cp="Error, pug!";
}
echo $error_msg_cp;
}
Thank you!
Edit:
The result of this code is:
Even with ini_set('display_errors', 'stdout'); it doesen't display the error...
This is the structure of the posts table in MySQL:
Seems to have a newline in your integer field.
Change your query like this. Single quote around '$post_categ_id' has changed.
$create_post_query = "INSERT INTO posts(post_name,post_content,post_date,
post_categ_id,post_user_name)
VALUES ('$post_name','$post_content','$post_date',
'$post_categ_id','$post_creator')";
echo "<br><br><br><br>".$create_post_query;
if (!$DBcon->query($create_post_query)){
$error_msg_cp="Error, pug!";
}
NB I suggest you to read this post How can I prevent SQL injection in PHP? to prevent your queries against SQL injections.
Change your insert query as follows, use '{$variable}' instead of '$variabe'
$create_post_query = "INSERT INTO posts(post_name,post_content,post_date,
post_categ_id,post_user_name) VALUES ('{$post_name}','{$post_content}','{$post_date}','
{$post_categ_id}','{$post_creator}')";
I am new in android development I am sending a json array through android application and insert that data into MySQL database. The problem is that whenever I insert userJSON it entered every time with duplicate entries. So, I want to prevent duplicate entry in mysql how can this possible with php. Please help me to solve this problem.
json string from android side
'[{"type":"Outgoing","duration":"0","number":"XXXXXXXX","date":"Tue Dec 13 15:26:29 GMT+05:30 2016"},
{"type":"Outgoing","duration":"0","number":"XXXXXXXX","date":"Tue Dec 13 13:49:50 GMT+05:30 2016"}]';
Here is my php file for post json:
<?php
require_once('conn.php');
if($_SERVER['REQUEST_METHOD']=='POST')
{
$json = $_POST["usersJSON"];
echo $json;
if (get_magic_quotes_gpc())
{
$json = stripslashes($json);
}
$data = json_decode($json,true);
$query=mysqli_query($con,"SELECT *
FROM users
where number = '$number'
and type = '$type'
and date = '$date'
and duration= '$duration'");
if(mysqli_num_rows($query)>0) {
echo "already exist";
}
elseif(is_array($data))
{
$sql = "INSERT IGNORE INTO users (type, duration, number,date) values ";
$valuesArr = array();
foreach($data as $row)
{
$type = mysqli_real_escape_string( $con,$row['type'] );
$duration = mysqli_real_escape_string($con, $row['duration'] );
$number = mysqli_real_escape_string( $con,$row['number'] );
$date = mysqli_real_escape_string( $con,$row['date'] );
$valuesArr[] = "('$type', '$duration', '$number', '$date')";
}
$sql .= implode(',', $valuesArr);
if(mysqli_query($con,$sql))
{
echo 'Entry Added Successfully';
}
else
{
echo 'Could Not Add Entry';
}
}
//Closing the database
mysqli_close($con);
}
?>
Create a UNIQUE INDEX
Regardless of whatever programming language that you use, all the constraints on the data have to be enforced with in the database and not in your application layer. And the easiest way to do that is to add a UNIQUE KEY on the columns in question.
ALTER TABLE users ADD UNIQUE KEY all_columns(number,type,date,duration)
I am adding all the four columns to the unique index because you seem to want any column to have duplicate values taken in isolation. Please confirm if this is correct or choose the columns appropriately when creating the index.
Simply your code
With a unique key in place, your don't need that SELECT
$data = json_decode($json,true);
if(is_array($data))
{
$sql = "INSERT IGNORE INTO users (type, duration, number,date) values ";
....
}
Use Prepared Statements
Instead of a huge string concatenation as is being currently done and multple calls to mysqli_real_escape, you would be better of using prepared statements. You might even get a tiny increase in performance. However more importantly there is a maximum size of a string that can be passed through to the server, if you get a large array you might go beyond that.
When Send Data With Json From Android(AS) to Server (php+mysql) Must 1 Record Insert But Multi Record Selected Why?
my php code is:
include ('connect.php');
$jsondata = file_get_contents('php://input' );
if($jsondata==""){
echo "forbiden";
}
else{
$data = json_decode($jsondata, true);
//get the employee details
$user = $data['name'];
$namayandegi = $data['code_namayandegi'];
$code = $data['kala_code'];
$name = $data['kala_name'];
$tedad= $data['kala_tedad'];
$cost= $data['kala_cost'];
$date= $data['date'];
$confirm= $data['confirm'];
$email=$data['email'];
$sql="INSERT INTO `final_factor`(`id`, `name`, `code_namayandegi`, `kala_code`, `kala_name`, `kala_tedad`, `kala_mablagh`, `date`, `confirm`,`email`)
VALUES ('','$user','$namayandegi','$code','$name','$tedad','$cost','$date','$confirm','$email')";
if(mysql_query($sql,$con))
{
echo "1";
}
}
First of all you don't need to insert the id in you query and it's supposed to be AI.
So your query would be something like this
$sql="INSERT INTO `final_factor`( `name`, `code_namayandegi`, `kala_code`, `kala_name`, `kala_tedad`, `kala_mablagh`, `date`, `confirm`,`email`)
VALUES ('$user','$namayandegi','$code','$name','$tedad','$cost','$date','$confirm','$email')";
Second: The only reason why there are duplicate rows is that your code is repeating itself somewhere and for some reason. it could be multiple page loads or something like this. It's not possible to tell it because the code you provided has no errors so maybe it's not all the code. It would be great if you provide all your code. If you don't want look after what I told. Somewhere your code is called twice. Look after that.
My entry form I have an inventory database with tables like aluminium, iron etc... Each table contains a subcategory of items like aluminium_pala, iron_1.5inch and so on. The entry code is like this:
include("dbConnect.php");
$orderNo = $_POST["number"];
if(isset($_POST["mat1"])&&$_POST["mat1"]!=NULL)
{
$mat1 = $_POST["mat1"];
$selmat1 = $_POST["selmat1"];
$amtmat1 = $_POST["amtmat1"];
$query = "INSERT INTO $mat1 ($selmat1,orderNo) VALUES (-$amtmat1,$orderNo);";
if(!($result = $mysqli->query($query)))
print "<div class='error'>insertion failed. Check your data</div>";
}
if(isset($_POST["mat2"])&&$_POST["mat2"]!=NULL)
{
$mat2 = $_POST["mat2"];
$selmat2 = $_POST["selmat2"];
$amtmat2 = $_POST["amtmat2"];
$query = "INSERT INTO $mat2 ($selmat2,orderNo) VALUES (-$amtmat1,$orderNo);";
if(!($result = $mysqli->query($query)))
print "<div class='error'>insertion failed. Check your data</div>";
}... and it goes on till mat11
I am trying to collect each similar table (mat1, mat2..) and their corresponding item (selmat1, selmat2...) and bunch the all in one query. That is, instead of going
INSERT INTO al_openable (zPala,orderNo) VALUES (23,14);
INSERT INTO al_openable (outer,orderNo) VALUES (50,14);
I am trying to execute it like
INSERT INTO al_openable (zPala,outer,orderNo) VALUES (23,50,14);
I need this to avoid duplicate foreign key entry(for $orderNo). One idea I've been considering is to use UPDATE if the order number is pre-existing. Do you guys think this is a good idea? And if so, what will be the best way to execute it? If not, how would a more experienced programmer solve this conundrum?
I think this question is related to your query: Multiple Updates in MySQL
You may use ON DUPLICATE KEY UPDATE in combination with INSERT statement.
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";