I want to make a PHP file to insert array data in my server table. As i have multiple values selected so i have taken an array and created jsonstring from my iphone application to post value in PHP file and insert data in server table. I don't know what i am doing wrong and the value is not getting inserted in the server DB PHP/MYSQl.
I am getting Error message = "An error occurred.";
I have also tried declaring a variable with same array(used json_encode and decode also) data which i want to insert but shows same error.
<?php
$response = array();
if (isset($_REQUEST['userid']) && isset($_REQUEST['svalueid'])) {
$userid = $_REQUEST['userid'];
$svalueid = json_decode($_REQUEST['svalueid']);
include 'connect.php';
$db = new DB_CONNECT();
$result = mysql_query("SELECT userid, svalueid FROM users WHERE userid = '$userid'");
if (mysql_num_rows($result) > 0) {
$result = mysql_query("DELETE FROM uses WHERE userid = '$userid'");
foreach($svalueid as $value) {
$result = mysql_query("INSERT INTO users(id, userid, svalueid) VALUES('','$userid', '$value')");
}
} else {
foreach($svalueid as $value) {
$result = mysql_query("INSERT INTO users(id, userid, svalueid) VALUES('','$userid', '$value')");
}
}
if ($result) {
$response["success"] = 1;
$response["message"] = "successful.";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "An error occurred.";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Field's missing";
echo json_encode($response);
}
?>
To check if i am getting correct string i used this php file ..
<?php
$response = array();
$userid = $_REQUEST['userid'];
$test="'svalueid' : [
'0' : 1,
'1' : 2
]";
$xyz = json_encode($test);
$vb = json_decode($test);
$pbk=array("1"=>"abc","2"=>"cck");
$pk=json_encode($pbk);
$ck=json_decode($pk);
include 'db_connect.php';
$db = new DB_CONNECT();
echo "<pre>";
print_r($_REQUEST['svalueid']);
echo "<br>";
print_r($vb);
echo "<br>";
print_r($ck);
echo "<br>";
echo "hi";die;
if ($result) {
$response["success"] = 1;
$response["message"] = "Success.";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "An error occurred.";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Value is missing";
echo json_encode($response);
}
?>
The response i get in my application on console shows this :
response: <pre>{
\"sidselected\" : {
\"0\" : 1,
\"1\" : 2
}
}<br><br>stdClass Object
(
[1] => abc
[2] => cck
)
<br>hi
Value that i have in userid = 1 and svalueid = "svalueid" : { "0" : 1, "1" : 2 }in jsonString is like this
json string going on server is {
"svalueid" : {
"0" : 1,
"1" : 2
}
}
i am not able to insert the values 1 and 2 in my DB table.
Is the format of svalueid correct ? Please help how should i enhance my php code.
$userid = (int) $_REQUEST['userid'];
. Also look into preventing SQL injections.