开发者

Call to a member function fetch_assoc() on a non-object

Here's my function:

function get_fname($un){

$registerquery = $this->conn->query("SELECT f_name FROM tz_members WHERE 
                     usr='".$un."'");

while ($row = $registerquery->fetch_assoc()) { 
    return $fname = $row[$un];
开发者_运维百科    }
}

Edit:

I chose to answer my own question because it has an editor.

@Mark Baker:

<?php
    require_once 'Mysql.php'; 
    $mysql = new Mysql(); 

?>
<html>
  <head>
  </head>
  <body>
    <h4><?php echo $mysql->get_fname("joann"); ?></h4>
  </body>
</html>

That's how I am doing it...


It seems that your query failed. Because in that case query returns false. So try this:

$registerquery = $this->conn->query("SELECT f_name FROM tz_members WHERE 
                 usr='".$un."'");
if ($registerquery) {
    while ($row = $registerquery->fetch_assoc()) { 
        return $fname = $row[$un];
    }
}

The failure may be caused by a syntax error in your query when $un contains characters that break the string declaration (like ' or \). You should use MySQLi::real_escape_string to escape that characters to prevent that.

Additionally, a function can only return a value once. So the while will be aborted after the first row.


$fname = $row[$un]; is assigning the value in $row[$un] to the variable $fname, then returning the result. It's pointless doing that assignment to $fname because $fname is simply a local variable within the function.... if it's defined as global, then it's not good programming practise.

If echo $mysql->get_fname("joann") is the line where you're calling the get_fname() function, then how are you setting $mysql?

And what do you think will happen if the database query doesn't find any valid result for the query?


while ($row = fetch_assoc($registerquery)) { 
    return $fname = $row[$un];
    }
}


Is it possible you forgot to give a table name in the connection?

$conn = new mysqli('localhost', 'root', 'password', 'ANY VALUE HERE??');

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