tags:

views:

125

answers:

4

I'm a super beginner. I did find related questions here but I think they're too advanced for my skills. :-(

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];
    }
}

Any help plsss??

+3  A: 

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.

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

$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?

Mark Baker
Ok I will change it to global. But the problem is in the query itself. It can't seem to connect to the database. I tried other functions that are working for other queries, still they're not working. Here's the thing, I am building a membership site... All query functions are working if I haven't logged in yet. But after I logged in, say I have index.php as the page I am redirected once logged in, and then run a query from there, the functions can't seem to connect to the database. At first I thought it was because of WP, but then when I tried pure thml files, it's still not working???
Joann
A: 

I apologize, 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...

Joann