【问题标题】:JS array to PHP and update table in MYSQL with PDOJS数组到PHP并使用PDO更新MYSQL中的表
【发布时间】:2016-09-21 08:13:51
【问题描述】:

我有一个表单,用户可以在其中插入最多 4 个年龄范围。用户可以动态添加或删除输入字段。

我正在尝试将数组发送到我的 PHP 文件,然后将其插入数据库(为每个范围对插入新行,假设 1-3 和 4-6 将位于具有正确 user_id 的单独行上)@987654323 @。

在 PHP 文件中回调成功,但没有插入任何内容,这意味着它无法从 JS 获取值,我很迷茫如何发送带有其余表单数据的数组。

html我有一个按钮,用户可以动态添加字段,ID每次都会增加1。

HTML 文件

<div class="row default" id="childAgeRange1">
    <div class="col-md-6">
        <input type="text" class="form-control" id="userProfileAgeFrom" name="userProfileAgeFrom[]" placeholder="Alates..." />
    </div>
    <div class="col-md-6">
        <input type="text" class="form-control" id="userProfileAgeTo" name="userProfileAgeTo[]" placeholder="Kuni..." />
    </div>
</div>

我的 JS 文件:

    $(document).on("click", "#btnUpdateInformation", function (e) {


                var userProfileAgeFrom = $("input[name^='userProfileAgeFrom']").map(function (idx, ele) {
                    return $(ele).val();
                }).get();

                var userProfileAgeTo = $("input[name^='userProfileAgeTo']").map(function (idx, ele) {
                    return $(ele).val();
                }).get();

                var formData = {
                    'user_id'                     : $("#hiddenUserID").val(),
                    'userPassword'                : $('#userPassword').val(),
                    'userRetypePassword'          : $('#userRetypePassword').val(),
                    'userBirthCountry'            : $('#userBirthCountry').val(),
                    'userBirthCity'               : $('#userBirthCity').val(),
                    'userBirthAddress'            : $('#userBirthAddress').val(),
                    'UserZipCode'                 : $('#UserZipCode').val(),
                    'userFirstName'               : $('#userFirstName').val(),
                    'userLastName'                : $('#userLastName').val(),
                    'userSex'                     : $('#userSex').val(),
                    'userBirthDay'                : $('#userBirthDay').val(),
                    'userBirthMonth'              : $('#userBirthMonth').val(),
                    'userBirthYear'               : $('#userBirthYear').val(),
                    'userPhoneNr'                 : $('#userPhoneNr').val(),
                    'userPasswordConfirm'         : $('#userPasswordConfirm').val(),
                    'userQuote'                   : $('#userQuote').val(),
                    'userDescription'             : $('#userDescription').val(),
                    'userProfileAgeFrom'          : userProfileAgeFrom,
                    'userProfileAgeTo'            : userProfileAgeTo,
                    'userProfileWage'             : userFinalWage

                };
        console.log(formData);
        $.ajax({
            type: "POST",
            url: "PHP/updateUserProfile.php",
            data: formData,  
            success: function(data){
                console.log(data);
                if(data.status == 'success'){
                    console.log("success");
                }else if(data.status == 'error'){
                    console.log("error");
                }else if(data.status == 'no_results'){
                    console.log("no results");
                }else if(data.status == 'results'){
                    console.log("there are results");
                }else if(data.status == 'password_matches'){
                    console.log("password matches");
                }

            },
            error: function(jqXHR, textStatus, errorThrown, data){
                console.log(jqXHR, textStatus, errorThrown, data);
            }
        });
        $('#btnUpdateInformation').unbind('click');
        e.preventDefault();
    });

PHP 文件

        if(isset($_POST['userProfileAgeFrom']) && isset($_POST['userProfileAgeTo'])){
            $data = array( 
                $userProfileAgeFrom => $_POST['userProfileAgeFrom'], 
                $userProfileAgeTo => $_POST['userProfileAgeTo']
            );

            $user_profile_age_range = $user_home->runQuery("UPDATE nanny_age_range SET age_minimum=:userProfileAgeFrom, age_maximum=:userProfileAgeTo WHERE user_id=:user_id ");
            $user_profile_age_range->bindparam(':userProfileAgeFrom', $userProfileAgeFrom, PDO::PARAM_STR);
            $user_profile_age_range->bindparam(':userProfileAgeTo', $userProfileAgeTo, PDO::PARAM_STR);
            $user_profile_age_range->bindparam(':user_id', $user_id, PDO::PARAM_STR);
            $user_profile_age_range->execute(); 
            $response_array['status'] = 'success';
        }

和数据库表:

编辑 Console.log(formData) 显示

