At the beginning and at ending of the contents I have to append the brackets my csv file looks like this
date1,success,failure,count
1427653800,95,65,160
1427653800,30,10,40
1427740200,10,8,18
1427740200,30,38,68
1427826600,38,20,58
1427826600,60,10,70
1427653800,15,15,30
1427653800,10,10,20
After adding brackets the contents should look like this: [1427653800,95,65,160] My php code is below:
<?php
$list = array ('date1', 'success', 'failure','count');
$sql = "SELECT (SUBSTRING(UNIX_TIMESTAMP(date1),1,10)),success,failure,count from h_statistics;";
$users_profile_user_id = mysqli_query($conn, $sql);
$fp = fopen("data.csv", "w");
fputcsv($fp, $list);
while($row = mysqli_fetch_array($users_profile_user_id, MYSQLI_ASSOC))
{
fputcsv($fp, $row);
}
fclose($fp);
?>
this is my conn.php file ,please suggest me on this
it is better to use this query
$sql = "SELECT CONCAT('[','',(SUBSTRING(UNIX_TIMESTAMP(date1),1,10))),success,failure,CONCAT(count,'',']') from h_statistics";
it give you result like [1427653800,95,65,160] so no need to do any code in you while loop
Try to append and prepend the brackets :
$row[0] = '['.$row[0];
$row[3] .= ']';
fputcsv($fp, $row);
try with my function which is adding your text to the first and last element of the associative array:
<?php
function array_brackets($array,$prefix,$suffix){
//add prefix to the first element
end($array);
$key = key($array);
$array[$key] = $prefix . $array[$key];
//add sufix to the last element
reset($array);
$key = key($array);
$array[$key] = $array[$key] . $suffix;
return $array;
}
$list = array ('date1', 'success', 'failure','count');
$sql = "SELECT (SUBSTRING(UNIX_TIMESTAMP(date1),1,10)),success,failure,count from h_statistics;";
$users_profile_user_id = mysqli_query($conn, $sql);
$fp = fopen("data.csv", "w");
fputcsv($fp, $list);
while($row = mysqli_fetch_array($users_profile_user_id, MYSQLI_ASSOC))
{
fputcsv($fp, array_brackets($row,"[","]"));
}
fclose($fp);
?>
Please run this code and give me the output:
<?php
$list = array ('date1', 'success', 'failure','count');
$sql = "SELECT (SUBSTRING(UNIX_TIMESTAMP(date1),1,10)),success,failure,count from h_statistics;";
$users_profile_user_id = mysqli_query($conn, $sql);
//$fp = fopen("data.csv", "w");
//fputcsv($fp, $list);
while($row = mysqli_fetch_array($users_profile_user_id, MYSQLI_ASSOC))
{
//fputcsv($fp, array_brackets($row,"[","]"));
print_r($row);
exit;
}
//fclose($fp);
?>