简体   繁体   中英

Basic SQL output question

this is probably the most basic question in the world, but I cannot figure it out.

I would like to simply display a users First name, and Email adress from my table. I have tried using a loop, but that was entirely worthless considering I am only selecting one row. I know this is a menial question but I could not find/remember how to do it. Thank you!

$db = mysql_connect("server","un", "pw"); 
    mysql_select_db("db", $db); 

$sql = "SELECT FirstName, EmailAddress" 
    . " FROM Student" 
    . " WHERE StudentID  = '$student' ";
$result = mysql_query($sql, $db); 
$num = mysql_num_rows($result);
 $userinfo = mysql_result($result,$userinfo);

$student is a session variable. I want to echo the First name and email address somewhere in the page, but I cannot believe how much pain thats causing me. Thanks again!

mysql_fetch_assoc() turns a result row into an array.

$result = mysql_query($sql, $db);
$user = mysql_fetch_assoc($result);
echo $user['FirstName'];
echo $user['EmailAddress'];

It looks like you spelled address wrong, so it probably doesn't match your real column name. More importantly, your code appears vulnerable to SQL injection. You really need to use prepared statements (see How to create a secure mysql prepared statement in php? ) or escaping.

To fetch a row, you must use one of the mysql_fetch functions (eg mysql_ fetch_ array, mysql_ fetch_ object, etc.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM