当我点击.deletePost
时,我收到以下错误。似乎$mysqli
是undefined
,但是我以相同的方式在类似的PHP脚本中使用它并且它没有这个错误,所以我很困惑到底是怎么回事。有人可以解释一下吗?谢谢!
错误:
Notice: Undefined variable: mysqli in C:\wamp\www\NightOwlSoftware\scripts\post_action.php on line 16
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\wamp\www\NightOwlSoftware\scripts\post_action.php on line 16
post_action.php
<?php
include 'db_connect.php';
include 'functions.php';
sec_session_start();
echo "<div>Hello World</div>";
echo "<div>Hello World</div>";
echo "<div>Hello World</div>";
echo "<div>Hello World</div>";
if($_GET['action'] == "deletePost")
deletePost($_GET['postTitle']);
function deletePost($title){
$sql = "DELETE FROM blog WHERE Title = '$title'";
mysqli_query($mysqli, $sql);
}
?>
的functions.php
<?php
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = false; // Set to true if using https.
$httponly = true; // This stops javascript being able to access the session id.
ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies.
$cookieParams = session_get_cookie_params(); // Gets current cookies params.
session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
session_name($session_name); // Sets the session name to the one set above.
session_start(); // Start the php session
session_regenerate_id(); // regenerated the session, delete the old one.
}
?>
dbconnect.php
<?php
$host="localhost"; // Host name
$username="root"; // username
$password="********"; // password
$dbname="nightowl"; // Database name
$tblname="blog"; // Table name
$mysqli=mysqli_connect($host,$username,$password,$dbname);
mysql_connect("$host", "$username", "$password");
mysql_select_db("$dbname");
?>
的Javascript
$(document).ready(function(){
$('.deletePost').click(function(){
$.ajax({
url:"scripts/post_action.php",
data: {action: "deletePost", postTitle: $(this).siblings("h3.blog").text()},
success: function(response){
$("body").html(response);
alert('DELETED SUCCESSFULLY');
}
});
});
});
答案 0 :(得分:3)
那是因为你在一个范围内调用了$ mysqli,它没有定义为$ mysqli不是全局的。您必须将其作为deletePost函数的参数传递。例如:
function deletePost($title, $mysqli){
$sql = "DELETE FROM blog WHERE Title = '$title'";
mysqli_query($mysqli, $sql);
}
答案 1 :(得分:2)
您不需要mysql_select_db()
和mysql_connect()
,因为您已经宣布了它。