duanbu1421 2017-07-20 08:33
浏览 104
已采纳

在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';
}
}
  • 写回答

1条回答 默认 最新

  • doulangxun7769 2017-07-20 08:35
    关注

    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;
    }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