Data values need to store in CSV file - php

I cant stored data csv in file
I can Load the data but I cant stored the data in the CSV files and stored the file in the specific folder
My requirement was to load the web form details and send the email to specific users. I can able to download the csv file but I cant store the details in CSV file
function webform_email_menu() {
$items = array();
$items['webform_email'] = array(
'title' => 'Webform Email', //page title
'description' => 'Webform Information', //description show when mouse hover on link
'page callback' => 'webform_list', //callback function which is invoked when menu item is called.
'access callback' => true, //any user can access this page
);
return $items;
}
function webform_list() {
module_load_include('inc', 'webform', 'includes/webform.export');
module_load_include('inc', 'webform', 'includes/webform.components');
module_load_include('inc', 'webform', 'includes/webform.submissions');
$submissions = webform_get_submissions(125);
echo "installation Type,Date of Purchase,Date of Install ,Outdoor Unit Model,Outdoor Unit Serial,Indoor Unit 1 Model,Indoor Unit 1 Serial,Indoor Unit 2 Model,Indoor Unit 2 Serial,Indoor Unit 3 Model,Indoor Unit 3 Serial,Indoor Unit 4 Model,Indoor Unit 4 Serial,Indoor Unit 5 Model,Indoor Unit 5 Serial,Indoor Unit 6 Model,Indoor Unit 6 Serial,Indoor Unit 7 Model,Indoor Unit 7 Serial,Indoor Unit 8 Model,Indoor Unit 8 Serial,Indoor Unit 9 Model,Indoor Unit 9 Serial,Owner First Name,Owner Last Name,Installation Address 1,Installation Address 2,City,State/Province,Zip/Postal Code,Country ,Owner Phone Number,Owner Email,Contractor Information,Contractor Name,Contractor Address 1 ,Contractor Address 2,City,State/Province,Zip/Postal Code,Country,Contractor Phone Number,Contractor Email,Distributor Name,Distributor Address 1,Distributor Address 2,City,State/Province,Zip/Postal Code,Country,TAC,Privacy Statement\n";
$surveycomponents = db_select('webform_component')
->fields('webform_component')
->condition('nid', 125)
->orderBy('weight')
->orderBy('name')
->execute()
->fetchAllAssoc('cid', PDO::FETCH_ASSOC);
$count =0;
$i=2;
foreach ($submissions as &$submission) {
$submission_value=$submission->data;
$i=0;
foreach($submission_value as $submissionvalue){
$numItems = count($submission_value);
if(++$i === $numItems) {
echo $csv_export="\n";
}else{
echo $csv_export=$submissionvalue[0].',';
}
}
}
$file_open = fopen('sites/default/files/csv/csvfile.csv', "a");
file_put_contents("sites/default/files/csv/csvfile.csv", $csv_export);
$csv_handler = fopen ('sites/default/files/csv/csvfile.csv','w');
fwrite ($csv_handler,$csv_export);
fclose ($csv_handler);
}
where I did mistake

You can store the data in CSV file using an array like this
$data = [[1,2,3][11,22,33]];
$fp = fopen('test.csv', 'w');
foreach ($data as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);

Check your folder permissions. i.e. sites/default/files/csv. It should be writable in order to write something into file.

I'm not sure about you are expected but you need to use drupal functions to get righet path to use and prepare it be modified :
$path = drupal_realpath('public://').DIRECTORY_SEPARATOR.'csv';
file_prepare_directory($path);
$file_open = fopen($path.'/csvfile.csv', "a");
file_put_contents($path.'/csvfile.csv', $csv_export);
[...]
https://api.drupal.org/api/drupal/includes%21file.inc/function/file_prepare_directory/7.x
https://api.drupal.org/api/drupal/includes%21file.inc/function/drupal_realpath/7.x

Related

0 records found PHP

I am talking with a MLS server and I'm pretty sure that I am on it. It just won't give me any arrays back.
I am logged on successfully
I pulled the Array of Listings Here are two that you may need to know.
[LIST_10] => Begin Date
[LIST_15] => Status
This worked
if($connect) {
/* Get table layout */
$fields = $rets->SearchQuery("Property", "A");
/* Take the system name / human name and place in an array */
$table = array();
foreach($fields as $field) {
$table[$field['SystemName']] = $field['LongName'];
}
/* Display output */
print_r($table);
$rets->Disconnect();
}
}
This returns 0 Records Found
if($connect) {
$sixmonths = date('c', time()-15778800); // get listings updated within last 6 months
/* Search RETS server */
$search = $rets->SearchQuery(
'Property', // Resource
"A", // Class
'((LIST_10>='.$sixmonths.'+),(LIST_15=ACT))', // DMQL, with SystemNames
array(
'Format' => 'COMPACT-DECODED',
'Select' => 'LIST_0,LIST_1,LIST_34,LIST_39,LIST_40,LIST_0,LIST_133',
'Count' => 1,//0 no record count, data 1 record count + data 2 record count, no data
'Limit' => 20
)
);
/* If search returned results */
if($rets->TotalRecordsFound() > 0) {
while($data = $rets->FetchRow($search)) {
print_r($data);
}
}
}
I am using this tutorial: http://dangodesign.net/2013/01/getting-started-with-rets-for-php/
Is there any information that would help more?
Change your DMQL from:
'((LIST_10>='.$sixmonths.'+),(LIST_15=ACT))'
To:
'((LIST_10='.$sixmonths.'+),(LIST_15=ACT))'
You don't need a > sign in your query that is what the + sign means. I found this site to have a nice introduction to DMQL queries: FlexMLS
If you are able to connect with PHPRETS then you just need to try and change the following query and try to process the results.
Can you please paste the metadata online somewhere?
Change your DMQL from:
'((LIST_10>='.$sixmonths.'+),(LIST_15=ACT))'
to:
'(LIST_10>={$sixmonths}+),(LIST_15=ACT)'
Also make sure the field names are correct and try using Standard Names instead of System Names.

Problems Creating my own Database in php

recently I decided to make my own database in php The reason is because I'm making a mini game online and I need to send some information more fast as possible (I Know it is not the best way to do that since I use web-pages.), So I noticed If I query a web-page (that has the php file) and then query a database, it takes me 1 seconds to 1.3 seconds which is a lot to me, So IF I just query a web-page it usually takes me 0.5 seconds so that is perfect to my purpose.
So What I need to do is save a multi array in the file 'db.txt' and make some checks for example if there is a value where the id is equal to 1 it should just change the array where the id is equal to 1 if there isn't a value where the id is equal to 1, so add it and the next time just modify.
This is what I did so far:
<?php
$id = $_REQUEST['id'];
$positionX = $_REQUEST['positionX'];
$positionY = $_REQUEST['positionY'];
$infoDB = fopen("db.txt", "a+");
$conteudo = fread($infoDB, 4096);
$obj = json_decode($conteudo, true);
if($conteudo == ''){
$table = json_encode(array(
array('id' => $id, 'positionX' => "$positionX", 'positionY' => "$positionY", 'hp' => 100, 'hpmax' =>100, 'hit' => 0, 'mp' => 0, 'mpmax' => 0)
));
$infoDB = fopen("db.txt", "a+t");
fwrite($infoDB,$table);
echo 'Writing first time ...';
}else{
$infoDB = fopen("db.txt", "a+");
$conteudo = fread($infoDB, 4096);
$array = json_decode($conteudo, true);
array_walk($array, "busca", $id);
}
function busca($valor, $chave, $it) {
if($valor['id']==$it){
$valor['positionX'] = $GLOBALS["positionX"];
$valor['positionY'] = $GLOBALS["positionY"];
$table = json_encode(array($valor));
$infoDB = fopen("db.txt", "w+");
fwrite($infoDB,$table);
echo $valor['id']." / ".$valor['positionX']." [".$valor['positionY']."]";
echo 'rewriting...';
}else{
$id = $GLOBALS["id"];
$positionX = $GLOBALS["positionX"];
$positionY = $GLOBALS["positionY"];
$arr = array('id' => $id, 'positionX' => "$positionX", 'positionY' => "$positionY", 'hp' => 100, 'hpmax' =>100, 'hit' => 0, 'mp' => 0, 'mpmax' => 0);
$valor[] = $arr;
$table = json_encode(array($valor));
$infoDB = fopen("db.txt", "w+");
fwrite($infoDB,$table);
echo 'Adding One more. '.$valor['id']." e ".$id;
}
return;
}
fclose($infoDB);
?>
I used the json_encode to save the array in the database.txt
This is how I believe My script work.
So first It gets the id, positionX and positionY, I open the db.txt
and then I decode it to array, I check if the db($conteudo) was empty
or not if so It write the first array if not It should check if there
is a value where id is equal a ($id = $_REQUEST['id'];) But there is a
bug in somewhere that make it just check the first value/array that was
saved on the db.txt I used a array_walk to try to do that But that is
the first time I used a array_walk so I don't know if I'm making it
right or wrong. If there is a better way to do what I want to do
please guys help me!! D:
Your assumtions about the speed of database-queries sound verry vague to me. Usually a latency as you describe it happens when the database is not on the same machine as the webserver, not in the same compute center and hast to make a connection via internet.
Usually the I/O speed heirachy looks something like this (beginning with the fastest)
Memcache on same machine
Memcache in local network
Database on same machine
Database in local network
File System of your machine
File System in local network
So if you really need to cache some basic key => value data and retrieve it at the speed of light, store it in memcache (i recommend the php memcached package). Memcache is simillar to what you want to build, but it is already finished, so you can go on work on your game.

