通过ajax在mysql中保存数据

时间:2017-11-23 11:04:34

标签: php ajax

我试图使用ajax在数据库中发送数据值,但它无法正常工作。请任何人帮助我。 我试图使用ajax在数据库中发送数据值,但它不起作用。请任何人帮助我。

form.php的

<!DOCTYPE html>
<html>
<head>
    <title></title>

</head>
<body>
    <form id="send_value" action="form.php" method="post">
        <input type="text" name="name" value="" id="name">
        <input type="text" name="address" value="" id="address">
        <input type="submit" value="submit" id="save">
    </form>
     <script type="text/javascript">
        $(document).ready(function() {
            $('#save').click(function() {
                var name = $('#name').val();
                var address = $('#address').val();
                $.ajax({
                    type: "POST",
                    cache: false,        
                    url: 'ajax.php',
                    data: { name: name, address: address},
                    success: function(data) {
                        alert('data has been stored to database');
                    }
                });
            });
        });
    </script>
</body>
</html>

和php文件

<?php 
include('DataModel.php');

$con = mysqli_connect("localhost","root","","ajax_test");
if (!$con) 
{
    die();
}
$name = $_POST['name'];
$address = $_POST['address'];

$sql = "INSERT INTO `test`(`name`, `address`) VALUES ($name,$address) ";
$query = mysqli_query($sql,$con);
$fetch = mysqli_fetch_assoc($query);
echo json_encode($fetch);
 ?>

2 个答案:

答案 0 :(得分:2)

查询周围缺少引号

$sql = "INSERT INTO `test`(`name`, `address`) VALUES ('$name', '$address')";

您还应该使用预准备语句,但至少请在将字符串传递给查询之前将其转义为

$name = mysqli_real_escape_string($con, $_POST['name']);
$address = mysqli_real_escape_string($con, $_POST['address']);

为了避免遇到包含单引号的地址或名称的错误,或者让自己对SQL注入攻击持开放态度。

答案 1 :(得分:1)

你忘记了这里的引语

$http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/500.json')
    .success(function(data) {
      if (data.length > 0) {
        $scope.gridOptions.data = data;
      } else {
        $scope.noData = true;
      }
    });

或者你可以像这样绑定param

 <div class="watermark" ng-show="noData">No data available</div>