使用php表单将记录添加到mysql数据库而不离开/刷新页面

Posted

技术标签:

【中文标题】使用php表单将记录添加到mysql数据库而不离开/刷新页面【英文标题】:Add records to mysql database with php form without leaving/refreshing the page 【发布时间】:2014-10-04 09:34:55 【问题描述】:

我使用这个文件 input.php 将记录添加到数据库:

$order = "INSERT INTO wp_userdata
            (username, product_name, product_brand)
            VALUES
            ('$_POST[username]',
                        '$_POST[name]',
            '$_POST[brand]')";


$result = mysql_query($order);  
if($result)
    header( 'Location: http://page-with-form.php' ) ;
 else
    echo("<br>Input data is fail");

还有我的页面表单page-with-form.php

<table border="1">
  <tr>
    <td align="center">Add Products</td>
  </tr>
  <tr>
    <td>
      <table>
        <form method="post" action="input.php">
<input type="hidden" name="username" value="[insert_php]echo $username;[/insert_php]">
        <tr>
          <td>Product Name</td>
          <td><input type="text" name="name" size="50">
          </td>
        </tr>
        <tr>
          <td>Brand</td>
          <td><input type="text" name="brand" size="50">
          </td>
        </tr>
        <tr>
          <td></td>
          <td align="right"><input type="submit" name="submit" value="Send"></td>
        </tr>
</form>
        </table>
      </td>
    </tr>
</table>

一切正常:当我单击“发送”按钮时,input.php 添加记录并重定向回 page-with-form.php。您甚至看不到 input.php 加载,但是您确实看到 page-with-form.php 正在刷新。

有没有办法在不刷新page-with-form.php的情况下进行所有操作?我认为这与 Ajax 有关,但也许还有另一种方式?期待您的建议!

【问题讨论】:

是的......如果你不想刷新页面,你应该使用 ajax。 是的。 Ajax 就是你想要的。不过,写另一个 Ajax 教程对于一个*** 问题来说太宽泛了。 如果您不想更新视图,也可以使用普通表单提交并发出 204 No Content HTTP 响应。 您的 html 无效。使用validator。 请learn to love labels 【参考方案1】:

你必须使用ajax将数据插入mysql而无需页面刷新

<form method='post' id='SaveForm' action="#">

<table class='table table-bordered'>

    <tr>
        <td>Name</td>
        <td><input type='text' name='name' /></td>
    </tr>

    <tr>
        <td>Employee Department</td>
        <td><input type='text' name='dept' ></td>
    </tr>

    <tr>
        <td colspan="2">
        <button type="submit" name="btn-save" id="btn-save"></button>  
        </td>
    </tr>

</table>

PHP 代码是:

<?php
 if($_POST)
 
    $emp_name = $_POST['name'];
    $emp_dept = $_POST['dept'];

    try

     $stmt = $db_con->prepare("INSERT INTO tbl_employees(emp_name,emp_dept)   VALUES(:ename, :edept)");
     $stmt->bindParam(":ename", $emp_name);
     $stmt->bindParam(":edept", $emp_dept);

     if($stmt->execute())
     
        echo "Successfully Added";
     
     else
     echo "Query Problem";
      
  
    catch(PDOException $e)
       echo $e->getMessage();
    
  

?>

jquery ajax 代码是:

/* Data Insert Starts Here */
   $(document).on('submit', '#emp-SaveForm', function() 

    $.post("create.php", $(this).serialize())
    .done(function(data)
     $("#dis").fadeIn('slow', function()
     $("#dis").html('<div class="alert alert-info">'+data+'</div>');
     $("#emp-SaveForm")[0].reset();
     ); 
   );   
  return false;
);
/* Data Insert Ends Here */

点击以下链接获取详细文章:

jQuery Ajax Insert, Update and Delete with PHP MySQL

【讨论】:

【参考方案2】:

你将不得不使用 ajax 来实现你的目标让我们以这个简单的 html 表单为例

<form id='myform' action='insert.php' method='post'>
  Name: <input type='text' name='name' />
  Address: <input type='text' name='address' />
</form>

而php是

$name = $_POST['name'];
$address= $_POST['address'];
$sql = "insert into peoples (name,address) values('$name','$address')";
if(mysql_query($sql))
   echo 'successfully inserted';
else
   echo 'could not insert';

你的 jQuery javascript

$('#myform').submit(function() return false; );
$('#submit').click(function()
   $.post($('#myform').attr('action'),
   $('#myform :input').serializeArray(),
function(output)   $('#result').html(output); ); );

For detailed description you check here

【讨论】:

【参考方案3】:

您想使用 AJAX 提交表单,

您可以使用 JQuery 来帮助您,您需要做的第一件事是确保您的表单不会刷新页面,并为您的按钮指定一个 ID,这样可以更轻松地通过 JQuery 找到按钮

首先让我们从您的 PHP 代码中删除导致服务器端重定向的那一行,而是让它生成一个字符串,说明数据已成功保存,无论该脚本在 HTTP 响应中打印什么,都将被 ajax 部分使用这个项目

$order = "INSERT INTO wp_userdata
            (username, product_name, product_brand)
            VALUES
            ('$_POST[username]',
                        '$_POST[name]',
            '$_POST[brand]')";


$result = mysql_query($order);  
if($result)
    echo ("DATA SAVED SUCCESSFULLY");
 else
    echo("Input data is fail");

然后让我们修改 HTML 让 Jquery 更容易找到我们需要的元素并输出一个状态(这不是唯一的方法,如果你有多个表单不建议这样做,Jquery 有更复杂的查找表单的方法元素http://api.jquery.com/input-selector/)

我只想简单地说明这个想法,而不是过多地介绍 Jquery 细节。

<table border="1">
      <tr>
        <td align="center">Add Products</td>
      </tr>
      <tr>
        <td>
          <table>
            <!-- THIS TELLS THE FORM TO NOT REFRESH THE PAGE -->
            <form onsubmit="return false">
    <input type="hidden" name="username" id="hdn_username" value="[insert_php]echo $username;[/insert_php]">
            <tr>
              <td>Product Name</td>
              <td><input type="text" id="txt_name" name="name" size="50">
              </td>
            </tr>
            <tr>
              <td>Brand</td>
              <td><input type="text" id="txt_brand" name="brand" size="50">
              </td>
            </tr>
            <!-- THIS ROW WILL DISPLAY THE RESULT OF THE LAST ENTRY -->`
            <tr>
                <td></td>
                <td><div id="status_text" /></td>
            </tr>
            <tr>
              <td></td>
              <td align="right">
                <!-- I GAVE THE BUTTON AN ID THAT WILL MAKE IT EASIER TO FIND WITH JQUERY -->
                <input type="submit" id="btn_submit" name="submit" value="Send"></td>
            </tr>
    </form>
            </table>
          </td>
        </tr>
    </table>

现在是使用 Jquery 帮助实现 AJAX 的 Javascript 版本

Javascript 会做的是,当你点击按钮时,它会发布到你的 input.php 并且输入 PHP 会返回一个结果文本。

//on the click of the submit button 
$("#btn_submit").click(function()
 //get the form values
 var username = $('#hdn_username').val();     
 var name = $('#txt_name').val();     
 var brand = $('#txt_brand').val(); 

 //make the postdata
 var postData = 'username='+username+'&name='+name+'&brand='+brand;

 //call your input.php script in the background, when it returns it will call the success function if the request was successful or the error one if there was an issue (like a 404, 500 or any other error status)

 $.ajax(
    url : "input.php",
    type: "POST",
    data : postData,
    success: function(data,status, xhr)
    
        //if success then just output the text to the status div then clear the form inputs to prepare for new data
        $("#status_text").html(data);
        $('#name').val('');
        $('#brand').val('');
    ,
    error: function (jqXHR, status, errorThrown)
    
        //if fail show error and server status
        $("#status_text").html('there was an error ' + errorThrown + ' with status ' + textStatus);
    
);

应该发生的是,您在表单中输入数据,您会看到显示成功或错误的状态,如果成功,表单将清除以供您添加更多输入。

【讨论】:

感谢您的详细回答,Oluwakayode!我复制了文本,但由于某种原因,当我单击按钮时没有任何反应。这是页面suppliesprices.com/?page_id=4 我没有看到您的页面中包含 jquery 库,另外,您需要关闭 ondocument 就绪调用,在第 66 行您需要另一个“);” 它现在可以工作了,非常感谢,这正是我想要的!不敢相信 wordpress 页面没有自己加载 jquery,必须对其进行硬编码才能使其工作。现在,有没有办法刷新从同一页面上的查询中打印出来的列表以更新以显示添加的新记录? 我在简单托管中尝试了上面的代码,但没有成功,当我点击发送按钮时没有任何反应,【参考方案4】:

你想要的

Button.click(function()
 $.Ajax(
  Data: data,
  Success: 
   What you want to do on success
   Such as set HTML to div element
  )
 )

只需查找 Ajax 的 jQuery API,它就在那里。

写在手机上,所以如果你需要我可以在以后扩展答案。

【讨论】:

以上是关于使用php表单将记录添加到mysql数据库而不离开/刷新页面的主要内容,如果未能解决你的问题,请参考以下文章

使用 Ajax、PHP、MYSQL 更新表单

如何在 .Net Core 中提交表单而不离开当前视图并保留当前模型

将数据从下拉菜单提交到mysql而不刷新页面

MySql:将数据添加到列而不删除以前的数据

通过 Bootstrap Modals PHP MySQL 创建搜索记录表单

使用ajax将表单提交给php而不刷新页面