【发布时间】:2015-03-15 02:18:52
【问题描述】:
我在通过表单中的 ajax 调用连接到我的函数和数据库时遇到了一些问题。
<?php require_once("../includes/session.php"); ?>
<?php require_once("../includes/db_connection.php"); ?>
<?php require_once("../includes/functions.php"); ?>
<?php require_once("../includes/validation_functions.php"); ?>
<?php include("../includes/layouts/header.php"); ?>
<form action="Assets/ajax/userdetails.php" id="ajax-user" method="post">
<div class="well" style="border-color: #b81e1e; display: none;" id="details1">
<div>
<label for="FirstName">First Name:<br /></label>
<input name="FirstName" type="text" />
</div>
<div>
<label for="LastName">Last Name:<br /></label>
<input name="LastName" type="text" />
</div>
<div>
<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
<input class="btn btn-hero right" type="submit">
</div>
</form>
<?php include("../includes/layouts/footer.php"); ?>
Javascript 看起来像这样;
$(document).on("submit", "form#ajax-user", function() {
var that = $(this),
url = that.attr("action"),
type = that.attr("method"),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
}
});
return false;
});
我已经在提交时运行了 ajax,这很好。然后是运行php,但是一直报错;
警告:mysqli_query() 期望参数 1 为 mysqli,在 /home/public/Assets/ajax/userdetails.php 中的 12 行中给出 null
最后调用的php看起来如下,我认为这与范围有关,但我仍在学习并为此苦苦挣扎了几天,如果有人可以给我一些指示,那就太好了赞赏。
谢谢
<?php
if (isset($_POST['FirstName'], $_POST['LastName'], $_POST['gender'])) {
$current_user = $_SESSION["admin_id"];
$firstname = $_POST['FirstName'];
$lastname = $_POST['LastName'];
$gender = $_POST['gender'];
$query = "UPDATE users SET FirstName = '$firstname', LastName = '$lastname', Gender = '$gender' WHERE id = $current_user";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
}
?>
编辑
$connection 在 db_connection 中定义;
<?php
define("DB_SERVER", "localhost");
define("DB_USER", "****");
define("DB_PASS", "****");
define("DB_NAME", "****");
// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
?>
【问题讨论】:
-
希望我在这里提供了足够的信息,如果这是一个明显的错误,我们深表歉意!
-
你如何定义
$connection? -
根据您编辑的问题检查已编辑的答案。