使用AJAX的PHP更新MySQL表 [英] Update mysql table with php using ajax

查看:175
本文介绍了使用AJAX的PHP更新MySQL表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我创建一个表 http://jsbin.com/OJAnaji/13/edit 和演示: http://jsbin.com/OJAnaji/13

所以当用户点击上表中的一些行全自动填充从表中的值成模态窗口输入字段。模态窗口用户打开时,点击按钮编辑行。现在我需要知道我可以更新mysql表的列:姓名,性别,年龄,甜甜圈吃。

我创建的js AJAX:

  $(#编辑)。点击(函数(){
    //在这里我们可以做阿贾克斯之后验证字段不为空。
    如果($(#名称)。VAL()!=){
        $阿贾克斯({
            网址:update.php
            键入:POST,
            异步:真正的,
            数据:{名称:$(#NAME)VAL(),性别:$(#性别)VAL(),年龄:$(#时代)VAL(),Donuts_eaten:$( #donuts_eaten)。VAL()} //你的表单数据后接着在这里作为一个JSON对象
            数据类型:HTML,

            成功:功能(数据){
                $('#输出)HTML(数据);
                drawVisualization();
            },
        });
    } 其他 {
        //通知他们需要输入数据的用户
    }
});
 

HTML - 模态窗口和按钮:

 <! - 按键触发模式 - >
<按钮ID =编辑级=BTN BTN-成功禁用类型=按钮数据切换=莫代尔数据目标=#myModal>
编辑选中的行< /按钮>

<! - 模态 - >
< D​​IV CLASS =模式变脸ID =myModal的tabindex = -  1角色=对话框中的咏叹调 -  labelledby =myModalLabelARIA隐藏=真>
  < D​​IV CLASS =模式 - 对话>
    < D​​IV CLASS =模式的内容>
      < D​​IV CLASS =模式的首部>
        <按钮式=按钮级=关闭数据解雇=莫代尔ARIA隐藏=真>&安培;倍;< /按钮>
        < H4类=模式的标题ID =myModalLabel>添加新行< / H4>
      < / DIV>
      < D​​IV CLASS =模态体>
        < D​​IV CLASS =输入组>
  <跨度类=输入组插件>名称< / SPAN>
  <输入类型=文字值=ID =名级=表单控制占位符=输入名称>
        < / DIV>< / BR>
        < D​​IV CLASS =输入组>
  <跨度类=输入组插件>性别< / SPAN>
  <输入类型=文本ID =性别类=表单控制占位符=?性别>
< / DIV>< / BR>
        < D​​IV CLASS =输入组>
  <跨度类=输入组插件>年龄< / SPAN>
  <输入类型=文本ID =年龄级=表单控制占位符=时代的数目>
< / DIV>< / BR>
        < D​​IV CLASS =输入组>
  <跨度类=输入组插件>甜甜圈吃< / SPAN>
  <输入类型=文本ID =donuts_eaten级=表单控制占位符=吃甜甜圈数>
< / DIV>< / BR>

      < / DIV>
      < D​​IV CLASS =模式躯>
        <按钮式=按钮级=BTN BTN默认数据解雇=模式>关闭< /按钮>
        <按钮式=按钮级=BTN BTN小学>保存更改< /按钮>
      < / DIV>
    < / DIV><! -  /.modal-content  - >
  < / DIV><! -  /.modal-dialog  - >
< / DIV><! -  /.modal  - >
 

所以,我怎么能现在更新与PHP的MySQL数据库:

这样的文件update.php如何必须是这样的:

 < PHP
$ CON =的mysql_connect('本地主机','gmaestro_agro,通行证)或死亡(错误连接到服务器);

mysql_select_db('gmaestro_agro',$ CON);

//我怎么可以更新MySQL数据库,我需要什么补充吗?

?>
 

解决方案

您应该在表这是一个自动增量列,如身份证或者像下面的示例使用index_id的一列。这应该创建表单时使用,而且随着$ _POST数组引用要更新的行发送。这是一个简单的例子,你可以用它来让你开始。

  $ _ POST = stripslashes_deep($ _ POST); #你将要为安全更好的过滤。
    如果(使用isset($ _ POST ['名称'])及和放大器;!$ _ POST('名称')=''){

    $查询=更新统计
              集名称='。$ _ POST ['名'。'
                  性别='。$ _ POST ['性别'。'
                  年龄='。$ _ POST ['时代'。'
                  Donuts_eaten ='。$ _ POST ['Donuts_eaten'。'
             哪里
                 index_id的='。$ _ POST ['index_id的'。';

    $结果= mysql_query($查询)或死亡(mysql_error());
    退出(json_en code($ _ POST));
    }


    功能stripslashes_deep($值)
    {
        $值= is_array($值)?
            array_map('stripslashes_deep',$值):
            函数stripslashes($值);

        返回$价值;
    }
 

有关你的MySQL表,你可以在你的MySQL phpMyAdmin的运行如下命令:

  ALTER TABLE`stats`加上`index_id` INT(3)NOT NULL AUTO_INCREMENT第一,
ADD PRIMARY KEY(`index_id`)
 

Here I create a table http://jsbin.com/OJAnaji/13/edit and DEMO: http://jsbin.com/OJAnaji/13

So when users click on some row on table automaticly populate input fields with values from table into modal window. Modal window user open when click on button "Edit row". Now I need to know how I can update mysql table with columns: Name,Gender,Age,Donuts eaten.

I create js ajax:

$("#edit").click(function() {
    //in here we can do the ajax after validating the field isn't empty.
    if($("#name").val()!="") {
        $.ajax({
            url: "update.php",
            type: "POST",
            async: true, 
            data: { Name:$("#name").val(), Gender:$("#gender").val(), Age:$("#age").val(), Donuts_eaten:$("#donuts_eaten").val()}, //your form data to post goes here as a json object
            dataType: "html",

            success: function(data) {
                $('#output').html(data); 
                drawVisualization();   
            },  
        });
    } else {
        //notify the user they need to enter data
    }
});

HTML - modal window and button:

<!-- Button trigger modal -->
<button id="edit" class="btn btn-success disabled" type="button" data-toggle="modal" data-target="#myModal">
Edit selected row</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Add new row</h4>
      </div>
      <div class="modal-body">
        <div class="input-group">
  <span class="input-group-addon">Name</span>
  <input type="text" value="" id="name" class="form-control" placeholder="Type name">
        </div></br>
        <div class="input-group">
  <span class="input-group-addon">Gender</span>
  <input type="text" id="gender" class="form-control" placeholder="Gender?">
</div></br>
        <div class="input-group">
  <span class="input-group-addon">Age</span>
  <input type="text" id="age" class="form-control" placeholder="Number of age">
</div></br>
        <div class="input-group">
  <span class="input-group-addon">Donuts eaten</span>
  <input type="text" id="donuts_eaten" class="form-control" placeholder="Number of donuts eaten">
</div></br>

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

So how I can now update MySql database with php:

so file update.php how must looks like:

<?php
$con = mysql_connect('localhost', 'gmaestro_agro', 'pass') or die('Error connecting to server');

mysql_select_db('gmaestro_agro', $con); 

//HOW I CAN UPDATE MYSQL DATABASE, WHAT I NEED TO ADD HERE?

?>

解决方案

You should have a column in the table which is an auto-increment column, such as "id" or like the example below uses "index_id". This should be used when creating your form, and sent along with the $_POST array to reference the row you are updating. This is a simple example, which you can use to get you started.

 $_POST = stripslashes_deep($_POST); # you will want to better filtering for security.
    if(isset($_POST['Name']) && $_POST('Name') !=''){

    $query = "UPDATE stat
              SET Name   ='". $_POST['Name'] . "',
                  Gender ='". $_POST['Gender'] . "',
                  Age    ='". $_POST['Age'] . "',
                  Donuts_eaten  ='" .$_POST['Donuts_eaten'] . "'
             WHERE
                 index_id = '". $_POST['index_id'] . "'";

    $result = mysql_query($query) or die(mysql_error()); 
    exit(json_encode($_POST)); 
    }


    function stripslashes_deep($value)
    {
        $value = is_array($value) ?
            array_map('stripslashes_deep', $value) :
            stripslashes($value);

        return $value;
    }

For your MYSQL table you can run this in your MYSQL PhpMyAdmin:

ALTER TABLE  `stats` ADD  `index_id` INT( 3 ) NOT NULL AUTO_INCREMENT FIRST ,
ADD PRIMARY KEY (  `index_id` )

这篇关于使用AJAX的PHP更新MySQL表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