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.
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 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 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.
i want to send data with url
and my code php is:
<?php
$db_host="127.0.0.1"; $db_uid="root"; $db_pass="";
$db_name="highway_db"; $db_con =
mysqli_connect($db_host,$db_uid,$db_pass,$db_name);
$longitude =(isset( $_GET['lon`enter code here`gitude']));
$latitude = (isset($_GET['latitude']));
$timestamp = (isset($_GET['timestamp']));
$result = mysqli_query($db_con,"INSERT INTO accident (longitude, latitude, timestamp)
VALUES ($longitude, $latitude, $timestamp)");
if($result == true)
echo '{"query_result":"SUCCESS"}';
else
echo '{"query_result":"FAILURE"}';
mysqli_close($db_con);
?>
and my table is accident have id,longitude,latitude and timestamp
id is AUTO_INCREMENT.
but thme problem when i use this url :
http://127.0.0.1/addAccidents.php?longitude=3.54&latitude=3.09×tamp=2016-04-25 11:11:00
i find that is add to my table accident
longitude=1
latitude =1,
timestamp =0000-00-00 00:00:00.
and this my problem with url please help me
try this :
$result = mysqli_query($db_con,"INSERT INTO accident (longitude, latitude, timestamp) VALUES ('".$longitude."', '".$latitude."', '".$timestamp."')");
Echo the sql query and try to run query directly in your phpmyadmin and also check your database table column type.
try changing the setting of hte variables around - you should anyway because even if the GET value is not present - this code will still try to insert values into the db, such as :
if(isset( $_GET['longitude'])){$longitude =$_GET['longitude']};
and then write code that only allows the writing to the db if the three values are set.
isset() is a function which checks if a given variable has contents or not. If it has it returns 1 and if not it return 0.
In all 3 below statements, you are just checking the variables, you have not assigned values to your variables!
Try to use this code here, it should work if GET REQUEST with those specified parameters is sent!
<?php
$db_host="127.0.0.1";
$db_uid="root";
$db_pass="";
$db_name="highway_db";
$db_con = mysqli_connect($db_host,$db_uid,$db_pass,$db_name);
$longitude = isset($_GET['longitude'])?$_GET['longitude']:"";
$latitude = isset($_GET['latitude'])?$_GET['latitude']:"";
$timestamp = isset($_GET['timestamp'])?$_GET['timestamp']:"";
$query = "INSERT INTO accident (longitude,latitude,timestamp) VALUES ($longitude,$latitude,$timestamp)";
if(mysqli_query($db_con,$query)){
echo '{"query_result":"SUCCESS"}';
}
else{
echo '{"query_result":"FAILURE"}';
echo "ERROR= ". mysql_error();
}
mysqli_close($db_con);
?>
Let me know how it goes....
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.