Search code examples
phpsqlfwrite

Using fwrite to display sql query


I'm trying to pull a username from a sql database to place on my chat. My database is structured as seen below. no matter what I do, It doesn't work which I don't seem to understand because I'm able to echo people's usernames by doing .$user_info['username']. However when I place it within a fwrite function nothing shows up. What am I missing, why isn't the username showing up within the fwrite function.

db http://goawaymom.com/db.jpg

<?
mysql_connect("localhost", "root", "password") or die(mysql_error());
mysql_select_db("root_members") or die(mysql_error());

session_start();
if(isset($_SESSION['name'])){
$text = $_POST['text']; 
$fp = fopen("log.html", 'a');
fwrite($fp, "<div class='msgln'> ".$user_info['username'].">".stripslashes(htmlspecialchars($text))."</div>");
fclose($fp);
}
?>

Solution

  • You need to define $user_info:

    <?
    mysql_connect("localhost", "root", "password") or die(mysql_error());
    mysql_select_db("root_members") or die(mysql_error());
    
    session_start();
    if(isset($_SESSION['name'])){
    
    // select from database
    $result = mysql_query('SELECT * FROM users WHERE username="' . $_SESSION['name'] . '"'); 
    // retrieve row
    $user_info = mysql_fetch_assoc($result); // fixed this from mysql_fetch_row to mysql_fetch_assoc
    
    $text = $_POST['text']; 
    $fp = fopen("log.html", 'a');
    fwrite($fp, "<div class='msgln'> ".$user_info['username']." &gt;".stripslashes(htmlspecialchars($text))."</div>");
    fclose($fp);
    }
    ?>