Connection getting reset but execution still happening in background in PHP?

I have just changed my host, and everything is now running smoothly, with only one glitch.
I have a page (precisely.me/fpl/epl), which gives the user the option to refresh the score. This is basically a link to precisely.me/fpl/eplrefresh which fetches data from another site, updates the table, and then redirects it back to precisely.me/fpl/epl.
The thing is that I'm getting this error on Chrome - The webpage at http://precisely.me/fpl/eplrefresh might be temporarily down or it may have moved permanently to a new web address
and something similar on Firefox - The connection to the server was reset while the page was loading.
I tried to set max_execution_time = 300 in php.ini but that didn't work. Do note that despite this error, the script is running successfully in the background, and the scores do get updated. But before it can redirect the user, I get the error.
What should I be changing in php.ini to make it work?
This really shouldn't be needed as it works on localhost and my previous server. But anyways snippet of eplrefresh.php
<?php
$dbc=mysqli_connect('localhost','root','','fplscore') or die("can't connect");
$team_epl=array("Arsenal","Aston Villa", "Chelsea","Everton"); //Trimmed for now
$teamid_epl=array("24854","17","109276","57");
$playernames_epl=array("Jackoff", "Epic Fail", "ENR", "Beric");
set_time_limit(500); //Minimum time for page to expire
$i=0;
foreach ($teamid_epl as $x)
{$team_name=$team_epl[$i];
$thisgw = mysqli_fetch_array(mysqli_query($dbc,"select gwno from gameweek"));
$gw=$thisgw['gwno'];
$str2="http://fantasy.premierleague.com/entry/".$x."/event-history/".$gw;
$file=fopen($str2,"r") or die("Heavy load on FPL. Please try later");
while(!feof($file))
{$str=fgets($file);
if(preg_match('/(<div class="ismSBValue ismSBPrimary">(.*))/', $str,$ar))
{ $str2=fgets($file);
$str2=fgets($file);
$str2 = strip_tags($str2);
$str2=str_replace("pts","",$str2);
$temp1=(int)$str2;
}
if(preg_match('/(<dl class="ismDefList ismSBDefList">(.*))/', $str,$ar))
{ .....
$str2=fgets($file);
$str2 = strip_tags($str2);
$str2=str_replace("pts","",$str2);
$str2=str_replace("(-","",$str2);
$str2=str_replace(")","",$str2);
$temp2=(int)$str2;
$z=$temp1-$temp2;
$gw=$gw-19;
$gw="gw".$gw;
$q="update epl_score set ".$gw."=$z where team='$team_name'" ;
$result=mysqli_query($dbc,$q) or die("unable to execute query");
}
}
$i++;
}
header("Location: epl");
?>
The construction click -> update from remote server -> redirect is not a very good one. With more then a few users you will get into serious problems because you will run out of workers.
Why not set up a cronjob to get the latest scores, save them somewhere and pull updates scores with ajax. Much less overhead (or even better, push them !).
We will need to see your code to know what is wrong with it.
Ps, my money is on a timeout/error somewhere between the apache server and the php backend. This probably is not something that you can fix.
You posted your code now ..... try adding exit(); after the header and dont close your php code (it could send newlines and you dont want that when redirecting)
I've just restructured your code a little bit for performance improvement.
The most important thing I made is removing $thisgw = mysqli_fetch_array(mysqli_query($dbc,"select gwno from gameweek")); from the foreach because it is always the same.
Other than that how many times is your update query executed per team? This should be exactly 1 time. Therefore I would try to remove this part from the while of the file reader.
<?php
$dbc=mysqli_connect('localhost','root','','fplscore') or die("can't connect");
$epl_arr = array(
array('id' => 24854, 'team' => 'Arsenal', 'player' => 'Jackoff'),
array('id' => 17, 'team' => 'Aston Villa', 'player' => 'Epic Fail'),
array('id' => 109276, 'team' => 'Chelsea', 'player' => 'ENR'),
array('id' => 57, 'team' => 'Everton', 'player' => 'Beric'),
);
$thisgw = mysqli_fetch_array(mysqli_query($dbc,"select gwno from gameweek"));
foreach ($epl_arr as $ea)
{
$gw = $thisgw['gwno'];
$team_name = $ea['team'];
$team_id = $ea['id'];
$player_name = $ea['player'];
$str2="http://fantasy.premierleague.com/entry/".$team_id."/event-history/".$gw;
$file=fopen($str2,"r") or die("Heavy load on FPL. Please try later");
while(!feof($file))
{
$str=fgets($file);
if(preg_match('/(<div class="ismSBValue ismSBPrimary">(.*))/', $str,$ar))
{
$str2 = fgets($file);
$str2 = fgets($file);
$str2 = strip_tags($str2);
$str2 = str_replace("pts","",$str2);
$temp1 = $str2;
}
if(preg_match('/(<dl class="ismDefList ismSBDefList">(.*))/', $str,$ar))
{
$str2 = fgets($file);
$str2 = strip_tags($str2);
$str2 = str_replace("pts","",$str2);
$str2 = str_replace("(-","",$str2);
$str2 = str_replace(")","",$str2);
$temp2 = $str2;
$z = $temp1-$temp2;
$gw = $gw-19;
$gw = "gw".$gw;
$q = "update epl_score set ".$gw."=$z where team='$team_name'" ;
$result=mysqli_query($dbc,$q) or die("unable to execute query");
}
}
}
header("Location: epl");
?>
If this doesn't help, also have a look at memory_limit.
Maybe you can also remove your header at the end of the file for testing purpose. There might be a problem with output before it.
Also try debugging with setting ini_set('error_reporting', E_ALL);