UserZipCode
:
"11111"
userBirthAddress
:
"address"
userBirthCity
:
"c"
userBirthCountry
:
"c"
userBirthDay
:
"31"
userBirthMonth
:
"08"
userBirthYear
:
"1992"
userDescription
:
"description"
:
"x"
userLastName
:
"x"
userPassword
:
""
userPasswordConfirm
:
"xxxx"
userPhoneNr
:
"555555555555"
userProfileAgeFrom
:
"["1"]"
userProfileAgeTo
:
"["3"]"
userProfileWage
:
"9.60"
userQuote
:
"c"
userRetypePassword
:
""
userSex
:
"m"
user_id
:
"6"

【问题讨论】:

  • var_dump($_POST) 返回什么?
  • @Cornwell var dump 什么都不返回,如果我把它放在函数里面
  • $userProfileAgeFrom$userProfileAgeTo$user_id 定义在哪里?您的查询也写为UPDATE 而不是INSERT INTO。我显然不明白这个问题。
  • @Chay22,它应该被更新---编辑。 $userProfileAgeFrom 和 To 来自 $_POST。它们的定义如下 $user_id = $_POST['user_id']; $userProfileAgeTo=trim($_POST['userProfileAgeTo']); $userProfileAgeFrom= trim($_POST['userProfileAgeFrom']);
  • 请告诉我们console.log(formData);的输出

标签: javascript php mysql arrays pdo


【解决方案1】:

$userProfileAgeFrom 和 $userProfileAgeTo 的结果似乎都是数组,因此插入将在 for 循环中进行。并希望这两个数组的计数相同。

$userProfileAgeFrom = $_POST['userProfileAgeFrom'];
$userProfileAgeTo = $_POST['userProfileAgeTo'];

for ($i = 0; $i < count($userProfileAgeFrom); $i++) {
    $user_profile_age_range = $user_home->runQuery("UPDATE nanny_age_range SET age_minimum=:userProfileAgeFrom, age_maximum=:userProfileAgeTo WHERE user_id=:user_id ");
    $user_profile_age_range->bindparam(':userProfileAgeFrom', $userProfileAgeFrom[$i], PDO::PARAM_STR);
    $user_profile_age_range->bindparam(':userProfileAgeTo', $userProfileAgeTo[$i], PDO::PARAM_STR);
    $user_profile_age_range->bindparam(':user_id', $user_id, PDO::PARAM_STR);
    $user_profile_age_range->execute();
}

【讨论】:

  • 此解决方案确实会更新 DB 中的值,但会将行更新为相同的结果 - 假设我输入了 1-3 和 5-7,这两行都是 5-7跨度>
  • 这是因为您尝试使用 user_id 运行更新查询。尝试为表 nanny_age_range 提供自动增量 id 并根据该 id 进行更新。
【解决方案2】:

根据 OP 评论,console.log(formData) 显示如下:

userProfileAgeFrom: "["1"]"
userProfileAgeTo: "["3"]"

这意味着,现在您的值中有一个 JSON 数组。所以你需要对其进行解码,并得到它的第一个值:

$userProfileAgeFrom = json_decode($_POST['userProfileAgeFrom'],true)[0], 
$userProfileAgeTo = json_decode($_POST['userProfileAgeTo'],true)[0]

编辑

基于 OP 评论。

因此,如果您的 userProfileAgeFrom 和其他人有更多价值,那么请遍历它们:

for ($i = 0; $i < count($_POST['userProfileAgeFrom']); $i++) {
    $user_profile_age_range = $user_home->runQuery("UPDATE nanny_age_range SET age_minimum=:userProfileAgeFrom, age_maximum=:userProfileAgeTo WHERE user_id=:user_id ");
    $user_profile_age_range->bindparam(':userProfileAgeFrom', $_POST['userProfileAgeFrom'][$i], PDO::PARAM_STR);
    $user_profile_age_range->bindparam(':userProfileAgeTo', $_POST['userProfileAgeTo'][$i], PDO::PARAM_STR);
    $user_profile_age_range->bindparam(':user_id', $user_id, PDO::PARAM_STR);
    $user_profile_age_range->execute();
}

警告

但这会很糟糕,因为WHERE user_id=:user_id,您的所有行都将相同

我认为你应该重新设计你的代码。

【讨论】:

  • 但是如果还有更多呢?最多有 4 个不同的范围(抱歉回复晚了)。
  • 也试过了,得到这个:警告:json_decode() 期望参数 1 是字符串,给定数组
  • 任何建议我如何编辑正确的行,所以它们都不会一样?
  • 为所有字段创建一个隐藏字段,例如&lt;input type="hidden" name="userProfileAgeToOld[]" value="&lt;?php echo $oldValue[$keyOfOldValuesArray];?&gt;" /&gt; 并说WHERE userId = ... AND userProfileAge = userProfileAgeToOld[$i] AND ... 所以更新所有值。
  • 所以如果我添加隐藏输入并将行 ID 从数据库附加到值。然后我可以说像 update where user_id = user_id and age_range_id = id 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-12
  • 1970-01-01
相关资源
最近更新 更多