How can i fit this comma problem with CSV file? - php
I have this code that creates a CVS file with the CF7 information the customer has provided, and it is attached into the mail I receive, the code is into functions.php.
The problem I have is that if a customer puts a comma into any field, like if he put on the name field John, Smith, it breaks the CSV
Do you have any idea how can I fix it?
//Create the shortcode which will set the value for the DTX field
function cf7dtx_counter(){
$val = get_option( CF7_COUNTER, 0) + 1; //Increment the current count
return $val;
}
add_shortcode('CF7_counter', 'cf7dtx_counter');
//Action performed when the mail is actually sent by CF7
function cf7dtx_increment_mail_counter(){
$val = get_option( CF7_COUNTER, 0) + 1; //Increment the current count
update_option(CF7_COUNTER, $val); //Update the settings with the new count
}
add_action('wpcf7_mail_sent', 'cf7dtx_increment_mail_counter');
// Add this to functions.php //
// Create CSV by scraping email using before_send_mail action //
add_action( 'wpcf7_before_send_mail', 'cf7_csv_creation' );
function cf7_csv_creation($cf7) {
// Allow to target the ID of specific form //
$form_id = $cf7->id();
// Check certain form by ID - remove this IF statement if not specific //
// Make sure the file is saved into wp-content to retieve it within WPCF7 settings as an attachement //
$user_register_csv = 'wp-content/uploads/csvs/csvreserva.csv';
// Create file contents - if you have more fields add them to the output below //
$output = "poblacio,tipus,data-entrada,data-sortida,PrimerCognom,SegonCognom,nom,Sexe,data-naixament,identificacio,Adreca,CodiPostal,Ciutat,Provincia,Pais,Telefon,Mobil,email,Estudis,Curs,Centre,Familiar,NIF-familiar,professio-familiar,Adreca-familiar,CodiPostal-familiar,Poblacio-familiar,Provincia-familiar,Pais-familiar,Mail-familiar,Telefon-familiar,Mobil-familiar,questionari-coneixament,questionari-aficions,accepto,num-registre,maildesti,titol,url,arxiu-dni,arxiu-universitat,arxiu-pagament,arxiu-dni-url,arxiu-universitat-url,arxiu-pagament,url,Submitted From,data,accepta-politica,ip,navegador";
$output .= "\n";
$output .= $_POST["residencia"] . ", ";
$output .= $_POST["menu-147"] . ", ";
$output .= $_POST["date-5"] . ", ";
$output .= $_POST["date-6"] . ", ";
$output .= $_POST["text-145"] . ", ";
$output .= $_POST["text-4445"] . ", ";
$output .= $_POST["text-144"] . ", ";
$output .= $_POST["radio-603"] . ", ";
$output .= $_POST["date-34"] . ", ";
$output .= $_POST["text-146"] . ", ";
$output .= $_POST["text-147"] . ", ";
$output .= $_POST["text-1478"] . ", ";
$output .= $_POST["text-149"] . ", ";
$output .= $_POST["text-150"] . ", ";
$output .= $_POST["menu-950"] . ", ";
$output .= $_POST["text-151"] . ", ";
$output .= $_POST["text-1521"] . ", ";
$output .= $_POST["email-775"] . ", ";
$output .= $_POST["text-200"] . ", ";
$output .= $_POST["text-201"] . ", ";
$output .= $_POST["text-202"] . ", ";
$output .= $_POST["text-301"] . ", ";
$output .= $_POST["text-302"] . ", ";
$output .= $_POST["text-313"] . ", ";
$output .= $_POST["text-303"] . ", ";
$output .= $_POST["text-304"] . ", ";
$output .= $_POST["text-305"] . ", ";
$output .= $_POST["menu-951"] . ", ";
$output .= $_POST["text-306"] . ", ";
$output .= $_POST["text-309"] . ", ";
$output .= $_POST["text-308"] . ", ";
$output .= $_POST["text-3048"] . ", ";
$output .= $_POST["text-543"] . ", ";
$output .= $_POST["text-697"] . ", ";
$output .= $_POST["Si"] . ", ";
$output .= $_POST["cf7-coutner"] . ", ";
$output .= $_POST["reserves#sample.com"] . ", ";
$output .= $_POST["Formulario recibido"] . ", ";
$output .= $_POST["https://www.sample.com"] . ", ";
$output .= $_POST["file-628"] . ", ";
$output .= $_POST["file-629"] . ", ";
$output .= $_POST["file-630"] . ", ";
$output .= $_POST[""] . ", ";
$output .= $_POST[""] . ", ";
$output .= $_POST[""] . ", ";
$output .= $_POST["1"] . ", ";
$output .= $_POST["_date"] . ", ";
$output .= $_POST["Si"] . ", ";
$output .= $_POST["_remote_ip"] . ", ";
$output .= $_POST["_user_agent"] . ", ";
$output .= $_POST["your-email"];
// Save contents to file //
file_put_contents($user_register_csv, $output);
}
// Clear file/user data after submission //
add_action('wpcf7_mail_sent', function ($cf7) {
$user_register_csv = 'wp-content/uploads/csvs/csvreserva.csv';
file_put_contents($user_register_csv, '');
// File cleared and ready to be rewritten on next submission //
});
// Remember - add the above path to the WPCF7 File attachment setting within the relevant form //
I think the guy that commented on you post has a better solution but alternatively you can add this line before you assign a value to $output
$_POST = str_replace(",","",$_POST);
This will replace all the commas in $_POST with an empty character so even if the user enters a comma it will get replaced with an empty character.
If you want to keep the commas that the user enters, you can enclose the $_POST variable in quotation marks when extending the value of the $output variable. For example:
$output .= '"'.$_POST["residencia"].'", ';
Related
How to refactor a long function?
I have a function that prepares a receipt output. But since it has all kinds of conditions it ends up being very long and difficult to understand.. How would one go about refactoring this? Any ideas? If I split this into 100 small functions would that really be better? public static function prepare_receipt($printer) { if (self::hasItems($printer['id'])) { $output = ''; if ($_POST['pre_receipt']) { $output .= "======== Pre receipt =======\n\n\n"; } /** * Time and table */ if ($_POST['isTakeaway'] || $_POST["isDeliveryGuys"] || $_POST["isBolt"]) { $output .= "Table: " . $_POST['table'] . "\n"; $output .= "Floor: " . $_POST['floor'] . "\n"; $output .= "Time: " . $_POST['takeawayTime'] . "\n"; if ($_POST['order_comment']) { $output .= "Comment: " . removeSpecialChars($_POST['order_comment']) . "\n"; } } else { $output .= "Table: " . $_POST['table'] . "\n\n"; $output .= "Floor: " . $_POST['floor'] . "\n\n"; if ($_POST['order_comment']) { $output .= "Comment: " . removeSpecialChars($_POST['order_comment']) . "\n"; } } $output .= "------------------------\n"; /** * Food items */ foreach ($_POST['orderedItems'] as $orderedItem) { $has_unprinted_quantity = false; if (isset($orderedItem['last_printed_quantity'])) { $unprinted_quantity_count = intval($orderedItem['is_printed_quantity']) - intval($orderedItem['last_printed_quantity']); if ($unprinted_quantity_count > 0) { $has_unprinted_quantity = true; } } if ( ($orderedItem['should_print'] && !$orderedItem['is_printed'] && $orderedItem['is_visible']) || $_POST['pre_receipt'] || $has_unprinted_quantity) { if (is_array($orderedItem['printers'])) { $in_printer = in_array($printer['id'], $orderedItem['printers']); } else { $in_printer = in_array($printer['id'], json_decode($orderedItem['printers'], true)); } if ( $in_printer || $_POST['pre_receipt'] ) { if ($orderedItem['is_sidedish'] && !$_POST['pre_receipt']) { continue; } if ($has_unprinted_quantity) { $output .= $unprinted_quantity_count . 'x '; } else { $output .= $orderedItem['quantity'] . 'x '; } // We ned to split it for multiple lines... $itemDescriptionParts = self::split($orderedItem['description']); foreach ($itemDescriptionParts as $itemDescription) { $itemDescriptionClean = removeSpecialChars($itemDescription); $output .= $itemDescriptionClean; } // Add price for pre receipt if ($_POST['pre_receipt']) { $output .= " - " . number_format($orderedItem['price_with_discount'], 2, '.', ','); } if (!$_POST['pre_receipt']) { if ($orderedItem['comments'] != '') { $output .= " > " . removeSpecialChars(substr($orderedItem['comments'], 0, 27)) . "\n"; } } /** Side dishes */ if (isset($orderedItem['side_dishes']) && !$_POST['pre_receipt']) { foreach ($orderedItem['side_dishes'] as $side_dish) { $output .= "\n + " . removeSpecialChars(substr($side_dish['description'], 0, 27)) . "\n"; } } $output .= "\n"; } } } /** * Sums */ /** * Footer */ $output .= "------------------------\n"; if ($_POST['pre_receipt']) { $output .= "\nSubtotal: " . number_format($_POST['order']['subtotal'], 2, '.', ',') . "\n"; $output .= "Discount: " . number_format($_POST['order']['discount'], 2, '.', ',') . "\n"; $output .= "Total: " . number_format($_POST['order']['total'], 2, '.', ',') . "\n\n"; } $output .= "Time: " . getTime() . "\n"; return $output; } else { return 'EMPTY'; } } Any pointers in the right direction would be much appreciated.
Refactoring works often well, if it follows semantics. In your case: You made already comments for different sections. This is often a sign for a function on it's own. Just to give you an idea: How it may look like afterwards: $output .= create_headline(...); $output .= create_time_table(...); $output .= create_separator(); foreach ($_POST['orderedItems'] as $orderedItem) { $output .= create_food_item($orderedItem, $_POST['pre_receipt'], ...); } $output .= create_separator(); $output .= create_footer(...); This will save time when searching for a bug in a certain area of the receipt.
I would advice https://en.wikipedia.org/wiki/Divide-and-conquer_algorithm, and your function already has comment that indicates how this function can be divided in multiple that has a single responsability. I would also advice not to use $_POST directly, all input data must always be validated and possibly filtered. Data from input should be passed as dependency, to adhere dependency injection, see https://phptherightway.com/ for other good practices. I would also avoid the use of string concatenation, store all the parts within an array and then join/implode them using a separator.
Looking at your code smart use of ternary operators and shifting the orderitem loop into different function can drastically reduce your code length by half. There is no need to create function for each operation like printing head, printing tail etc as the logic in those print is pretty simple and your code can prettry muddy and difficult to navigate if there are large number of unwanted functions. You can do something like below. Also note using . (dot) operator for string concatenation make your string less readable hence prefer printing variables with {} operator. <?php public static function prepare_receipt($printer) { if (self::hasItems($printer['id'])) { $output = isset($_POST['pre_receipt']) ? "======== Pre receipt =======\n\n\n" : "" ; //addiing time table $output .= "Table: {$_POST['table']}. \n Floor: {$_POST['floor']}. \n"; //adding time if it is takeaway or isDeliveryGuys or isBolt $output .= ($_POST['isTakeaway'] || $_POST["isDeliveryGuys"] || $_POST["isBolt"]) ? "Time: {$_POST['takeawayTime']}. \n" : "" ; //adding order comment $output .= $_POST['order_comment']) ? "Comment: {removeSpecialChars($_POST['order_comment'])} \n" : "" ; //print order items this->getOrderItems($_POST[orderedItems], &$output); // footer $output .= "------------------------\n"; if ($_POST['pre_receipt']) $output .= "\nSubtotal: {number_format($_POST['order']['subtotal'], 2, '.', ',')} \n Discount: { number_format($_POST['order']['discount'], 2, '.', ',') } \n Total: {number_format($_POST['order']['total'], 2, '.', ',')} \n\n"; $output .= "Time: " . getTime() . "\n"; return $output; } else { return 'EMPTY'; } } ?> .
TCPDF - Having trouble with getting MySQL content to show in PDF
I am trying to make a printable version of a catalogue of products. If I display the products in HTML it works fine. But when I try and use TCPDF I loose half of it or nothing at all. $query = "SELECT ID, Category_Name, Image FROM Categories ORDER BY Position ASC"; $result = mysqli_query($connection, $query); confirm_query($result); while ($cat = mysqli_fetch_row($result)) { // add a page $pdf->AddPage(); $query1 = "SELECT * FROM Products WHERE Category = " . $cat[0] . " AND Visibility = 1 ORDER BY Product_Name ASC"; $result1 = mysqli_query($connection, $query1); $html = $query1; confirm_query($result1); //$html .= '<style>'. file_get_contents('./images/print.css').'</style>'; $html .= '<table style="margin: 0 auto;"><tbody>'; $html .= '<tr><th colspan="6"><div id="title" style="color: white;">' . $cat[1] . '</div></th></tr>'; $html .= '<tr>'; $html .= '<th></th>'; $html .= '<th>Product</th>'; $html .= '<th>Pack Size</th>'; $html .= '<th>Price(Ex VAT)</th>'; $html .= '<th>Price(Inc)</th>'; $html .= '<th>RRP</th>'; $html .= '</tr>'; // Show product prodcuts from selected category while ( $row123 = mysqli_fetch_row($result1)) { $html .= '<tr><td>'; $html .= '<img width="100px" height="100px" src="/images/' . $row123[6] . '"/>'; $html .= '</td><td>'; $html .= '<b><u>' . $row123[1] . '</u></b><br /><i>' . $row123[5] . '</i>'; $html .= '</td><td>'; $html .= $row123[3]; $html .= '</td><td>'; $html .= '£' . $row123[4]; //echo '<br />'; $html .= '</td><td>'; $query2 = "SELECT VAT FROM VAT WHERE ID = " . $row123[7]; $result2 = mysqli_query($connection, $query2); confirm_query($result2); // Put results in an accessible form $result_array2 = array(); while ($row234 = mysqli_fetch_row($result2)) {$result_array2[] = $row234;} $html .= '£' . number_format($row123[4] + ($result_array2[0][0] * $row123[4] / 100), 2, '.', ''); $html .= '</td><td>'; if ($row123[9] == "") { $html .= "N/A"; } else { $html .= '£' . number_format($row123[9], 2, '.', ''); } $html .= '</td>'; $html .='</tr>'; } $html .= '</tbody></table>'; // output the HTML content $pdf->writeHTML($html, true, false, true, false, ''); } If I comment out the second while loop, I can get the first query ($query1) to echo out. One per page for each category. But when I uncomment it, it just creates 4 blank pages.
cant display two image links from mysql php
function find_image_by_id() { global $connection; $query = "SELECT * "; $query .= "FROM images "; $query .= "WHERE page_id={$_GET["page"]}"; $image_set = mysqli_query($connection, $query); confirm_query($image_set); return $image_set; } function display_image_by_id(){ $current_image = find_image_by_id(); while($image=mysqli_fetch_assoc($current_image)){ $output = "<div class=\"images\">"; $output .= "<img src=\"images/"; $output .= $image["ilink"]; $output .= "\" width=\"72\" height=\"72\" />"; $output .= $image["phone_name"]; $output .= "</div><br />"; } mysqli_free_result($current_image); return $output; } This is the code I'm using to show the images stored as links in mysql and the images are in a folder. But what happens after this code is executed only the second value is displayed. I want both value/ images to be displayed.
Try something like that- All you need to do is just initialize this variable outside the loop. $output =''; //initialize before SO your function look like this - function display_image_by_id(){ $current_image = find_image_by_id(); $output =''; //initialize before while($image=mysqli_fetch_assoc($current_image)){ $output .= "<div class=\"images\">"; $output .= "<img src=\"images/"; $output .= $image["ilink"]; $output .= "\" width=\"72\" height=\"72\" />"; $output .= $image["phone_name"]; $output .= "</div><br />"; } mysqli_free_result($current_image); return $output; }
Prepared PHP statement not printing out
I have a statement that is grabbing information from the database, and then is printed out after it is fully prepared.. For some reason though, my script is not printing out the information. I have it in this if statement: if($community == ''){ print $community . "\n\n" . "END" . "\n"; } else { print $community; echo "hi";} This prints out when it is ran: () wrote: But that is all it prints out. That is coming from the 8th $community .= line. So, my question is, why is it ONLY printing out () Wrote: and not all the variables as well? // and ticker_symbol ='".$sym."' $c_sql = "SELECT message_id, subject, author, FROM_UNIXTIME(datestamp,'%m-%d-%Y') AS formatted_datestamp, forum_id, body, thread, user_id FROM phorum_messages WHERE user_id=13423720 ORDER BY datestamp DESC LIMIT 5"; $c_result = mysql_query($c_sql,$connection) or die("Couldn't execute get query"); // Declare Variables $body = $c_result['body']; $forum_id = $c_result['forum_id']; $user_id = $c_result['user_id']; $author = $c_result['author']; $formatted_datestamp = $c_result['formatted_datestamp']; // Prepare the statement if ($c_result != "") { $community .= $forumPost = '<<<ENDL '. "\n"; $community .= $body . "\n"; $community .= 'ENDL;' . "\n"; $community .= '$forumPost = stripBBCode(strip_tags($forumPost));' . "\n"; $community .= "\n"; $community .= '<div class="comment">' . "\n"; $community .= '<table cellspacing="0" cellpadding="0" border="0" class="reply"><tbody><tr>' . "\n"; $community .= '<td width="90%"><b>'.$author.' ('.$formatted_datestamp.') wrote:</b><br />' . "\n"; $community .= '<p>'.iconv("ISO-8859-1//TRANSLIT", "UTF-8", $forumPost).'</p></td>' . "\n"; $community .= '</tr></tbody></table>'. "\n"; $community .= '</div>' . "\n"; } // Print out the prepared statement if($community = ''){ print $community . "\n\n" . "END" . "\n"; } else { print $community;}
When you are calling if($community = ''){ you only have one equals sign which will set $community to a blank string. I think what you mean to do is if($community == ''){
It should have the double-equal: if($community == '') With a single = sign you're simply assigning an empty string to variable $community - and then checking whether it's true. Empty strings evaluate to false, hence you're getting into your else part - and losing your value in the process.
You only have one = sign you need: if($community == '') { etc...
Display a table in while loop
I am trying to display a table in while loop with 3 rows and 3 td for each row. But I am confusing how to archived thit. This is my code so far: while($row = mysqli_fetch_array($result)){ $testimonial = $row['testimonial']; $cityName = $row['city_name']; $name = $row['name']; $imageName = $row['image_name']; $member = $row['membership_type']; $testimonial = nl2br($testimonial); //Create new testimonial output $output = "<table>\n"; $output .= " <tr>\n"; $output .= " <td>\n"; $output .= " <p>\n"; $output .= " <img src=\"".UPLOAD_DIR.$imageName."\" />"; $output .= " {$testimonial}"; $output .= " </p>\n"; $output .= " <p class=\"name\">{$name}<br />\n"; $output .= " <span>A Teacher - From {$cityName}</span></p>\n"; $output .= " </td>\n"; $output .= " </tr>\n"; $output .= "</table>\n"; echo $output; } The above code given me a table with multiple rows and 1 td for each row. But it is not my expecting result. Can anybody tell me how can I display such a table in my While loop?
The current code creates a new table for every single entry. What you want is to move the <table> and </table> pieces outside of the loop, then you want a counter to keep track of how many cells you've handled. If it's even, start a new <tr>. Otherwise, end the current </tr>. Make sure you check at the end to see if you've finished a </tr>, and optionally add an empty <td></td> if needed.
this aught to do it <?php echo "<table>\n"; $cells = $total = 0; $total_cells = mysqli_num_rows($result); while($row = mysqli_fetch_array($result)) { $testimonial = nl2br($row['testimonial']); $cityName = $row['city_name']; $name = $row['name']; $imageName = $row['image_name']; $member = $row['membership_type']; if ($cells === 0) echo "<tr>\n"; //Create new testimonial output $output = " <td>\n"; $output .= " <p>\n"; $output .= " <img src=\"".UPLOAD_DIR.$imageName."\" />"; $output .= " {$testimonial}"; $output .= " </p>\n"; $output .= " <p class=\"name\">{$name}<br />\n"; $output .= " <span>A Teacher - From {$cityName}</span></p>\n"; $output .= " </td>\n"; echo $output; $cells++; $total++; if ($cells === 3 || $total === $total_cells) { echo "</tr>\n"; $cells = 0; } } echo "</table>\n"; ?>
Try this $i = 0; echo "<table>\n<tr>"; while($row = mysqli_fetch_array($result)){ $testimonial = $row['testimonial']; $cityName = $row['city_name']; $name = $row['name']; $imageName = $row['image_name']; $member = $row['membership_type']; $testimonial = nl2br($testimonial); //Create new testimonial output $output .= " <td>\n"; $output .= " <p>\n"; $output .= " <img src=\"".UPLOAD_DIR.$imageName."\" />"; $output .= " {$testimonial}"; $output .= " </p>\n"; $output .= " <p class=\"name\">{$name}<br />\n"; $output .= " <span>A Teacher - From {$cityName}</span></p>\n"; $output .= " </td>\n"; echo $output; if( $i %2 == 1 ) echo "</tr><tr>\n"; $i++; } echo "</tr>\n</table>\n"; EDIT In general, for displaying n cells per row, change the if statement to if( $i % n == (n - 1) )