为什么我的数据库变量在这个php脚本中没有定义I';我是从Ajax打来的


Why is my database variable undefined in this php script I'm calling from Ajax?

当我点击.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');
            }
    });
});
});

这是因为您在一个未定义为$mysqli不是全局的范围内调用$mysqli。您必须将其作为deletePost函数的参数传递。例如:

function deletePost($title, $mysqli){
    $sql = "DELETE FROM blog WHERE Title = '$title'";
    mysqli_query($mysqli, $sql);
}

您不需要mysql_select_db()mysql_connect(),因为您已经声明了它。