duanliang5051 2016-03-29 15:06
浏览 63
已采纳

如何使用PHP,AJAX和JSON使用mysqli插入数据?

PHP

    $data = array(
        'success' => false,
        'errors' => array()
    );

    if(isset($_POST['inputs'])) {


            $inputs = $_POST['inputs'];
            foreach($inputs as $input) {

                    $name = $input['name'];
                    $value = $input['value'];

                    switch ($name) {
                            case 'email':
                                    if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
                                            $msg = "You must provide a valid e-mail address";
                                    }
                                    break;

                            default:
                                    $msg = "Sorry, we do not understand the data, please try again";
                                    break;
                    }

                    if(!empty($msg)) {
                            $data['errors'][] = array(
                                    'msg' => $msg,
                                    'field' => $name
                            );
                    }
            }

            if(empty($data['errors'])) {
                    $data['success'] = true;

                    $json = file_get_contents('php://input');
                    $obj = json_decode($json,true);

                    foreach ($obj as $item) {
                            $query = "INSERT INTO users (email)

                            VALUES

                            ('".$item['email']."')";

                            $objConnection->query($query) or die($objConnection->error);
                            $objConnection->close();
                    }

            }

    } else {
            $data['errors'][] = "Data missing";
    }
    header("Content-type: application/json; charset=UTF-8");
    echo json_encode((object)$data);

Jquery / AJAX

$(function() {
    $('.submit').click(function() {

            var formInputs = new Array();

            var formId = $(this).parent().attr('id');

            $('#' + formId + ' input').each(function() {

                    var obj = {
                        'value': $(this).val(),
                        'name': $(this).attr('name')
                    };

                    formInputs.push(obj);
            });

            $.ajax({
                    url: 'add.php',
                    type: 'POST',
                    dataType: 'json',
                    cache: false,
                    data: {
                            'inputs': formInputs
                    },
                    success: function(data) {
                            if(data.success) {
                                    $(".hej").html("worked");
                            } else {
                                    $.each(data.errors, function() {
                                            var list = "<p>"+this.msg+"</p>";
                                            $(".hej").html(list);
                                    });
                            }
                    }
            });

            return false;

    });
});

I have been searching for an answer, to see if I could figure it out myself, I did find this Insert data with JSON and mysql . It seems to be working, besides that it gives me an error that says: "Invalid argument supplied for foreach()". If anyone has a better method / solution to insert the data, I am open ears.

  • 写回答

2条回答 默认 最新

  • dongliu4320 2016-04-06 15:55
    关注

    I figured it out!

    if(empty($data['errors'])) {
    
        $data['success'] = true;
    
        $inputs = $_POST['inputs'];
        $email = $inputs[0]['value']; // I select the first element in my array, then I select its value
        $password = $inputs[1]['value']; // I select the second element in my array, then I select its value
    
        $query = "INSERT INTO users (email, password)
    
        VALUES
    
        ('{$email}', '{$password}')";
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