2011-03-17 167 views
0

好吧,我現在遇到了一個問題,我想顯示數據庫中的數據,並通過函數顯示它現在我該怎麼做?在php函數中顯示mysql數據

像我從數據庫中取出一行,它的名字是$ row_field ['data'];這是正確的,現在我已經分配了一個變量,像這樣$ data = $ row_field ['data'];現在,如果我在一個函數調用它,它顯示未定義的變量i分配其全球的功能這樣

function fun(){ 
    global $data; 
    echo $data; 
} 

即使但是如果我給你它像1或2或任何一個值,它就會沒有任何錯誤,爲什麼顯示是這樣嗎??

+1

請出示一個完整的代碼示例 – 2011-03-17 15:20:01

+0

UFF ......我現在不從哪裏開始。 – 2011-03-17 15:21:55

回答

0

如果在仍處於全局範圍內時爲它指定一個值,如1或2,那麼我只能假設你的數據庫沒有返回你認爲它的結果。如果您在函數之外回顯數據庫值,是否顯示數據庫值?

+0

再次抱歉邁克爾 – 2011-03-17 15:33:18

0

全球是邪惡的。我不知道你在做什麼,但爲什麼不在功能本身做查詢?

+0

該死的這真的很尷尬請原諒浪費你的時間它的工作我錯過了全球的「l」,這就是爲什麼它給錯誤謝謝你TJ你的時間.. – 2011-03-17 15:32:16

0

如果你有一個名爲列和data你的PHP電話是像

$result = mysql_query("SELECT data FROM mytable"); 

while ($row_field = mysql_fetch_assoc($result, MYSQL_NUM)) { 
    ... 
} 

然後,你可以用print $row_field['data']取代...

否則請在您查詢數據庫並檢索結果的地方提供代碼片段。

+0

再次抱歉nyom我的壞..: p – 2011-03-17 15:33:36

0

學習php時試着從簡單的事情開始。例如,爲了從數據庫獲取一些數據,請從php網站下載examples

<?php 

$conn = mysql_connect("localhost", "mysql_user", "mysql_password"); 

if (!$conn) { 
    echo "Unable to connect to DB: " . mysql_error(); 
    exit; 
} 

if (!mysql_select_db("mydbname")) { 
    echo "Unable to select mydbname: " . mysql_error(); 
    exit; 
} 

$sql = "SELECT id as userid, fullname, userstatus 
    FROM sometable 
    WHERE userstatus = 1"; 

$result = mysql_query($sql); 

if (!$result) { 
    echo "Could not successfully run query ($sql) from DB: " . mysql_error(); 
    exit; 
} 

if (mysql_num_rows($result) == 0) { 
    echo "No rows found, nothing to print so am exiting"; 
    exit; 
} 

// While a row of data exists, put that row in $row as an associative array 
// Note: If you're expecting just one row, no need to use a loop 
// Note: If you put extract($row); inside the following loop, you'll 
//  then create $userid, $fullname, and $userstatus 
while ($row = mysql_fetch_assoc($result)) { 
    echo $row["userid"]; 
    echo $row["fullname"]; 
    echo $row["userstatus"]; 
} 

mysql_free_result($result); 

如果一切順利,稍微進一步改變一下while循環。

$myArray = array(); 

while ($row = mysql_fetch_assoc($result)) { 
    $myArray[] = $row; 
} 

mysql_free_result($result); 

// now you can start playing with your data 
echo $myArray[0]; 

小步驟...