I am having difficulty in saving all post data to csv file and emailing the values to an address. I have over 125 post variables and im quite stuck. Here is a sample of my code thus far:
<?php
$x23 = "date";
$x24 = "fclose";
$x25 = "fopen";
$x26 = "fwrite";
$x27 = "mail";
$x28 = "time";
extract($_POST);
$a1 = $_POST['fname'];
$a2 = $_POST['lname'];
$a3 = $_POST['email'];
$a4 = $_POST['landline'];
$a5 = $_POST['mobile'];
$a6 = $_POST['addr1'];
$a7 = $_POST['addr2'];
$a8 = $_POST['towncity'];
$a9 = $_POST['postcode'];
$x1d = $a1 . "," . $a2 . "," . $a3 . "," . $a4 . "," . $a4 . "," . $a5 . "," . $a6 . "," . $a7 . "," . $a8 . "," . $a9 . "
";
$quotation = $x25("file5.csv", "a");
$x26($x1d, $quotation);
$x24($x1d);
header('Location: mydomain.co');
$x20 = 'mail#mydomain.com';
$x22 = 'Quotation - My Company';
$x27($x20, $x21, $x23, $x1f);
?>
I have not put all variables in this question (not sure how to do this, but I think fputcsv() would do the job, to save all the 125 variables being written, but Iv'e never much used PHP and not sure on arrays and fputcsv()).
How would I loop through all my post variables and append them to csv as one row?
Any help would be appreciated.
The function you're looking for is implode. It implodes an array into a single string with a specific "glue", in this case ','.
So, the simplest way is to use implode(',', $_POST), but in case not all of the values are supposed to be used, there's a nice way to handle it by changing the names of the form elements.
In the form, if you change the name from "fname" into "data[fname]" and do the same for the rest of the elements, then $_POST['data'] will be an array that holds all of the values. Then using implode(',', $_POST['data']) will make sure only desired values are used.
You first of all need to be disciplined about solving one problem at a time.
(1) Create the CSV data in a variable
(2) Write the data to a file
(3) Send an email
(4) Include an attachment in the email
Or even break it down into more steps. Trying to solve a bunch of problems all at once is only going to get yourself more confused, especially if you are just getting started on programming.
So let's solve the "create the CSV" file.
You can easily loop through your $_POST and create a CSV file like this:
$csv_line = '';
$sep = ''; // don't put a comma before the 1st element
foreach ($_POST as $k -> $v) {
$csv_line .= $sep . "\"$v\"";
$sep = ','; // put a comma before the 2nd, 3rd, etc. elements
}
However, there are at least 2 problems with this. You may not want EVERY element in your $_POST to be put into the CSV, and there is no guarantee of the order those elements within $_POST.
So we'll create a separate array with just the fields we are interested in and making sure they are in the order we want to keep it:
$myFields = array('email',
'fname',
'lname',
'junk',
...);
$csv_line = '';
$sep = ''; // don't put a comma before the 1st element
foreach ($myFields as $k) {
$csv_line .= $sep . "\"$_POST[$k]\"";
$sep = ','; // put a comma before the 2nd, 3rd, etc. elements
}
Now all you have to do is write out that line into a file, figure out how to send an email, and figure out how to attach the file to the email. But at least you are one step closer...
Related
See the code below. The polist is from a textarea field. It loops thought the array. This line produces as expected echo $line . ""; The PO Number is echoed. But the output from the query on v_devices only list the items from the last PO number in the list from the textarea.
Any ideas why? Any help would be most appreciated!!
if(isset($_POST['polist'])){
$polist=$_POST['polist'];
$text = trim($polist);
$textAr = explode("\n", $text);
$textAr = array_filter($textAr, 'trim');
foreach($textAr as $line) {
$result10 = $db->select(
"SELECT * FROM `v_devices` WHERE `ponumber` = :po",
array ("po" => $line)
);
echo $line . "<br>";
foreach($result10 as $row10) {
$poline = $line . "," . $row10['organization'] . "," . $row10['serialn'] . "," . $row10['model'];
echo $poline . "<br>";
}
}
}
The problem is that in the foreach($textAr as $line) loop you keep overwriting $result10 variable that holds the resultset of the query and you print out the results after the loop.
Either move the printing part into into this loop, or you need to add the result of the query to the $result10 variable.
The code below is working in reading per row and count each identical appearances. However, I still need excel to sort per row left to right before I i save it as delimited by as text file. Right now I want to omit the excel step. I checked on php manual and saw the sort and explode functions. I inserted those command but its not working. Can someone help me point to the right direction ?
raw data is :
hero2,hero1,hero3
hero2,hero3,hero4
hero1,hero2,hero3
text file db after excel :
hero1,hero2,hero3
hero2,hero3,hero4
hero1,hero2,hero3
output :
appeared 2x: hero1,hero2,hero3
apprered 1x: hero2,hero3,hero4
Code :
<?php
$data = file("heroes.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = explode(",", $data);
$sort ($lines);
$result = array_count_values($lines);
foreach($result as $v => $amount)
echo "Appeared " . $amount . "x: " . $v . "<br />";
?>
After reading the suggestions and samples of those who answered I came up with this code now.
<?php
$data = file("heroes.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = explode(",", implode($data));
$sorted_lines = sort($lines); // sorted data
$result = array_count_values($lines);
// output the sorted data
foreach($result as $v => $amount) {
echo "Appeared " . $amount . "x: " . $v . "\n";
}
?>
however the ouput became like this
output :
appeared 3x: hero2
appeared 3x: hero3
appeared 2x: hero1
appeared 1x: hero4
correct output should be like this
output :
appeared 2x: hero1,hero2,hero3
apprered 1x: hero2,hero3,hero4
I believe your problem is you are using explode with a space and you should be using it with a comma. explode(",",$data);
I'm thinking you then also want to turn your data back into a string before you try and count them or I don't think you'll get the results you're expecting.
For example...
$sortedString = implode(",", $theArray);
You are looping over the old data before doing the sort. And you are not using a PHP function sort, you are instead making it a kind of a variable (remove the $ before it).
<?php
$data = file("heroes.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = explode(",", $data);
$sorted_lines = sort($lines); // sorted data
$result = array_count_values($sorted_lines);
// output the sorted data
foreach($result as $v => $amount) {
echo "Appeared " . $amount . "x: " . $v . "<br />";
}
?>
This is similar to one of my previous questions here, although this is looking for a solution rather than tools to debug it. I'm trying to build a script to (amongst other things) automatically replace names entered in a MySQL database with the name bolded in WikiMedia format, so when I enter NAME: I expect to get '''NAME''':. What I actually get is NAME'''''':. I've tried a sugestion posted on the aforementioned question to remove Carriage Returns from my array using str_replace(array("\r", "\n"), array('', ''), $row); but it had no effect.
The code I'm using to generate this is:
<?php
$link = mysql_connect($host, $username, $pass);
$db = mysql_select_db($database, $link);
$query = "SELECT name FROM " . $prefix . "";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$name[] = $row['name'];
}
$sim = $_POST['sim']; //Fetches SIM from text box.
$sim_wrap = wordwrap($sim, 80, "\n"); //Constrains to 80 columns for readability.
$sim_penultimate = str_replace("::", "<nowiki>::</nowiki>", $sim_wrap);
$sim_final = str_replace($row . ":", "'''" . $row . "''':", $sim_penultimate); //Bold names
echo stripslashes($sim_final); //Removes slashes wordwrap() adds on some configurations example (James\'s).
?>
Thank you for any help you can give me, this really has me stumped.
$row is a result from mysql_fetch_array() - in other words, it's an array. Why are you concatenating it with a string ($row . ":")? Concatenating an array with a string doesn't work - you instead need to concatenate individual elements.
It seems like what you really want to do is something like this...
$names = array();
$replaces = array();
while($row = mysql_fetch_array($result)){
$names[] = $row['name'] . ":";
$replaces[] = "'''" . $row['name'] . "''':";
}
and then later on...
$sim_final = str_replace($names, $replaces, $sim_penultimate); // Bold names
How can I change the code below so each part is added together in a little bunch instead of smushed together? If a little part that appears on the screen is 123, it should add 12+3 and display 15 instead of 123. I have tried sum_array and other things but it won't work to add PARTS with other PARTS in little bunches. I can only get it to display smushed together results how it is below, or add the wrong parts or the whole thing other ways.
$data = mysql_query('SELECT weight FROM my_table WHERE session_id = "' . session_id() . '"');
$params = array();
while ($row = mysql_fetch_assoc($data)) {
$params[] = $row['weight'];
}
$combinations=getCombinations($params);
function getCombinations($array)
{
$length=sizeof($array);
$combocount=pow(2,$length);
for ($i=1; $i<$combocount; $i++)
{
$binary = str_pad(decbin($i), $length, "0", STR_PAD_LEFT);
$combination='';
for($j=0;$j<$length;$j++)
{
if($binary[$j]=="1")
$combination.=$array[$j];
}
$combinationsarray[]=$combination;
echo $combination . "<br>";
}
return $combinationsarray;
}
It looks like
$combination.=$array[$j];
is your problem . in PHP is used for String Concatenation and not math. Because PHP is a loosely data typed language you are telling PHP to take the String value of $array[$j] and ".=" (append) it to $combination giving you the 12 .= 3 == "123" problem and not 15 like what you want. You should try += instead.
If I understand what you're trying to do, I think you want to use addition + instead of concatination . in the following line:
if($binary[$j]=="1")
$combination += $array[$j];
As many recommend me to separate firstname and lastname instead of "full_name" with everything in, how can I separate them to each variables, so if for you example type in the field: "Dude Jackson" then "Dude" gets in $firstname and Jackson in the $lastname.
It's impossible to do with 100% accuracy, since the first/last name contains more information than a single "full name". (A full name can include middle names, initials, titles and more, in many different orders.)
If you just need a quick fix for a legacy database, it might be OK to split by the first space.
Assuming first name always comes first and there's no middle name:
list($firstname, $lastname) = explode(' ', $full_name);
This simply explodes $full_name into an array containing two strings if they're separated by only one space, and maps them to the first and last name variables respectively.
You can do:
list($first_name,$last_name) = explode(' ',$full_name);
This assumes that you full name contains first name and last name separated by single space.
EDIT:
In case the lastname is not present, the above method give a warning of undefined offset. To overcome this you can use the alternative method of:
if(preg_match('/^(\S*)\s*(\S*)$/',$full_name,$m)) {
$first_name = $m[1];
$last_name = $m[2];
}
$full_name = "Dude Jackson";
$a = explode($full_name, " ");
$firstname = $a[0];
$lastname = $a[1];
you would need to explode the value into its parts using a space as the separator
http://php.net/manual/en/function.explode.php
I am no PHP programmer, but for a quick fix, without data loss,
$full_name = "Dude Jackson";
$a = explode($full_name, " ");
$firstname = $a[0];
$count = 1;
$lastname = "";
do {
$lastname .= $a[$count]." ";
$count++;
} while($count<count($a));
$lastname = trim($lastname);
This should save all remaining part of name in $lastname, should be helpful for names like "Roelof van der Merwe". Also you can throw in checks for $full_name as first name only, without last name.
This is the code/solution
$full_name = "Dude Jackson";
$a = explode($full_name, " ",1);
if(count($a) == 2)
{
$firstname = $a[0];
$lastname = $a[1];
}
if(count($a) < 2)
{
$firstname = $full_name;
$lastname = " ";
}