2016-11-18 77 views
-2

我有數據庫連接。我想創建一個數組,但是我認爲有些問題是問題。這裏是我的陣列碼:從數據庫MySQL製作數組

$var = "SELECT SUBSTRING(KayitTarihi,1,4) AS year,SUBSTRING(KayitTarihi,6,2) AS month,SUBSTRING(KayitTarihi,9,2) AS day,SUBSTRING(KayitTarihi,12,2) AS saat,SUBSTRING(KayitTarihi,15,2) AS dakika,Guc FROM Urun WHERE Date(KayitTarihi)=\"".$link_m."\""; 

$result = $mysqli->query($var); 

$data = array(); 
foreach ($result as $row) {$data[] = $row;} 

print_r($data); 

$no=1;$total_deger=count($data); 
echo $total_deger; 

for($i=0;$i<$total_deger);$i++){ 
    $xxx[i]="[Date.UTC(".$data[i]['year'].",".$data[i]['month'].",".$data[i]['day'].",".$data[i]['saat'].",".$data[i]['dakika'].",00),".$data[i]['Guc']."]";if($no < $total_deger){echo ",";} 
    echo $xxx[i]; 
} 

當我運行這段代碼,什麼都不會發生在頁。當我寫信給我例如0。我可以看到我的數組值。我在哪裏錯誤?

+2

語法錯誤: - for($ i = 0; $ i <$ total_deger); $ i ++){'檢查額外支架?這是TYPO嗎? –

+0

是的,現在沒事了..謝謝。但是現在我的$ no = 1,並且我有if語句$ no <$ total_deger。 $ total_deger是23.但它看起來像$ no <$ total_deger,我的if語句是真的。哪裏不對? – catcher

+2

也'回聲$ XXX [I]'應該是'回聲$ XXX [$ i];'**看看你的PHP錯誤日誌預期當事情不工作** – RiggsFolly

回答

3

代碼校正和建議(兩者都註釋): -

<?php 
error_reporting(E_ALL); // check all errors 
ini_set('display_errors',1);// display those errors 
$var = "SELECT SUBSTRING(KayitTarihi,1,4) AS year,SUBSTRING(KayitTarihi,6,2) AS month,SUBSTRING(KayitTarihi,9,2) AS day,SUBSTRING(KayitTarihi,12,2) AS saat,SUBSTRING(KayitTarihi,15,2) AS dakika,Guc FROM Urun WHERE Date(KayitTarihi)=\"".$link_m."\""; 

$result = $mysqli->query($var); 

$data = array(); 

if ($result->num_rows > 0) { // check you got results or not 
    while($row = $result->fetch_assoc()) { 
     $data[] = $row; // assign them 
    } 
} 

//foreach ($result as $row) {$data[] = $row;} // not needed 

print_r($data); 

$no=1; 

$total_deger= count($data); 

echo $total_deger; 

for($i=0;$i<$total_deger;$i++){ // remove) 

$xxx[$i]="[Date.UTC(".$data[$i]['year'].",".$data[$i]['month'].",".$data[$i]['day'].",".$data[$i]['saat'].",".$data[$i]['dakika'].",00),".$data[$i]['Guc']."]"; // use $i instead of i 
if($no < $total_deger) 
{ 
    echo ","; 
} 
echo $xxx[$i]; 

} 

注: - 始終添加一些錯誤報告代碼。所以,所有的錯誤將填充,你可以糾正那些

也比較好是使用foreach()代替for循環(因爲它會採取指數本身的照顧): -

//use foreach 
foreach ($data as $dat){ 
    echo "[Date.UTC(".$data['year'].",".$data['month'].",".$data['day'].",".$data['saat'].",".$data['dakika'].",00),".$data['Guc']."]"; 
} 
+0

我已經添加了一個'foreach()'建議,這對你更有好處。 –

+0

當我再次使用foreach只是看到,,,,,不是我的價值。 – catcher

+0

我total_deger = 9,但我的輸出是 [Date.UTC(,,,,, 00),],[Date.UTC(,,,,, 00),],[Date.UTC(,,,,, 00),],[Date.UTC(,,,,, 00),],[Date.UTC(,,,,, 00),],[Date.UTC(,,,,, 00),] [Date.UTC(,,,,, 00),],[Date.UTC(,,,,, 00),],[Date.UTC(,,,,, 00),] – catcher

1

首先要檢查你的SQL查詢返回的行。那麼我認爲你需要修改你的foreachwhile如下。還要檢查循環前是否返回行。

if ($result->num_rows > 0) { 
    while($row = $result->fetch_assoc()) { 
     $data[] = $row; 
    } 
} 

按照例如這裏給出:http://www.w3schools.com/php/php_mysql_select.asp