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 基于RTKLIB框架写的精密单点定位-AR
  • ¥15 PFENet的预训练权重
  • ¥15 程序哪有错误怎么改?
  • ¥15 交换机和交换机之间的链路带宽以及主机带宽的理解
  • ¥15 ai创想家对战模式代码
  • ¥15 集合A由3个2行4列二维数组构成,从集合A中任意取一个二维数组元素、如果该二维数组元素的对应列位置的上、下两数都是奇数,而且仅有2个列是奇数/奇数,则该数组有意义,并放入集合B中打印输出。
  • ¥15 电信IPV6 无法外网访问吗
  • ¥15 有偿求效果比较好的遥感影像匹配的c++代码
  • ¥15 博主,你好,我下载了你的智能网联汽车辅助驾驶安全信息检测系统,现在不会运行,可以教我吗,
  • ¥15 怎么在excle输入下列公式