Sending Data to 2 MySQL tables - FuelPHP / PHP

I am adapting StationWagon (FuelPHP app) and so far it's working really well.
I have adapted it (with some help) to allow multiple images to be uploaded to the server. This is also working great.
However, I am thinking it would make more sense if I had 2 Tables: 1) Articles and 2) ArticleImages. I would use a Foreign Key to associate the Images with the Article. So when publishing an article it would add the article data to 'Articles' table and move each image to a new row in 'ArticleImages'.
So ultimately my 'ArticleImages' table could be:
ID | ImageURL | ArticleID
Portion of my 'articles.php' controller:
<?php
public function action_add()
{
$val = Model_Article::validate('add_article'); //<-- maybe its just me but i never saw any similar to this in fuelphp sorry about this if im wrong
// if your form validation is okay than continue with everyhing else
if ($val->run())
{
$article = Model_Article::forge();
// Custom configuration for this upload
$config = array(
'path' => DOCROOT.DS.'images',
'randomize' => true,
'ext_whitelist' => array('img', 'jpg', 'jpeg', 'gif', 'png'),
);
Upload::process($config);
// if a valid file is passed than the function will save, or if its not empty
if (Upload::is_valid())
{
// save them according to the config
Upload::save();
//if you want to save to tha database lets grab the file name
$value = Upload::get_files();
foreach($value as $files) {
print_r($files);
}
$article->filename = $value[0]['saved_as'];
}
$status = (Input::post('save_draft') ? 0 : 1);
if ( ! $val->input('category_id'))
{
$category_id = null;
}
else
{
$category_id = $val->validated('category_id');
}
$article->user_id = $this->user_id;
$article->category_id = $category_id;
$article->title = $val->validated('title');
$article->body = $val->validated('body');
$article->published = $status;
if ($article->save())
{
Session::set_flash('success', 'Article successfully added.');
}
else
{
Session::set_flash('error', 'Something went wrong, '.
'please try again!');
}
Response::redirect('articles/add');
}
$this->template->title = 'Add Article';
$this->template->content = View::forge('articles/add')
->set('categories', Model_Category::find('all'), false)
->set('val', Validation::instance('add_article'), false);
}
/* End of file articles.php */
So when i made the code for you back a few days a go you only requested, one file input.
And no offense but you are doing it all wrong...
foreach($value as $files) {
print_r($files);
}
$article->filename = $value[0]['saved_as'];
should be
foreach($value as $files) {
$articleimg = Model_Articleimages::forge();
$articleimg->image_row_name = $files['saved_as']
}
To get you to understand
what you did here, $value = Upload::get_files(); yes this gets all the elements but since you need to loop trouh the elements you dont need it
Second
this $value[0]['saved_as'] only grabs the first image name, just the first one, and since you are in a loop now you need to refer to the $files variable as i shown you in the above example, just an example
You are trying to make a relation between Articles and ArticleImages. An ArticleImage belongs to an Article, while an Article has many ArticleImages. FuelPHP has functionality built in for what you are trying to achieve. Have a look at the FuelPHP docs on its Object Relational Mapper, especially the Belongs To and Has Many relations.

While loop select all contacts

Okay so I have a script that generated pdf reports from a php page for different clients. At the moment this can only handle one client at a time but I would like to add a while statement to be able to cope when 'ALL' clients are picked from the drop down.
The while should select * contacts from mydatabase.mytable and run through the normal code for each. This is the bit I dont know how to do.
I know its something like this but can't quite remember the syntax...
<?php
$client_id=$_POST["client_id"];
$date_start=$_POST["date_start"];
$date_end=$_POST["date_end"];
if ($client_id == 'ALL') {
}
else
{
$command="php myfile.php $client_id $date_start $date_end > myfile.html";
exec($command, $output, $status);
if ($status!=0) {print_r($output); die("wget failed with status $status"); }
$command="wkhtmltopdf-i386 --margin-left 5mm --margin-right 5mm myfile.html myfile.pdf";
exec($command, $output, $status);
if ($status!=0) die("htmltopdf failed");
}
?>
Any suggestions would be appreciated
Many thanks
A simple if control structure would suffice.
if ('All' == $client_id) {
// e.g. - generateReport(-1)
// Your function would look for -1 so it knows to generate for all
}
else {
// e.g. - generateReport($client_id);
}
If you select ALL contacts from your database, then you should be able to get back an array of some sort, perhaps something like this:
array(
['John Smith'] => array( 'company' => 'xyz'),
['Anna Citizen'] => array( 'company' => 'abc),
)
To generate the above array, you can check for "ALL" contacts:
if ($_POST['dropdown'] == "ALL"){
//generate for ALL
}else{
//generate for 1 contact
}
Then you can use the foreach loop to iterate through your array for ALL contacts:
foreach ($contacts as $contact => $attributes){
var_dump($contact); //John Smith
var_dump($attributes); // array('company' => 'xyz);
var_dump($attributes['company']); //xyz
//Do whatever to generate reports.
}

Resources