PHP MySQL使用JsonString(Array)来插入记录

时间:2022-09-25 20:02:13

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.

我想制作一个PHP文件,在我的服务器表中插入数组数据。因为我选择了多个值,所以我采用了一个数组并从我的iphone应用程序创建了jsonstring,以便在PHP文件中发布值并在服务器表中插入数据。我不知道我做错了什么,价值没有插入服务器数据库PHP 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.

我也尝试声明一个变量与同一个数组(使用json_encode和解码)数据,我想插入但显示相同的错误。

<?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文件..

<?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

我在userid = 1和svalueid =“svalueid”中的值:{“0”:1,“1”:2}在jsonString中是这样的

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.

我无法在数据库表中插入值1和2。

Is the format of svalueid correct ? Please help how should i enhance my php code.

svalueid的格式是否正确?请帮助我应该如何增强我的PHP代码。

2 个解决方案

#1


1  

I'd personally be inclined to go all-in on the JSON request, including both the userid and the svalueids part of the JSON request. I'd also make svalueids an array, not a dictionary (unless, of course, you were actually going to use the keys passed).

我个人倾向于全押JSON请求,包括JSON请求的userid和svalueids部分。我也让svalueids成为一个数组,而不是一个字典(当然,除非你实际上要使用传递的密钥)。

For example, I might make the request like so:

例如,我可能会这样提出请求:

{
    "userid"    : 1,
    "svalueids" : [4, 5]
}

For example, if generating the request in iOS:

例如,如果在iOS中生成请求:

NSURL *url = [NSURL URLWithString:@"http://your.url.here.com/submit.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

NSDictionary *requestDictionary = @{@"userid"    : @1,
                                    @"svalueids" : @[@4, @5]};

NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestDictionary options:0 error:nil];

[request setHTTPBody:requestData];
[request setHTTPMethod:@"POST"];
[request addValue:@"text/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (error) {
        NSLog(@"%s: error: %@", __FUNCTION__, error);
        return;
    }
    if (data) {
        NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"responseDictionary=%@", responseDictionary);
    }
}];

You could then have PHP to parse that JSON request (where the JSON formatted request is the actual HTTP body):

然后,您可以使用PHP来解析该JSON请求(其中JSON格式的请求是实际的HTTP主体):

<?php

$handle = fopen("php://input", "rb");
$raw_post_data = '';
while (!feof($handle)) {
    $raw_post_data .= fread($handle, 8192);
}
fclose($handle);

// I'm expecting a request in the form of
//
// {"userid":1, "svalueids":[1,2]}

$request_data = json_decode($raw_post_data, true);
if (is_null($request_data)) {
    echo json_encode(array("success" => false, "message" => "Request not valid formed JSON"));
    exit;
}

// get userid

$userid = $request_data["userid"];

if (is_null($userid) || !is_numeric($userid)) {
    echo json_encode(array("success" => false, "message" => "Userid not provided or not numeric"));
    exit;
}

// get array of svalueids

$svalueids = $request_data["svalueids"];

if (!is_array($svalueids)) {
    echo json_encode(array("success" => false, "message" => "svalueids array not provided"));
    exit;
}

$dbuserid = ...;
$dbpassword = ...;
$dbdatabase = ...;
$con = mysqli_connect("localhost", $dbuserid, $dbpassword, $dbdatabase);

// Check connection
if (mysqli_connect_errno())
{
    echo json_encode(array("success" => false, "message" => mysqli_connect_error()));
    exit;
}

foreach ($svalueids as $svalueid) {
    if (!is_numeric($svalueid)) {
        echo json_encode(array("success" => false, "message" => "svalueid is non- numeric"));
        mysqli_close($con);
        exit;
    }

    $sql = "INSERT INTO users(userid, svalueid) VALUES ({$userid}, {$svalueid})";

    if (!mysqli_query($con, $sql))
    {
        echo json_encode(array("success" => false, "message" => mysqli_error($con)));
        mysqli_close($con);
        exit;
    }
}

mysqli_close($con);

echo json_encode(array("success" => true));

?>

#2


1  

You have double quotes all over the place in svalueid = "svalueid" : { "0" : 1, "1" : 2 } this is likely your problem.

你在svalueid =“svalueid”中有多个双引号:{“0”:1,“1”:2}这可能是你的问题。

try

$fixedValue = mysql_real_escape_string($value);

$result = mysql_query("INSERT INTO users(userid, svalueid) VALUES('$userid', '$fixedValue')");

Also if ID is a AUTO_INCREMENT field you dont need to add it to the INSERT query, it is implied and will be incremented and inserted automatically.

此外,如果ID是AUTO_INCREMENT字段,您不需要将其添加到INSERT查询中,它是隐含的,并将自动递增和插入。

