【问题标题】:Using A $_GET Variable inside a function for database insert?在数据库插入函数中使用 $_GET 变量?
【发布时间】:2017-06-14 22:26:59
【问题描述】:

希望有人能对我遇到的问题有所了解。

我有一个用于向页面添加评论的表单;

    <?php if(app('current_user')->role != 'user'): ?>
        <div class="leave-comment">
            <div class="control-group form-group">
                <h5><?= trans('leave_comment'); ?></h5>
                <div class="controls">
                    <textarea class="form-control" id="comment-text"></textarea>
                </div>
            </div>
            <div class="control-group form-group">
                 <div class="controls">
                    <button class="btn btn-success" id="comment">
                        <i class="fa fa-comment"></i>
                        <?= trans('comment'); ?>
                    </button>
                </div>
            </div>
        </div>
    <?php else: ?>
        <p><?= trans('you_cant_post'); ?></p>
    <?php endif; ?>

这里使用ajax来加载下面的case;

case "postComment":
    echo app('comment')->insertComment(ASSession::get("user_id"), $_POST['comment']);
    break;

哪些加载;

public function insertComment($userId, $comment)
{
    $userInfo = $this->users->getInfo($userId);
    $datetime = date("Y-m-d H:i:s");

    $this->db->insert("as_comments", array(
        "posted_by" => $userId,
        "posted_by_name" => $userInfo['username'],
        "comment" => strip_tags($comment),
        "post_time" => $datetime,
        "FK_DappID" => 1
    ));

    return json_encode(array(
        "user" => $userInfo['username'],
        "comment" => stripslashes(strip_tags($comment)),
        "postTime" => $datetime
    ));
}

cmets 在一个名为 view.php 的页面上使用,我有一个变量,它是从名为 $_GET['ID'] 的 htis 页面的 URL 设置的。

所以..

如何将要插入数据库的数组中的 "FK_DappID" => 1 更改为 $_GET['ID'] 的值?

我尝试过使用 "FK_DappID" => $_GET['ID'] 但它不起作用..

任何帮助都会非常感激。

谢谢,B.

编辑:Index.js

$(document).ready(function () {

//comment button click
$("#comment").click(function () {
    //remove all error messages
    asengine.removeErrorMessages();

    var comment = $("#comment-text"),
         btn    = $(this);

    //validate comment
    if($.trim(comment.val()) == "") {
        asengine.displayErrorMessage(comment, $_lang.field_required);
        return;
    }

    //set button to posting state
    asengine.loadingButton(btn, $_lang.posting);

     $.ajax({
        url: "ASEngine/ASAjax.php",
        type: "POST",
        data: {
            action : "postComment",
            comment: comment.val()
        },
        success: function (result) {
            //return button to normal state
            asengine.removeLoadingButton(btn);
            try {
               //try to parse result to JSON
               var res = JSON.parse(result);

               //generate comment html and display it
               var html  = "<blockquote>";
                    html += "<p>"+res.comment+"</p>";
                    html += "<small>"+res.user+" <em> "+ $_lang.at +res.postTime+"</em></small>";
                    html += "</blockquote>";
                if( $(".comments-comments blockquote").length >= 7 )
                    $(".comments-comments blockquote").last().remove();
                $(".comments-comments").prepend($(html));
                comment.val("");
            }
            catch(e){
               //parsing error, display error message
               asengine.displayErrorMessage(comment, $_lang.error_writing_to_db);
            }
        }
    });
});

});

编辑:Ajax.php

include_once 'AS.php';

$action = $_POST['action'];

