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

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站