mysql - 使用 AJAX 向服务器发送数据

标签 mysql ajax

我需要一些关于以下问题的帮助。以下代码对我不起作用。有没有人可以帮助我?我在 youtube 视频中看过这个,但我找不到为什么它没有运行.. 我想通知您,我在 127.0.0.1 运行一个 WAMP 服务器,很奇怪浏览器没有给我任何错误响应,等等。

这是我的 PHP 代码:

<?php
$host="127.0.0.1";
$username = "root";
$password = "";
$db = "data";

$conn = mysqli_connect($host, $username, $password, $db);


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

    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $gender = $_POST['slct'];

    $query = "Insert into users (firstname, lastname,gender) Values(?,?,?))";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('sss', $fname, $lname, $gender);
    $stmt->execute();

    if(mysqli_affected_rows($conn) > 0){
        echo "insert";
    }
    else{
        echo "no";
    }

}
?>

这是我的 html 代码:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>

<h3> Insert Data into Database</h3>
<form id="form1" method="post">
<p> Enter FirstName</p>
<input type="text" name="fname" class="form-control">
<br>
<p> Enter lastName</p>
<input type="text" name="lname" class="form-control">
<br>
<p>Enter Gender</p>
<select class="form-control" name="slct">
<option value="Male">Male </option>
<option value="Female">Female</option>
</select>
<br><br><br>
<button class="btn btn-primary" onclick="insertData()">Submit</button>

</form>


</body>

<script>
    function insertData(){

        var formData = $('#form1').serialize();

        $.ajax({
        url:'http://127.0.0.1/PHP/insert.php',
        data:formData,
        type:'Post',
        success:function(response){
        console.log(response);

        },
        error:function(err){
            console.log(err);

        }

        })

    }
</script>

</html>

任何帮助将不胜感激。 提前致谢!

最佳答案

您的插入命令不正确。将 ...(?,?,?))"; 更改为 ...(?,?,?)";

最好使用像 netbeans 这样的 IDE,因为它们会突出显示此类错误。你也应该从 mysqli 切换到 PDO。而且您不需要检查受影响的行。 $stmt->execute() 返回一个 bool 值

关于mysql - 使用 AJAX 向服务器发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51984260/

相关文章:

mysql - SQL : Using the target table in an UPDATE statement in a nested FROM clause

php - Mysql/PHP错误: not displaying $username

php - 使用 PHP Ajax 将开/关按钮的值存储在 MySQL 数据库中

java - 使用 Tapestry 的 Bootstrap 模式内的 Ajax 区域形式

javascript - Reactjs 在单击按钮时多次触发 AJAX 调用(每次单击只需要 1 次!)

python - 将 XML 加载到 MySQL

Mysql 从 future 日期时间中选择分钟 - now()

mysql - 使用 Visual Studio 在 WINDOWS STORE 中发布带有 Mysql.dll 的 UWP 时出错

jquery - 等待jquery ajax请求完成并返回值

php - Ajax成功函数不输出Php脚本发送的文本