从数据库MySQL制作数组

时间:2016-11-18 09:11:11

标签: php mysql arrays

我有数据库连接。我想制作一个数组,但我觉得有些问题。这是我的数组代码:

$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];
}

当我运行此代码时,页面中没有任何反应。当我为i写例如0时。我可以看到我的数组值。我在哪里弄错了?

2 个答案:

答案 0 :(得分: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']."]";
}

答案 1 :(得分:1)

首先,您要检查SQL查询是否返回行。然后我认为您需要将foreach修改为while,如下所示。还要在循环之前检查是否返回了行。

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

根据此处给出的示例:http://www.w3schools.com/php/php_mysql_select.asp