开关 ($action) { 案例“检查登录”: app('login')->userLogin($_POST['username'], $_POST['password']); 休息;

case "registerUser":
    app('register')->register($_POST['user']);
    break;

case "resetPassword":
    app('register')->resetPassword($_POST['newPass'], $_POST['key']);
    break;

case "forgotPassword":
    $result = app('register')->forgotPassword($_POST['email']);
    if ($result !== true) {
        echo $result;
    }
    break;

case "postComment":
    echo app('comment')->insertComment(ASSession::get("user_id"), $_POST['comment']);
    break;

case "updatePassword":
    app('user')->updatePassword(
        ASSession::get("user_id"),
        $_POST['oldpass'],
        $_POST['newpass']
    );
    break;

case "updateDetails":
    app('user')->updateDetails(ASSession::get("user_id"), $_POST['details']);
    break;

case "changeRole":
    onlyAdmin();

    $result = app('user')->changeRole($_POST['userId'], $_POST['role']);
    echo ucfirst($result);
    break;

case "deleteUser":
    onlyAdmin();

    $userId = (int) $_POST['userId'];
    $users = app('user');

    if (! $users->isAdmin($userId)) {
        $users->deleteUser($userId);
    }
    break;

case "getUserDetails":
    onlyAdmin();

    respond(
        app('user')->getAll($_POST['userId'])
    );
    break;

case "addRole":
    onlyAdmin();

    respond(
        app('role')->add($_POST['role'])
    );
    break;

case "deleteRole":
    onlyAdmin();

    app('role')->delete($_POST['roleId']);
    break;


case "addUser":
    onlyAdmin();

    respond(
        app('user')->add($_POST)
    );
    break;

case "updateUser":
    onlyAdmin();

    app('user')->updateUser($_POST['userId'], $_POST);
    break;

case "banUser":
    onlyAdmin();

    app('user')->updateInfo($_POST['userId'], array('banned' => 'Y'));
    break;

case "unbanUser":
    onlyAdmin();

    app('user')->updateInfo($_POST['userId'], array('banned' => 'N'));
    break;

case "getUser":
    onlyAdmin();

    respond(
        app('user')->getAll($_POST['userId'])
    );
    break;

default:
    break;
}

function onlyAdmin()
{
if (! (app('login')->isLoggedIn() && app('current_user')->is_admin)) {
    exit();
}
}

【问题讨论】:

  • 向我们展示你的 ajax
  • @RyanTuosto 添加了

标签: php arrays get insert


【解决方案1】:

您正在使用type: "POST" 提交您的ajax,因此数据将在您的PHP 中的$_POST 变量中可用。

因为看起来您正在添加评论,所以这是要使用的正确请求动词,因此请在您的插入方法中更改为 "FK_DappID" =&gt;$_POST['ID'],并确保将 ID 添加到您在 AJAX 中发布的 data

您应该创建一个隐藏的表单输入 &lt;input type="hidden" id="post_id" name="post_id" value="&lt;?= $_GET['ID'] ?&gt;" /&gt;,然后从该输入中获取值以发送到您的 AJAX POST 请求中。

data: {
  action : "postComment",
  comment: comment.val(),
  ID: $("#post_id").val()
}

【讨论】:

  • 嗨,我正在传递变量 ID,localhost/Login/view.php?ID=1 然后使用 $PK_DappID = $_GET['ID']; 在视图页面上获取它我可以使用 POST 而不是 GET 来获取变量吗?感谢您的意见!
  • 确保只使用 $_POST['ID'] 代替,您还需要将其添加到您通过 ajax 发送的数据中
  • 嗨 Ryan,非常感谢您的帮助,希望您能原谅我缺乏编码知识。如何使用 POST 而不是 GET 将变量传递到新页面?我认为 GET 是从另一个页面带来价值的唯一方法。如果我在我的视图页面上使用 $PK_DappID = $_POST['ID'] 它不会从其他页面带来价值。谢谢,布拉德。
  • 不用担心,我认为这是一个常见的混淆点。您确实想使用 GET 将数据传递到帖子视图页面。然后要向该帖子添加评论,您需要使用 POST 请求并传递 ID 以将评论添加到正确的帖子。交换此数据的常用方法是通过隐藏的表单元素,在该元素中回显 $_GET 值,然后在 javascript 中检索它,以便通过 ajax 中的 POST 请求发回。我已经更新了我的答案以显示这一点。
  • 我已将隐藏的输入添加到页面,& ID: $("#post_id").val() 到 ajax 请求。我还在插入方法中设置了 "FK_DappID" => $_POST['ID'] 。到目前为止还没有运气,我注意到我忘记在我的代码中添加 ASAjax 页面,我现在将添加它,额外的参数是否也需要添加到那里?再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-09
  • 2017-03-16
  • 1970-01-01
相关资源
最近更新 更多