簡體   English   中英

Web開發,PHP將來自SQL的變量顯示為其他內容

[英]web Development, PHP display variable from SQL as something else

好的,所以我有一個PHP頁面,並且我有一個數據庫。 在我的數據庫中,我有一個帶有字段的表,其中一個字段稱為accounttype,它是enum('n','m','s')。如果用戶為N ,我想在我的PHP頁面上顯示,應該說普通用戶,如果用戶是E專家用戶或S超級用戶...

我該怎么做?

PHP頁面頂部

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

我試圖在頁面上顯示的位置這是代碼。 現在,它只是留出空白。

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

圖片http://i.stack.imgur.com/KXu9A.png

首先建立連接,而不是建立一段時間,如果這樣

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

然后

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

我認為問題在於您的范圍。 您的變量是在while循環中定義的,因此在文檔中進一步未知。 嘗試像這樣在頂部實例化它們(在while循環之前):

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

在一段時間內,這些變量將不為人知,並且在打印它們時將記住這些值。

我以為您沒有先連接到數據庫。請使用以下代碼與您的憑據進行連接。這就是為什么您看到空白的原因

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

// some code

mysql_close($con);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM