2012-07-04 46 views
-2

我想在我的簡單CMS中自動添加頁面,並且不是PHP的大用戶,不能解決我如何從我的MySQL數據庫獲取列並創建一組從它的字符串。我會解釋。從MySQL條目創建字符串

$home=mysql_query("SELECT * FROM data WHERE callsign='home'"); //** 

$num=mysql_num_rows($home); 
$i=0; 
while ($i < $num) { 
$f1=mysql_result($home,$i,"code"); //** 
$i++; 
} 
switch($_GET['page']) { 
case '#home' : $page = $f1; break; //** 
} 
echo $page; 

如何在MySQL數據庫的每列中的每個條目的標有星號的行上創建字符串和變量?

+0

我覺得應該是** $ F1 = mysql_result($ HOME,$ I); ** .. – mithunsatheesh

+0

你的問題不是很清楚。假設這段代碼有效,它似乎會返回一個字符串。 – Cfreak

+0

您錯誤地輸入了mysql_num_rows – mithunsatheesh

回答

1

我不完全確定你的意思是來自數據庫的「變量」和「字符串」,但這裏是我如何解決這個問題。請注意,我使用的是PDO,因爲mysql_*函數已被棄用。

// this is how you connect with PDO 
$dbh = new PDO('mysql:dbname=yourdbname;host=yourhost','youruser','yourpassword'); 

// you can name the column from the database itself. This is much faster 
// also the ? is a placeholder. We'll pass the value on execute() 
// this prevents SQL Injection attacks. 
$sth = $dbh->prepare("SELECT code FROM data WHERE callsign=?"); 

// use try { } catch { } to detect errors 
try { 
    $sth->execute(array($_GET['page'])); 
} 
catch(PDOException $e) { 
    die($e->getMessage()); 
} 

// now you can fetch(). This returns the first row as an array. list() names the only variable in it 
list($code) = $sth->fetch(PDO::FETCH_NUM); 

$sth->closeCursor(); // close the cursor or you'll have problems reusing the db handle 

print $code; // output is a string