【问题标题】:Fatal error on a non-object非对象的致命错误
【发布时间】:2011-02-07 13:04:14
【问题描述】:

嘿,所以我创建了一个函数来检查数据库中的唯一条目,但是当我调用该函数时,它似乎不起作用并且给了我一个致命错误任何想法?谢谢:)

 //Check for unique entries
    function checkUnique($table, $field, $compared)
    {
        $query = $mysqli->query('SELECT  '.$mysqli->real_escape_string($field).' FROM '.$mysqli->real_escape_string($table).' WHERE "'.$mysqli->real_escape_string($field).'" = "'.$mysqli->real_escape_string($compared).'"');
        if(!$query){ 
            return TRUE; 
        }   
        else {
            return FALSE;
        }
    }

调用它的页面.....

    //Start session
session_start();

//Check if the session is already set, if so re-direct to the game
if(isset($_SESSION['id'], $_SESSION['logged_in'])){
    Header('Location: ../main/index.php');
};

//Require database connection
require_once('../global/includes/db.php');
require_once('../global/functions/functions.php');

//Check if the form has been submitted
if (isset($_POST['signup'])){
    //Validate input
    if (!empty($_POST['username']) && !empty($_POST['password']) && $_POST['password']==$_POST['password_confirm'] && !empty($_POST['email']) && validateEmail($_POST['email']) == TRUE && checkUnique('users', 'email', $_POST['email']) == TRUE && checkUnique('users', 'username', $_POST['username']) == TRUE)
    {
        //Insert user to the database
        $insert_user = $mysqli->query('INSERT INTO (`username, `password`, `email`, `verification_key`) VALUES ("'.$mysqli->real_escape_string($_POST['username']).'", "'.$mysqli-real_escape_string(md5($_POST['password'])).'", "'.$mysqli->real_escape_string($_POST['email']).'", "'.randomString('alnum', 32). '"') or die($mysqli->error());

        //Get user information
        $getUser = $mysqli->query('SELECT id, username, email, verification_key FROM users WHERE username = "'.$mysqli->real_escape_string($_POST['username']).'"' or die($mysqli->error()));

        //Check if the $getUser returns true
        if ($getUser->num_rows == 1)
        {
            //Fetch associated fields to this user
            $row = $getUser->fetch_assoc();

            //Set mail() variables
            $headers = 'From: no-reply@musicbattles.net'."\r\n".
                      'Reply-To: no-reply@musicbattles.net'."\r\n".
                      'X-Mailer:  PHP/'.phpversion();
            $subject = 'Activate your account (Music Battles.net)';
            //Set verification email message
            $message = 'Dear '.$row['username'].', I would like to welcome you to Music Battles. Although in order to enjoy the gmae you must first activate your account. \n\n Click the following link: http://www.musicbattles.net/home/confirm.php?id='.$row['id'].'key='.$row['verification_key'].'\n Thanks for signing up, enjoy the game! \n Music Battles Team';

            //Attempts to send the email
            if (mail($row['email'], $subject, $message, $headers))
            {
                $msg = '<p class="success">Accound has been created, please go activate it from your email.</p>';
            }
            else {
                $error = '<p class="error">The account was created but your email was not sent.</p>';
            }
        }
            else {
                $error = '<p class="error">Your account was not created.</p>';
            }
        }
            else {
                $error = '<p class="error">One or more fields contain non or invalid data.</p>';
            }
        }

错误....

Fatal error: Call to a member function query() on a non-object in /home/mbattles/public_html/global/functions/functions.php on line 5

【问题讨论】:

  • $mysqli 未在您的函数中设置。函数中的变量在不同的范围内,因此与函数外的变量不同。另外,我在您的主脚本中也没有看到任何 $mysqli 定义。我想它来自db.php,是这样吗?

标签: php function mysqli


【解决方案1】:

$mysqli 没有在你的函数内部定义,因为函数有自己的variable scope。要么将该变量作为参数传递给您的函数:

function checkUnique($mysqli, $table, $field, $compared) {
    // …
}

或者使用global keyword$GLOBAL 变量来访问函数内全局范围的变量:

