Fatal error: Call to a member function prepare() on null

耗尽温柔 提交于 2019-12-08 12:16:13

问题


code:

function insertheadright($name) {
    $str1 = xss($name);
    $sql = "INSERT INTO `nav-menu` (`id`, `Head-categories`, `RightMenu`, `LeftMenu`, `Sub-categories`, `Show-sub`, `Show-head`, `keywords`, `description`) VALUES (NULL, ?, '1', '0', '0', '0', '1', '', '')";
    $result = $connect->prepare($sql);
    $result->bindValue(1, $str1);
    $query = $result->execute();
    if ($query) {
        $num = 1;
        return $num;
    } else {
        $num = 0;
        return $num;
    }
}

code 2:

$object = insertheadright($_POST["nav-name"]);
if (isset($object)) {
    if ($object == 1)
        echo "<div class=ok>منو با موفقیت افزوده شد</div>";
    else
        echo '<div class="error">مشکل در ثبت فهرست</div>';
}

in error:

Notice: Undefined variable: connect in /home/user/domains/site.com/public_html/inc/nav/function-nav.php on line 8 Fatal error: Call to a member function prepare() on null in /home/designpr/domains/shrg.ir/public_html/inc/nav/function-nav.php on line 8


回答1:


Make the connect variable accessible to your function like so:

function insertheadright($name) {
    global $connect;

or, you could pass it as an argument to the function:

function insertheadright($connect, $name) {

Depending on your code, one might be better then the other but as long as you remain consistent you'll be okay.



来源:https://stackoverflow.com/questions/34507352/fatal-error-call-to-a-member-function-prepare-on-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!