2011-12-10 78 views
2

我看到了幾個與我的問題有關的問題,但我對編程很陌生,無法弄清答案的一半。下面是我得到數據從我的表中獲得的唯一工作,然而,這樣做比我需要的方式更多,但仍然給我一個不希望的結果。SQL查詢將行值保存到php變量中

我只想從我的表的第一行中取出字符串並保存到名爲$news1的php變量中。

$connection = mysql_connect("localhost", "USERNAME", "PW"); 

if(!$connection) 
{ 
    die("<p>no connection to database</p>"); 
} 

if(!mysql_select_db("akron11_db", $connection)) 
{ 
    die("<p>Kunne ikke finde databasen</p>"); 
} 

$result = mysql_query("SELECT news1 FROM TurenTilDannmark", $connection); 

if(!$result) 
{ 
    die("<p>Efterspørgslen slog fejl " . mysql_error() . "</p>"); 
} 

$rows = mysql_num_rows($result); 

for ($item = 0; $item < $rows; $item++) 
{ 
    echo "<li>" . mysql_result($result, $item) . "</li>"; 
} 

echo "</p>"; 
+1

「不良結果」。你能更具體一點嗎?你得到的結果是什麼,你希望得到什麼? –

回答

1

您可以使用限制來獲取只有一個結果:

$result = mysql_query('SELECT news1 FROM TurenTilDannmark LIMIT 1', $connection); 

然後你就可以使用mysql_fetch_assoc

$row = mysql_fetch_assoc($result); 
echo $row['news1']; // ta-da! 

mysql_result

$news1 = mysql_result($result, 0); // 0 is the index of the field, not the row 
echo $news1; 
+2

感謝middus,那太簡單了!你們好棒。 – Snigern

+0

@ user1091537我很高興我可以幫助:)。 – middus

1

嘗試:

$result = mysql_query("SELECT FIRST(news1) FROM TurenTilDannmark", $connection); 

FIRST()相當於LIMIT 1

這應該給你的時候,你做下一個只有一行:

$rows = mysql_num_rows($result); 
+0

沒有錯誤,但迴應結果給出了不輸出。 $ news1 = mysql_query(「SELECT TOP1 news1 FROM TurenTilDannmark」,$ connection); echo $ news1; – Snigern

+1

@ user1091537:它不是'$ result',你需要回顯。你需要做'$ row = mysql_fetch_assoc($ result);'然後'echo $ row ['news1'];'就像* middus *在他的答案中寫的。 – Otiel

+0

對不起,我的網站移動速度太快xD它現在的作品!謝謝大家。 – Snigern