function checkUnique($table, $field, $compared) {
    global $mysqli;     // registers the global variable $mysqli locally
    $GLOBALS['mysqli']; // OR access the global variable via $GLOBALS['mysqli']
    // …
}

【讨论】:

  • 为什么不直接以$mysqli 而不是$GLOBALS['mysqli'] 访问变量(在函数的第一行声明为global 之后)?
  • @brianreavis:这只是显示这两种变体的示例。
  • 哦,不用担心!我只是真的很好奇……仅此而已。
【解决方案2】:

函数内部的 $mysqli 与函数外部的 $mysqli 不同。您要么必须将 $mysqli 设为全局,要么实例化另一个数据库连接。

【讨论】:

    【解决方案3】:

    对我来说,我有同样的问题,但与 mysql 无关。我从现有的 PHP 中提取了以下方法:

    <?php function checkMainInner()
    {
        ?>
    <?php if ($this['modules']->count('innertop')) : ?>
    <section id = "innertop" class = "row grid-block"><?php echo $this['modules']->render('innertop', array('layout' => $this['config']->get('innertop'))); ?></section>
    <?php endif; ?>
    
    <?php if ($this['modules']->count('breadcrumbs')) : ?>
    <section id = "breadcrumbs"><?php echo $this['modules']->render('breadcrumbs'); ?></section>
    <?php endif; ?>
    
    <?php if ($this['config']->get('system_output')) : ?>
    <section class = "row grid-block"><?php echo $this['template']->render('content'); ?></section>
    <?php endif; ?>
    
    <?php if ($this['modules']->count('innerbottom')) : ?>
    <section id = "innerbottom" class = "row grid-block"><?php echo $this['modules']->render('innerbottom', array('layout' => $this['config']->get('innerbottom'))); ?></section>
    <?php endif;
    }
    
    ?>
    

    我做了如下的函数调用:

    <!--if it's just sidebar b-->
            <?php if ($this['modules']->count('sidebar-b') && ($this['modules']->count('sidebar-a') == 0)): ?>
            <div id = "maininner" class = "grid-box ninecol">
                <?php checkMainInner() ?>
            </div>
            <aside id = "sidebar-b" class = "grid-box threecol last">
                <?php echo $this['modules']->render('sidebar-b', array('layout' => 'stack')); ?>
            </aside>
            <?php endif; ?>
    

    当然,这失败了,因为$this 超出了函数的范围。所以更改函数参数以将$self 作为参数修复了这个问题:

    <?php function checkMainInner($self)
    {
        ?>
    <?php if ($self['modules']->count('innertop')) : ?>
    <section id = "innertop" class = "row grid-block"><?php echo $self['modules']->render('innertop', array('layout' => $self['config']->get('innertop'))); ?></section>
    <?php endif; ?>
    
    <?php if ($self['modules']->count('breadcrumbs')) : ?>
    <section id = "breadcrumbs"><?php echo $self['modules']->render('breadcrumbs'); ?></section>
    <?php endif; ?>
    
    <?php if ($self['config']->get('system_output')) : ?>
    <section class = "row grid-block"><?php echo $self['template']->render('content'); ?></section>
    <?php endif; ?>
    
    <?php if ($self['modules']->count('innerbottom')) : ?>
    <section id = "innerbottom" class = "row grid-block"><?php echo $self['modules']->render('innerbottom', array('layout' => $self['config']->get('innerbottom'))); ?></section>
    <?php endif;
    }
    
    ?>
    

    我接着新方法调用:

    <!--if it's just sidebar b-->
            <?php if ($this['modules']->count('sidebar-b') && ($this['modules']->count('sidebar-a') == 0)): ?>
            <div id = "maininner" class = "grid-box ninecol">
                <?php checkMainInner($this) ?>
            </div>
            <aside id = "sidebar-b" class = "grid-box threecol last">
                <?php echo $this['modules']->render('sidebar-b', array('layout' => 'stack')); ?>
            </aside>
            <?php endif; ?>
    

    这样做解决了我的问题。希望这对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-05-29
      • 2016-12-07
      • 1970-01-01
      • 2015-09-14
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多