Apply this logic to all your INSERTS and UPDATES.

将此逻辑应用于所有INSERTS和UPDATES。

Also should have error processing code after each mysql_query() and it should be displaying mysql_erno() and mysql_error() at least. Thats would de-mistify your errors as they happen.

在每个mysql_query()之后还应该有错误处理代码,它应该至少显示mysql_erno()和mysql_error()。多数民众赞成会在你的错误发生时将其误解。

#1


1  

I'd personally be inclined to go all-in on the JSON request, including both the userid and the svalueids part of the JSON request. I'd also make svalueids an array, not a dictionary (unless, of course, you were actually going to use the keys passed).

我个人倾向于全押JSON请求,包括JSON请求的userid和svalueids部分。我也让svalueids成为一个数组,而不是一个字典(当然,除非你实际上要使用传递的密钥)。

For example, I might make the request like so:

例如,我可能会这样提出请求:

{
    "userid"    : 1,
    "svalueids" : [4, 5]
}

For example, if generating the request in iOS:

例如,如果在iOS中生成请求:

NSURL *url = [NSURL URLWithString:@"http://your.url.here.com/submit.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

NSDictionary *requestDictionary = @{@"userid"    : @1,
                                    @"svalueids" : @[@4, @5]};

NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestDictionary options:0 error:nil];

[request setHTTPBody:requestData];
[request setHTTPMethod:@"POST"];
[request addValue:@"text/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (error) {
        NSLog(@"%s: error: %@", __FUNCTION__, error);
        return;
    }
    if (data) {
        NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"responseDictionary=%@", responseDictionary);
    }
}];

You could then have PHP to parse that JSON request (where the JSON formatted request is the actual HTTP body):

然后,您可以使用PHP来解析该JSON请求(其中JSON格式的请求是实际的HTTP主体):

<?php

$handle = fopen("php://input", "rb");
$raw_post_data = '';
while (!feof($handle)) {
    $raw_post_data .= fread($handle, 8192);
}
fclose($handle);

// I'm expecting a request in the form of
//
// {"userid":1, "svalueids":[1,2]}

$request_data = json_decode($raw_post_data, true);
if (is_null($request_data)) {
    echo json_encode(array("success" => false, "message" => "Request not valid formed JSON"));
    exit;
}

// get userid

$userid = $request_data["userid"];

if (is_null($userid) || !is_numeric($userid)) {
    echo json_encode(array("success" => false, "message" => "Userid not provided or not numeric"));
    exit;
}

// get array of svalueids

$svalueids = $request_data["svalueids"];

if (!is_array($svalueids)) {
    echo json_encode(array("success" => false, "message" => "svalueids array not provided"));
    exit;
}

$dbuserid = ...;
$dbpassword = ...;
$dbdatabase = ...;
$con = mysqli_connect("localhost", $dbuserid, $dbpassword, $dbdatabase);

// Check connection
if (mysqli_connect_errno())
{
    echo json_encode(array("success" => false, "message" => mysqli_connect_error()));
    exit;
}

foreach ($svalueids as $svalueid) {
    if (!is_numeric($svalueid)) {
        echo json_encode(array("success" => false, "message" => "svalueid is non- numeric"));
        mysqli_close($con);
        exit;
    }

    $sql = "INSERT INTO users(userid, svalueid) VALUES ({$userid}, {$svalueid})";

    if (!mysqli_query($con, $sql))
    {
        echo json_encode(array("success" => false, "message" => mysqli_error($con)));
        mysqli_close($con);
        exit;
    }
}

mysqli_close($con);

echo json_encode(array("success" => true));

?>

#2


1  

You have double quotes all over the place in svalueid = "svalueid" : { "0" : 1, "1" : 2 } this is likely your problem.

你在svalueid =“svalueid”中有多个双引号:{“0”:1,“1”:2}这可能是你的问题。

try

$fixedValue = mysql_real_escape_string($value);

$result = mysql_query("INSERT INTO users(userid, svalueid) VALUES('$userid', '$fixedValue')");

Also if ID is a AUTO_INCREMENT field you dont need to add it to the INSERT query, it is implied and will be incremented and inserted automatically.

此外,如果ID是AUTO_INCREMENT字段,您不需要将其添加到INSERT查询中,它是隐含的,并将自动递增和插入。

Apply this logic to all your INSERTS and UPDATES.

将此逻辑应用于所有INSERTS和UPDATES。

Also should have error processing code after each mysql_query() and it should be displaying mysql_erno() and mysql_error() at least. Thats would de-mistify your errors as they happen.

在每个mysql_query()之后还应该有错误处理代码,它应该至少显示mysql_erno()和mysql_error()。多数民众赞成会在你的错误发生时将其误解。