phpmysqlfunctionprepare

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


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


Solution

  • 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.