mysql_query中給出了兩行,我希望每行放入一個變量$ date1和$ date2。我的示例代碼如下。把sql放到一個變量中
while($row=mysql_fetch_array($sql)) {
$date1 = $row['TheDate'];
$date2 = $row['TheDate'];
}
echo $date1;
echo $date2;
mysql_query中給出了兩行,我希望每行放入一個變量$ date1和$ date2。我的示例代碼如下。把sql放到一個變量中
while($row=mysql_fetch_array($sql)) {
$date1 = $row['TheDate'];
$date2 = $row['TheDate'];
}
echo $date1;
echo $date2;
while($row=mysql_fetch_array($sql)){
$results[] = $row['TheDate1']
}
echo $results[0];
echo $results[1];
雖然我不知道爲什麼你想擁有$date1
和$date2
而不是$date
兩個元素的數組,這裏有一個辦法做到這一點:
$i = 1;
while($row=mysql_fetch_assoc($sql)){
${"date".$i} = $row['TheDate'];
$i++;
}
echo $date1;
echo $date2;
一種合適的方式將它們分配到一個數組和訪問數據是這樣的:
while($row=mysql_fetch_assoc($sql)){
$date[] = $row['TheDate'];
}
echo $date[0];
echo $date[1];
要兩個日期進行比較,可以做如下:
$difference = $date2- $date1;
或陣列的方法:
$difference = $date[1] - $date[0];
我覺得這是你所需要的。
$dates = array();
$allData = array();
while($row=mysql_fetch_array($sql)){ // switch to mysqli or PDO
$dates[] = $row['TheDate']; // $dates will have all the dates
$allData[] = $row; // $allData will have all the data in the query
}
print_r($dates);
PS:
請考慮您的代碼轉換到庫MySQLi或PDO - 因爲PHP的MySQL 5.5已經過時,而且不再被維護。
你想要做的是創建一個數組:
$dates = array();
while($row=mysql_fetch_array($sql)) {
$dates[] = $row['TheDate'];
}
var_dump($dates);
// Now if you *really* insist in having it in separate variables you could do:
list($date1, $date2) = $dates;
另外:
Please, don't use mysql_*
functions in new code。他們不再維護and are officially deprecated。請參閱red box?請改爲了解prepared statements,並使用PDO或MySQLi - this article將幫助您決定哪個。如果您選擇PDO,here is a good tutorial。
每個日期是在自己的行,所以'$日期[] = $行[ 'TheDate']'就足夠了。 –
@Jack啊我明白了。 OP代碼困惑我:) – PeeHaa
在外鍵有兩個日期我想查看以前的日期和最新的日期。 –
有什麼問題?顯示你當前的輸出和你想要的輸出。這裏至少有一點是,你把兩個變量放在相同的信息中,並覆蓋所有結果 – Nanne
我不能正確理解這個問題,但是不會使用一個數組也不錯?我認爲OP希望將第一個日期放在$ date1中,第二個日期放入$ date2中。所以我認爲使用一個數組和$ dates [0]和[1] ......會更好一些......但我不確定,如果這就是OP所需要的。 – ppeterka
使用數組來存儲結果,請參閱http://stackoverflow.com/questions/6741425/populate-php-array-from-while-loop – Jochen