This is my PHP code
<?php
require_once 'd:\xampp\htdocs\bpr\pdo_db.php';
$sql = "Select ID,FULL_NAMe,AGE from TRIAL";
$csv = get_csv_string($dbh, $sql);
echo "<script> var_csv='" . $csv . "' </script>";
function get_csv_string($dbh, $sql)
{
try
{
$result = $dbh->query($sql);
//return only the first row (we only need field names)
$row = $result->fetch(PDO::FETCH_ASSOC);
if ($row == null) {
return "No Data";
}
$f = fopen('php://memory', 'r+');
foreach ($row as $field => $value) {
if (fputcsv($f, $field) === false) {
return false;
}
}
//second query gets the data
$data = $dbh->query($sql);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach ($data as $row) {
if (fputcsv($f, $row) === false) {
return false;
}
} // end record loop
rewind($f);
$csv = stream_get_contents($f);
return rtrim($csv);
} catch (PDOExepction $e) {
return $e->getMessage();
}
return $csv;
}
I am getting following error!
Instead of fputcsv(), I made my own code. But issue if found when I save the CSV to a javascript variable. Is there any other way to convert the data to CSV and pass it on to javascript?
I will convert this csv to JSON at Client side using javascript
You're trying to output a header row to CSV with the field names.
This code fails because you're looping through the $row array and attempting to write one field header at a time.
foreach ($row as $field => $value) {
if (fputcsv($f, $field) === false) {
return false;
}
}
What you want is an array with the field names in it. You can use array_keys() for that, so your code becomes
if (fputcsv($f, array_keys($row)) === false) return false;
No loop required.
I have an empty test.php file,in that file, I've inserted data below shown.
This code is form controller. This trace data coming from UI using ajax.
Here my $trace array data like this :
array(
[0] => $test1 = "1,2,3,4,5,6,7";
[1] => $test2 = "1,2,3,4,7";
[2] => $test3 = "1,4,6,7,9,0";
)
This is coming from UI
$trace = $this->input->post('trace');
$viewsDir = 'C:/xampp/htdocs/project/application/views/html_v3/';
$fp = fopen($this->viewsDir.'test.php', 'w');
fwrite($fp, "<?php \n\n");
$i = 0;
if($trace){
foreach ($trace as $value) {
fwrite($fp, $trace[$i]."\n");
$i++;
}
}
fwrite($fp, "\n?>");
fclose($fp);
After inserted my data into test.php file then the file look like this:
<?php
$test1 = "1,2,3,4,5";
$test2 = "5,2,0,6,5";
$test3 = "4,8,9,7,1";
?>
Here, if once again I want to insert data into test.php file, my $trace array data like this:
aray(
[0] => $test1 = "9,9,9,9,9";
[1] => $test2 = "1,1,1,1,1";
[2] => $test4 = "1,2,6,7,8";
)
Here my query is how can I replace this ($trace)array variables if matched with test.php. If not matched it should be added to the test.php file.
Here my expected output is:
<?
$test1 = "9,9,9,9,9";
$test2 = "1,1,1,1,1";
$test3 = "4,8,9,7,1";
$test4 = "1,2,6,7,8";
?>
I tried like this,but i don't know how to compare my array($trace) and content of test.php
$file = $this->viewsDir.'test.php';
$contents = file_get_contents($file);
echo $contents; //i will get content of test.php based on this i have to replace or add
Please help me,
Thanks.
I'm not even sure I should help you with that. There is possibly something very wrong with your design if you're passing php code via POST and save it to a source file.
Anyways...
I'd declare helper function that 'parses' entry string line as key $trace1 and value "1,2,3,4,5" and adds it to array $arr
function addToTrace(&$arr, $entry) {
$entry = trim($entry);
if(substr($entry, 0, 1) == "$") {
$elements = explode("=", $entry);
if(count($elements) !== 2) {
return false;
}
$elements = array_map('trim', $elements);
$arr[$elements[0]] = $elements[1];
return true;
}
return false;
}
After that it's only a matter of reading the file first, adding all entries to new array $currTrace
$currTrace = [];
$fp = fopen($this->viewsDir . 'test.php', 'r');
if($fp) {
while (!feof($fp)) {
$line = fgets($fp);
addToTrace($currTrace, $line);
}
fclose($fp);
}
than adding new trace from post (ovewriting matching keys):
if($trace){
foreach ($trace as $value) {
addToTrace($currTrace, $value);
}
}
and saving $currTrace to file:
$fp = fopen($this->viewsDir . 'test.php', 'w');
fwrite($fp, "<?php \n\n");
foreach($currTrace as $key => $value) {
fwrite($fp, $key . " = " . $value . "\n");
}
fclose($fp);
I have an application where I can generate JSON, which in turn I use as input to GoogleCharts API to draw different visualizations. The pages of this web application are in HTML.
Suppose I have a JSON which has a list of departments of a hospital, like: [{"v":"General Medicine"},{"v":"Laboratory"}]
How do I use Javascript to convert this to an array which in turn can be used as option values of a drop down list?
I am using the following code to generate JSON:
<?php
$serverName = "forestroot"; //serverName\instanceName
$connectionInfo = array( "Database"=>"****", "UID"=>"****", "PWD"=>"****");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
//echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT distinct([DEPT_NAME]) as dept FROM [Pristine11Dec15].[dbo]. [PACKAGE_REVN]";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$result = sqlsrv_query( $conn, $sql, $params, $options);
if (sqlsrv_num_rows( $result ) > 0) {
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
$array[] = array('v'=>$row["dept"]);
}
}
echo json_encode($array);
sqlsrv_close( $conn);
?>
The output is [{"v":"General Medicine"},{"v":"Laboratory"}]
When I use JSON.parse in my code I am getting the options as [object Object] in the drop down list. Where am I going wrong?
var json = '[{"v":"General Medicine"},{"v":"Laboratory"}]';
Parse the data and use map to return an array of v values:
var list = JSON.parse(json).map(function (el) {
return el.v;
}); // [ "General Medicine", "Laboratory" ]
DEMO
You could extend this however to build up the HTML for the select:
var templ = '<option value="#{el}">#{el}</option>';
var options = JSON.parse(json).map(function (el) {
return templ.replace('#{el}', el.v, 'g');
}).join('');
var select = '<select>' + options + '</select>';
document.getElementById('menu').insertAdjacentHTML('beforeend', select);
DEMO
I'm a beginner in using PHP and Javascript, and I don't have any idea on how to store the data that I've gathered from MySQL which I placed in a multidimensional array in PHP to a 2D array in Javascript. Here's my working code in PHP:
<?php
function connecToDatabase(){
$host = "localhost";
$username = "root";
$password = "p#ssword";
$database = "flood_reports";
mysql_connect("$host", "$username", "$password") or die(mysql_error());
mysql_select_db("$database") or die(mysql_error());
}
function retrieveData(){
connecToDatabase();
$data = mysql_query('SELECT * FROM entries') or die(mysql_error());
$entries = array();
$index = 0;
while($info = mysql_fetch_array( $data ))
{
$entries[$index] = array('entry_id' => $info['entry_id'],
'location' => $info['location'],
'image_dir' => $info['image_dir'],
'longitude' => $info['longitude'],
'latitude' => $info['latitude'],
'level' => $info['level']);
$index++;
}
$json = json_encode($entries);
echo $json;
mysql_close();
}
retrieveData();
?>
on the end of your script add the following
<script type="text/javascript">
var jsvar = <?php echo $phpvar;?>
</script>
Replace
echo $json;
with
echo 'var fromPhp = ' . $json . ';';
You just need to put the data into a variable. This will make it available as fromPhp on the browser side.
filePHP.php
$query = $kon->prepare("SELECT * FROM t_kategori");
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$json = array('id' => $row['id_kategori'], 'nama' => $row['nama_kategori']);
echo json_encode($json);
}
and index.php
$.post('filePHP.php', function(data){
console.log(data);
},'json');
but this not working, what would solve this problem?
Try this in PHP
$query = $kon->prepare("SELECT id_kategori,nama_kategori FROM t_kategori");
$query->execute();
$json=array();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$arr=array('id'=>$row['id_kategori'],'nama'=>$row['nama_kategori']);
array_push($json,$arr);
}
echo json_encode($json);
Read array-push
try something like this , your code will echo json in wrong format whereas below code will give you json array.
$query = $kon->prepare("SELECT * FROM t_kategori");
$query->execute();
$json_arr =array();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$temp_arr = array();
$temp_arr['id'] => $row['id_kategori'];
$temp_arr['nama'] => $row['nama_kategori'];
array_push($json_arr,$temp_arr);
}
echo json_encode($json_arr);