2013-10-27 66 views
0

我想從while循環獲取特定的數據並循環它x次。每個在while循環中的php

我選擇這樣的數據:

$r=mysql_query("SELECT ac6, ac5, ac4, ac3, ac2, ac1, ac0 FROM advertisements WHERE token = '".$_GET['token']."'"); 
while ($adData = mysql_fetch_array($r, MYSQL_NUM)) 
{ 
    $data = $adData; 
    $ac0 = $data['ac0']; 
    $ac1 = $data['ac0']; 

print $ac0; 
print $ac1; 

} 

這是行不通的。沒有打印出來。

我想要做的是獲得ac6 ac0值爲特定的廣告(其中令牌)。 我該怎麼做?

+1

它不起作用,因爲你使用'MYSQL_NUM',但然後試圖檢索字符串鍵''ac0''。 –

+5

[請不要在新代碼中使用'mysql_ *'函數](http://bit.ly/phpmsql)。他們不再被維護[並被正式棄用](https://wiki.php.net/rfc/mysql_deprecation)。看到[紅框](http://j.mp/Te9zIL)?學習[*準備的語句*](http://j.mp/T9hLWi),並使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [這篇文章](http://j.mp/QEx8IB)將幫助你決定哪個。如果你選擇PDO,[這裏是一個很好的教程](http://j.mp/PoWehJ)。 **您也可以[SQL注入](http://stackoverflow.com/q/60174)** –

+0

將while($ adData = mysql_fetch_array($ r,MYSQL_NUM))更改爲'while($ adData = mysql_fetch_assoc($ r)' –

回答

0

將您的數值提取更改爲關聯函數,然後添加一個foreach循環來處理結果。

$r = mysql_query("SELECT ac6, ac5, ac4, ac3, ac2, ac1, ac0 
    FROM advertisements WHERE token = '" . $_GET['token'] . "'"); 
while ($adData = mysql_fetch_assoc($r)) 
{ 
    foreach ($adData as $key => $value) 
    { 
     $nubmer = (int)substr($key, 2); 
     print $value; // or whatever you actually want to do 
    } 
} 

另外我希望你在你的代碼中是validating $_GET['token'] against possible mischief

+1

不,不要驗證'$ _GET','$ _POST'和'$ _COOKIE'參數,但是按照已被接受的答案的建議,使用準備好的陳述問題與你聯繫在一起。 –

0

您可以創建一個陣列從結果查詢

月1日是創建一個數組添加值:

$advert_AC0 = array(); 
$advert_AC1 = array(); 
$advert_AC2 = array(); 
$advert_AC3 = array(); 
$advert_AC4 = array(); 
$advert_AC5 = array(); 
$advert_AC6 = array(); 

現在,內容陣列

$r = mysql_query("SELECT ac6, ac5, ac4, ac3, ac2, ac1, ac0 
    FROM advertisements WHERE token = '" . $_GET['token'] . "'"); 
if(mysql_num_rows($r)){ //check 1st if there is num of rows from the result 
while ($adData = mysql_fetch_assoc($r)) 
{ 
    array_push($advert_AC0, $dData['ac0']); 
    array_push($advert_AC1, $dData['ac1']); 
    array_push($advert_AC2, $dData['ac2']); 
    array_push($advert_AC3, $dData['ac3']); 
    array_push($advert_AC4, $dData['ac4']); 
    array_push($advert_AC5, $dData['ac5']); 
    array_push($advert_AC6, $dData['ac6']); 
} 
}else{ 
echo "NO RESULT."; 
} 

增加請求數組值,1乘1

$count_array = count($advert_AC0); 
$i = $count_array; 
while(1 <= $i){ 
echo "AC0: $advert_AC0[$i]<br>"; 
echo "AC1: $advert_AC1[$i]<br>"; 
echo "AC2: $advert_AC2[$i]<br>"; 
echo "AC3: $advert_AC3[$i]<br>"; 
echo "AC4: $advert_AC4[$i]<br>"; 
echo "AC5: $advert_AC5[$i]<br>"; 
echo "AC6: $advert_AC6[$i]<br>"; 
$i++; 
} 

我不知道我的答案是否解決了您的問題,請不要評論。