在php中运行SQL查询并打印结果时,在null错误时调用成员函数prepare()

在php中运行SQL查询并打印结果时,在null错误时调用成员函数prepare(),php,sql,Php,Sql,我试图在php文件中运行以下SQL代码 Select show_id, show_name From (tv_shows JOIN distributes on D_SHOW_ID=SHOW_ID) Where show_name= ‘Show Name’ (其中“Show Name”是用户传入的一个变量。)SQL在mySQL中运行得很好,但我似乎无法打印出没有错误发生的结果 我试过了 $mysqli = include ('./DBconnect.php'); $sql = 'SELECT

我试图在php文件中运行以下SQL代码

Select show_id, show_name
From (tv_shows JOIN distributes on D_SHOW_ID=SHOW_ID)
Where show_name= ‘Show Name’
(其中“Show Name”是用户传入的一个变量。)SQL在mySQL中运行得很好,但我似乎无法打印出没有错误发生的结果

我试过了

$mysqli = include ('./DBconnect.php');

$sql = 'SELECT show_id, show_name 
FROM (tv_shows JOIN distributes ON D_SHOW_ID=SHOW_ID)
WHERE show_name= ? ';

$stmt = $mysqli-> prepare($sql);
// getting the variable from the user input
$showName = $_GET["name"];

//testing if the variable is passed through
echo $showName."is printed";
$stmt->bind_param('s',$showName);

$stmt-> execute();
$stmt -> bind_result($show_id,$show_name);

if ($stmt->fetch())
{
    echo '<p> Show ID: '.$show_id.' Show Name'. $show_name.'</p><br>';
}

1st:您需要使用连接对象

$stmt = $mysqli-> prepare($sql);
改为

$stmt = $conn-> prepare($sql);
include ('./DBconnect.php');
2nd:您只需要像下面这样包含它

$mysqli = include ('./DBconnect.php');
 include ('./DBconnect.php');
 $conn = get_mysqli_conn();
function get_mysqli_conn(){
    $dbhost = "xxxxx";
    $dbuser = "xxxxx";
    $dbpassword = "xxxxx";
    $dbname = "xxxxxx";

$conn =  new mysqli($dbhost, $dbuser,$dbpassword,$dbname);

if (!$conn){
    die ('Failed to connec to MySQL : (' . $conn->connect_errno.')' . $conn ->connect_error);
}else{
    return $conn;
}
}
改为

$stmt = $conn-> prepare($sql);
include ('./DBconnect.php');
3rd:您的连接创建在函数内部,因此您需要调用函数一次,并获得如下所示的连接对象

$mysqli = include ('./DBconnect.php');
 include ('./DBconnect.php');
 $conn = get_mysqli_conn();
function get_mysqli_conn(){
    $dbhost = "xxxxx";
    $dbuser = "xxxxx";
    $dbpassword = "xxxxx";
    $dbname = "xxxxxx";

$conn =  new mysqli($dbhost, $dbuser,$dbpassword,$dbname);

if (!$conn){
    die ('Failed to connec to MySQL : (' . $conn->connect_errno.')' . $conn ->connect_error);
}else{
    return $conn;
}
}
4th:在该函数中,您需要返回如下所示的连接对象

$mysqli = include ('./DBconnect.php');
 include ('./DBconnect.php');
 $conn = get_mysqli_conn();
function get_mysqli_conn(){
    $dbhost = "xxxxx";
    $dbuser = "xxxxx";
    $dbpassword = "xxxxx";
    $dbname = "xxxxxx";

$conn =  new mysqli($dbhost, $dbuser,$dbpassword,$dbname);

if (!$conn){
    die ('Failed to connec to MySQL : (' . $conn->connect_errno.')' . $conn ->connect_error);
}else{
    return $conn;
}
}

很高兴帮助您:)