在php中运行SQL查询然后打印出结果时,调用成员函数prepare()on null error

问题描述:

i am trying to run the following piece of SQL code in a php file

Select show_id, show_name
From (tv_shows JOIN distributes on D_SHOW_ID=SHOW_ID)
Where show_name= ‘Show Name’

(where 'Show Name' is a variable the the user passes in.) The SQL functions perfectly in mySQL but i just can't seem to print the results without errors occurring.

i tried

$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>';
}

and it is giving me a "Call to a member function prepare() on null " error

i have a second php file that is called DBconnect.php which also seem to function correctly.

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{
    echo 'connected';
}
}

1st : you need to use connection object .

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

change to

$stmt = $conn-> prepare($sql);

2nd : you just need to include it like below .

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

change to

include ('./DBconnect.php');

3rd : your connection creation is inside the function so you need to call the function once and get the connection object like below .

 include ('./DBconnect.php');
 $conn = get_mysqli_conn();

4th : In that function you need to return the connection object like below .

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;
}
}