简体   繁体   中英

web Development, PHP display variable from SQL as something else

Ok So i have an PHP page and i have a database. In my database i have a table with a Field one of the fields is called accounttype it is enum('n', 'm', 's') I am trying to display on my PHP page if the user is N it should say Normal User if the user is E Expert user or S Super user...

How do i go about doing this?

Top of PHP Page

<?php
// Query member data from the database and ready it for display
$sql = mysql_query("SELECT * FROM members WHERE id='$id' LIMIT 1");
while($row = mysql_fetch_array($sql)){
    $phone = $row["phone"];
    $country = $row["country"];
    $state = $row["state"];
    $city = $row["city"];
    $accounttype = $row["accounttype"];
    $bio = $row["bio"];
}    
?>

Where i am trying to display on the page This is the code. Right now it just puts a blank space.

<span class="admin">Edward</span>
<span class="date">March 19, 2048</span>
<span class="tag"><?php echo "$accounttype"; ?></span>
<span class="comment"><a href="#">166 comments</a></span>

picture http://i.stack.imgur.com/KXu9A.png

first make a connection, than dont make a while, make a if like this

if($row = mysql_fetch_array($sql)){
    $phone = $row["phone"];
    $country = $row["country"];
    $state = $row["state"];
    $city = $row["city"];
    $accounttype = $row["accounttype"];
    $bio = $row["bio"];
}  

and than

$speaking_type = null;
switch($accounttype) {
    case 'n':
        $speaking_type = 'Normal User';
        break;
    case 'm':
        $speaking_type = 'Expert User';
        break;
    case 's':
        $speaking_type = 'Super User';
        break;
    default:
        $speagink_type = 'none';
        //throw new Exception('unsupported account type '.$accounttype);
}

echo $speaking_type;

I think the problem is your scope. Your variables are defined within the while-loop, and so they are unknown further in the document. Try instantiating them on top (before the while-loop) like this:

$phone = null;
$country = null;
$state = null;
$city = null;
$accounttype = null;
$bio = null;

Than the variables will be known outside the while and the values will be remembered when you print them.

I thought u didn't connect to the database first .use following code to the connect with your credentials.That's why you are seeing a blank space

$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

// some code

mysql_close($con);

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