繁体   English   中英

提交按钮以将值输入数据库而无需表单操作PHP

[英]submit button to input value to database without form action PHP

我想单击提交并将字段中输入的值存储在数据库中。

但是,我不想使用表单操作。 是否可以在不使用PHP创建表单操作的情况下做到这一点?

<tr>
<form method="post">
<tr>
    <td>
        <label for="Item name"><b>Finish Product:</b></label>
    </td>
    <td>
        <input id="finish_product" type="text" maxlength="100" style="width:100px"name="finish_product" required>
    </td>
</tr>
<tr>
    <td>
        <input type="submit" value="Save" id="submit" />
    </td>
</tr>

<?php
if(isset($_POST['submit']))
{
var_dump($_POST); exit;

$SQL = "INSERT INTO bom (finish_product) VALUES ('$finish_product')";
$result = mysql_query($SQL);
}?>
</tr>

使用Jquery ajax执行此操作。 试试这个: HTML

<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<body>
<table>
<tr>
<td><label for="Item name"><b>Finish Product:</b></label></td>
<td><input id="finish_product" type="text" maxlength="100" style="width:100px" name="finish_product" required></td>
</tr>
</table>
<input type="button" value="Save" id="submit" />
    <script>
    $(document).ready(function(){
       $('#submit').click(function(){
          $.ajax({
                url: '1.php',
                data: {finish_product: $('#finish_product').val()},
                success: function (result) {
                    alert(result)
                }
            });
       });
    });
    </script>
</body>

PHP (1.php)

注意 :由于mysql_query在最新版本中已被描述,因此使用mysqli_query。 并使用bind参数,而不是直接将值附加到查询中。

<?php
if (!empty($_GET)) {
    $SQL = "INSERT INTO bom (finish_product) VALUES ('".$_GET['finish_product:']."')";
    $result = mysql_query($SQL);
    echo 1;
} else {
    echo -1;
}
?>
  1. 这不是form ,而是一系列具有各种输入和一个提交按钮的表格元素。 清理代码-没有结束tr标记,提交按钮应该在哪里?
  2. 在其周围添加一个form元素。
  3. 您需要formmethod属性-在这种情况下为“ post”。 没有action属性,它将默认为同一页面。

<!-- add form tag -->
<form method="post">
    <tr>
        <td>
            <label for="Item name"><b>Finish Product:</b></label>
        </td>
        <td>
            <input id="finish_product" type="text" maxlength="100" style="width:100px"name="finish_product" required>
        </td>
    </tr>
    <!-- added new row for submit button - you might want to have the td element span two columns? -->
    <tr>
        <td>
            <input type="submit" value="Save" id="submit" />
        </td>
    </tr>
</form>
<-- end of form -->

<?php
if(isset($_POST['submit']))
{
    //see what is being POSTED - comment out this line when you're happy with the code!
    var_dump($_POST); exit;

    $SQL = "INSERT INTO bom (finish_product) VALUES ('$finish_product')";
    $result = mysql_query($SQL);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM