I cannot access a common array from all PHP files.
I have a PHP application set up similar to this:
index.php
image.php
myvars.php
functions.php
JavaScript.js
index.php
<?php
require("./myvars.php");
require("./functions.php");
session_name("myawesomesession");
session_start();
readfiles($myarray);
// $MYARRAY IS POPULATED
<img src="./image.php" />
// $MYARRAY IS POPULATED
?>
image.php
<?php
require("./myvars.php");
require("./functions.php");
session_name("myawesomesession");
// have also tried "session_start();" here too.
// $MYARRAY IS NULL
$image = getrandomfile($myarray);
header('Content-Type: ' . mime_content_type($image));
readfile($image);
?>
myvars.php
<?php
$myarray = array();
?>
functions.php
<?php
// have also tried "session_name()" and "session_start()" here
require("./myvars.php");
readfiles(&$myarray){
while(){
array_push($myarray, $file);
}
// $MYARRAY IS POPULATED
}
getrandomfile(&$myarray){
// $MYARRAY IS NULL
return $random_file_from_myarray;
}
?>
JavaScript.js
xmlHttp.onreadystatechange = setimage;
xmlHttp.open("GET","./image.php",true);
xmlHttp.send(null);
You can try changing myvars.php to something like this
session_start();
if (!isset($_SESSION['myarray'])) {
$_SESSION['myarray'] = array();
}
$myarray = $_SESSION['myarray'];
and then include
require("./myvars.php");
You will get access to $myarray variable.
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 am making a call to php file, which is picking up data of 'name' and 'email' row-by-row and need to send it as a ajax response to my index.html file. I can fetch the row data but unable to know, how to send back the data as a reply to ajax request in json form.
PHP Code:
if ($result->num_rows > 0){
// output data of each row
while($row = $result->fetch_assoc()) {
echo "jname".$row["name"]."jemail".$row["email"];
}
}
else{
echo "0 results";
}
Instead of just echoing out the data as you are, store it in an array and use json_encode to return it as a json string.
$return = array();
if ($result->num_rows > 0){
$return['result'] = $result->num_rows.' results';
$return['rows'] = array();
// output data of each row
while($row = $result->fetch_assoc()) {
$return['rows'][] = array(
'jname' => $row['name'],
'jemail' => $row['email']
);
}
}
else{
$return['result'] = "0 results";
}
echo json_encode($return);
Put your result in array, and print it via json_encode()
$response = array();
if ($result->num_rows > 0){
// output data of each row
while($row = $result->fetch_assoc()) {
$response[] = array(
'jname' => $row['name'],
'jemail' => $row['email']
);
}
}
echo json_encode($response);
exit();
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.