PHP - Writing Multiple File Names To A Mysql Db In Same Row
I can get files to upload to folder and add a new row for each in to a mysql db using the code below, how do I get all the filles in one row with multiple uploads
Code: [Select] //Check if the form was submitted. if(isset($_POST['uploadButton'])) { //Specify folder path where the file is going. $path = 'uploads/'; //Upload file one by one. foreach($_FILES['file']['name'] as $key => $val) { if($val != '') { $file_name = $_FILES['file']['name'][$key]; //Get file name. $file_tmp = $_FILES['file']['tmp_name'][$key]; //Get temporary file name. $file = $path . $file_name; mysql_query("INSERT INTO images (img1) VALUES('$file');") or trigger_error('Unable to INsert: ' . mysql_error()); //Move uploaded file if(move_uploaded_file($file_tmp, $file)) { echo 'File was succesfully uploaded to: ' . $file . '<br />'; } else { //Display error message if there was a problem uploading file. echo 'Error uploading file "' . $key . '."<br />'; } echo $target_path; } } } ?> Similar TutorialsHi, I am a newbie to php and am trying to copy mysql data to a text file. The format I need to create is In querying my database, I'm Selecting nameFirst and nameLast, and it produces a name like Joe Smith. I'm trying to match a photo with the name. Right now I'm uploading photos into a folder naming the file (e.g. SmithJoe.jpg). For reasons that involve writers being able to upload and access photos, I'm trying to use an image plugin. When uploading photos, it strips capital letters, so SmithJoe,jpg goes in as smithjoe.jpg, and it's not matching my database query. Here is the code I'm working with that works quite well with this one exception: $query = 'SELECT * FROM wp_playerRank'; $results = mysql_query($query); while($line = mysql_fetch_assoc($results)) { if ($line['wpID'] == $wp_tagID) { echo '<div class="player">'; // Here is the code that produces the image. I need to get rid of capital letters for ease of use echo '<div><img src="/wp-content/uploads/' . $line['nameLast'] . $line['nameFirst'] . '.jpg"></div>'; echo '<div class="playerData">' . $line['height'] . ' '; if ($line['position'] == 'PG') {echo 'Point Guard';} elseif ($line['position'] == 'SG') {echo 'Shooting Guard';} elseif ($line['position'] == 'SF') {echo 'Small Forward';} elseif ($line['position'] == 'PF') {echo 'Power Forward';} elseif ($line['position'] == 'C') {echo 'Center';} echo '</div>'; echo '<div class="playerData">' . $line['hschool'] . '</div>'; echo '<div class="playerData">' . $line['summer'] . '</div>'; echo '<div class="playerData">Class of ' .$line['year'] . '</div>'; if ($line['committed'] == 'y') { echo '<div> <br>Committed to <strong>'. $line['college'] . '</strong></div> ';} } } My Php Buddies, I have mysql tbl columns these:
id: Now, I want to display their row data by excluded a few columns. Want to exclude these columns: date_&_time account_activation_code account_activation_status id_verification_video_file_url password
So, the User's (eg. your's) homepage inside his account should display labels like these where labels match the column names but the underscores are removed and each words' first chars CAPITALISED:
Id: 1
For your convenience only PART 1 works. Need help on Part 2 My attempted code:
PART 1 <?php // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Query to get columns from table $query = $conn->query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'members' AND TABLE_NAME = 'users'"); while($row = $query->fetch_assoc()){ $result[] = $row; } // Array of all column names $columnArr = array_column($result, 'COLUMN_NAME'); foreach ($columnArr as $value) { echo "<b>$value</b>: ";?><br><?php } ?> PART 2 <?php //Display User Account Details echo "<h3>User: <a href=\"user.php?user=$user\">$user</a> Details</h3>";?><br> <?php $excluded_columns = array("date_&_time","account_activation_code","account_activation_status","id_verification_video_file_url","password"); foreach ($excluded_columns as $value2) { echo "Excluded Column: <b>$value2</b><br>"; } foreach ($columnArr as $value) { if($value != "$value2") { $label = str_replace("_"," ","$value"); $label = ucwords("$label"); //echo "<b>$label</b>: "; echo "$_SESSION[$value]";?><br><?php echo "<b>$label</b>: "; echo "${$value}";?><br><?php } } ?> PROBLEM: Columns from the excluded list still get displayed. Edited November 19, 2018 by phpsaneI was wondering how I would go about doing a sorting of a new element being added on the page. This element would have to be alphabetically sorted into the existing elements onto the page. For example: I am making a file manager, so when a user creates a new file, it would be sorted into the already existing files and displayed in the spot that it should.
All necessary details would be provided by PHP, so I would only need help with the JavaScript part.
Honestly, I have no clue how I would get around to doing that. I was thinking earlier that it would involve looping through each class of file_name and getting the text() value. Then add all of the values into an array and sorting it somehow. Then it would be getting the <tr> of which file_name is before it, and then append under it somehow.
I'm not asking for any free code, but I was wondering which (JavaScript/JQuery) functions I would be looking for. I was also wondering if the idea I had would be beneficial or not, or if there were any other ways. Here is how the files are displayed as is:
<?php // There may be undefined variables, this is only part of it $return = '<table id="manager" class="table table-bordered"> <thead> <tr class="table_header"> <th><input id="select" type="checkbox"></th> <th>Name</th> <th>Size</th> <th>Last Modified</th> <th>Type</th> <th>Permissions</th> <th></th> </tr> </thead> <tbody>'; $path = $_SERVER['DOCUMENT_ROOT']; // Scan the directory and remove the paths from the result $files = array_diff(scandir($path), array(".", "..")); // Get the number of files in the directory $num_files = count($files); // If there are no files in the directory, return the empty directory variable we defined earlier if($num_files == 0) return $empty_dir; $directory_array = array(); $file_array = array(); foreach($files as $file) { // Set the path correctly $file_path = $path."/".$file; // If the item is a directory if(is_dir($file_path)) $directory_array[] = $file; // The item is a file else $file_array[] = $file; } // Sort each of the arrays alphabetically sort($directory_array); sort($file_array); // Merge the directories and files into one array - directories shown first $files = array_merge($directory_array, $file_array); // Loop through the items foreach($files as $file) { $file_name = $file; // Set the path correctly $file = $path."/".$file; // Get the information for the file if(is_dir($file)) $file_size = "--"; else $file_size = @filesize($file); if($file_size === false) { $checkbox = '<input id="files_check" type="checkbox" name="files[]" value="'.htmlentities($file_name).'">'; $file_name = htmlentities($file_name). " - <b>Fatal Error Reading</b>"; $file_size = "--"; $last_modified = "--"; $type = "--"; $permissions = "--"; $actions = "--"; } else { $finfo = finfo_open(FILEINFO_MIME_TYPE); $checkbox = '<input id="files_check" type="checkbox" name="files[]" value="'.htmlentities($file_name).'">'; if(is_dir($file)) { $file_name = '<i class="icon-folder-open"></i> <a href="manager.php?path='.htmlentities($file_name).'/">'.htmlentities($file_name).'</a>'; } else { $file_name = '<i class="icon-file"></i> <a href="manager/view_contents.php?file=/'.htmlentities($file_name).'&token='.htmlentities($_SESSION['secure_token']).'">'.htmlentities($file_name).'</a>'; } $file_size = htmlentities(get_appropriate_size($file_size)); $last_modified = htmlentities(get_appropriate_date(filemtime($file))); $type = htmlentities(finfo_file($finfo, $file)); $permissions = htmlentities(substr(sprintf('%o', fileperms($file)), -4)); $actions = '<i class="actions"></i>'; } $return .= "<tr> <td>{$checkbox}</td> <td class='file_name'>{$file_name}</td> <td>{$file_size}</td> <td>{$last_modified}</td> <td>{$type}</td> <td class='permissions'>{$permissions}</td> <td class='action'>{$actions}</td> </tr>"; } $return .= '</tbody> </table>'; return $return; ?> guys, I have looked on google for this and apparently noone is doing it. I have 4 checkboxes and I want to send mail indicating which boxes were checked. the only code I've found is PHP that captures the *status* of the boxes, such as "on" or "off". I want to capture the names of the actual checkbox elements. Here is the code I'm currently testing (which just prints out "on" or "off" to indicate which boxes are checked): if(isset($_POST['checkboxes'])) { foreach($_POST['checkboxes'] as $selected){ echo $selected . "</br>"; } } else { echo "No Desired Contact Time Specified."; } if I check all 4 boxes for instance, I get this: on on on on any way to get the names? thanks! hmm im having some trouble tackling this problem i have a database table with topicname then 3 columns with 3 pdfs in each one all the files are stored in a directory called topicfiles in the server so like 3 topicnames with 3 files in each one with this page i want to make i want to display each topic name with the files under it calling it from the server like Code: [Select] topic 1 file1.pdf file2.pdf file3.pdf topic 2 file4.pdf file5.pdf file6.pdf topic 3 file71.pdf file8.pdf file9.pdf i tried using dhandler to access all files in the folder and only managed to display all of the files in rows using foreach loop was thinkin of using mysql query to access the topic name and then each file for that topic but not sure hmmm I need to add these lines to my .htaccess file via PHP Code: [Select] RewriteCond %{REQUEST_URI} checkout RewriteRule ^(.*)$ https://myurl.com/checkout/$1 [R,L] RIGHT after this line: Code: [Select] RewriteBase / AND before this line: Code: [Select] RewriteCond %{REQUEST_FILENAME} !-f This is how the current file looks w/o the new line addition: Code: [Select] RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)$ index.php [L,QSA] It needs to look like this when the new lines are added(extra line breaks not necessary): Code: [Select] RewriteBase / RewriteCond %{REQUEST_URI} checkout RewriteRule ^(.*)$ https://myurl.com/checkout/$1 [R,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)$ index.php [L,QSA] The line numbers may not match up, so I cannot use the line number. I have been developing applications for over 2 years now. In one of my domains I see some strange php files all created on 20th of April 2011 and named like this : IwA8ZSIhJ.php,QvDBnXYevm.php,LXgU1kf16y.php etc etc Any idea what could be the potential reason of creating such files in my hosting ? Thanks Sadan Masroor. This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=348587.0 Can anyone tell me, how the temporary file names (name of the file which is created in the 'tmp' dir ) generated by PHP when the files are uploaded ? Are there any algorithms used ? As you can see here I have the following code Code: [Select] <?php session_start(); session_register('hazard2'); //INITIALIZE ERROR VARIABLES $errorFound = false; $errorIcon['hazard2'] = ''; if (isset($_POST['submitbutton'])) { //SET SESSION VARIABLES $_SESSION['hazard2'] = $_POST['hazard2']; //TEST FORM INFORMATION if(count($_POST['hazard2']) != 3) { $errorFound = true; $errorIcon['hazard2'] = 'Error Question 2'; } //IF NO ERRORS WERE FOUND, CONTINUE PROCESSING if (!$errorFound) { header( "Location: hazardresult.php" ); } } ?> It's lazy I know, but the script is on a file called hazard2.php, is there anyway to have all of the hazard2's in the code come from the file name. So when I make hazard3, I don't have to change all the hazard2's to hazard3's Thank you I've got a script where the client can upload pictures. The pictures are then resized, thumbnailed, and added to the database. In the process I'm trying to search the database for a duplicate file name and create a new name if necessary: Code: [Select] $userfile = 'userfile' . $i; $tmpLoc = $_FILES[$userfile]['tmp_name']; $name = $_FILES[$userfile]['name']; $error = $_FILES[$userfile]['error']; $type = $_FILES[$userfile]['type']; $temp = 'album' . $i; $album = $_POST[$temp]; if($error > 0) { echo "Error on $name: "; switch ($error) { case 1: echo "File exceeded upload_max_filesize"; break; case 2: echo "File exceeded max_file_size"; break; case 3: echo 'File only partially uploaded'; break; case 4: echo 'No file uploaded'; break; } echo "</div>"; exit; } // Check for name duplicates and deal with $query = "SELECT * FROM pictures WHERE src = $name"; $result = mysql_query($query); if($result) $dup = true; while($dup) { echo "Duplicate file name $name <br />"; $ext; if($type == 'image/gif') $ext = '.gif'; else if($type == 'image/jpeg') $ext = '.jpg'; else if($type == 'image/png') $ext = '.png'; else die("Error: Unsupported file type"); $x = 0; $name = $x . $ext; echo "Checking $name <br />"; $query = "SELECT * FROM pictures WHERE src = $name"; $result = mysql_query($query); if(!$result) { $dup = false; echo "File successfully renamed to $name to avoid duplicate <br />"; } $x++; } I don't get any errors of any sort, it just never enters the loop Hello, I'm having some issues with PHP thinking that the variables that I send it are the actual columns in my database. First, I pull off Quadratic_Functions and introductory_problem from http://localhost:8888/algebra_book/Chapters/Quadratic_Functions/introductory_problem.php using the code below: Code: [Select] $chapter_page = $_SERVER['PHP_SELF']; $chapter_page_array = explode('/',$chapter_page); $size =count($chapter_page_array); $chapter = $chapter_page_array[$size-2]; $page = $chapter_page_array[$size-1]; $page_array = explode('.', $page); $page = $page_array[0]; Based on my printing of the variables $chapter and $page I think that it's doing what I want it to do. I then use the following function: Code: [Select] $supplemental_id = getSupplementalId($dbRead,$chapter,$page); to check out if the there's a supplemental_id for the Quadratic_Function chapter and introductory_problem page name via: Code: [Select] function getSupplementalId($read,$user_id,$chapter,$page) { $sql = "SELECT supplemental_id FROM instructors_supplemental WHERE page_name = $page AND chapter_name='$chapter"; return $read->fetchRow($sql); } If I stick in actual values, as seen below, the thing runs fine. Code: [Select] $sql = "SELECT supplemental_id FROM instructors_supplemental WHERE page_name = 'introductory_problem' AND chapter_name='Quadratic_Functions'"; But if I run it in the abstract version, with variables for page and chapter name (the first version), I get Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'introductory_problem' in 'where clause'' in... It's almost as if it thinks that my variables are the names of the columns. Any thoughts would be appreciated.... Hi. The idea: I want to pull a client record and simply place all the row columns into editable form field text boxes. Once the user reviews and edits a submit button will update the record. What I have: Code: [Select] $Query01 = "SELECT * FROM `CustomerSignups` WHERE `Id` = '$_GET[Id]'"; $Result01 = mysql_query($Query01) or die("Error 01: " . mysql_error()); while ($get_info = mysql_fetch_row($Result01)) { foreach ($get_info as $field) echo "<p>$field</p>"; It displays as expected, a line for each field. How can I get this to pull the field names also and then I can use those as text box input fields...? I need to update a particular table and there be a whole lot of field names. I'd like to do it without having to use them the same way you can access then like $row[12] after a "select" query. The standard for updating (at least how I write it) goes like this ... Code: [Select] $query = "UPDATE linguistics SET welcome1='$var3', welcome2='$var4' WHERE language = '$lengua'"; Well, I'd like to do it where I don't have to name welcome1 and welcome2, but instead refer to their numerical position within the database. On a "select" query we can do this. Can this be done on an update? Something perhaps like ... Code: [Select] $query = "UPDATE linguistics SET 3='$var3', 4='$var4' WHERE language = '$lengua'"; ... where 3 and 4 represent the 4th and 5th fields respectively. I know that this particular phrasing doesn't work because I've tried it, but surely there has to be something. This will save me LOTS of time. Thanks!! Hi all, This is my very first post here, so I will try and make it count Very recently I have been working with php and I found this simple little script that allows users to upload files. I tweaked some things to only make it upload .doc files but now I have a slight problem. Every time someone uploads a word file with the same name, it gets replaced. I tried looking for other examples here on the forum, but was unable to apply it to my own script. It would be a big help if someone could provide a simple add-on to this existing script. Thanks in advance. Script: <? $locatie="upload/"; $toegestaan = "doc"; $max_size = 1000000; set_time_limit(0); if(isset($_POST['upload'])) { if(is_uploaded_file($_FILES['bestand']['tmp_name'])) { $extensie_bestand = pathinfo($_FILES['bestand']['name']); $extensie_bestand = $extensie_bestand[extension]; $extensies_toegestaan = explode(", ", $toegestaan); for($i = 0; $i < count($extensies_toegestaan); $i++) { if($extensies_toegestaan[$i] == "$extensie_bestand") { $ok = 1; } } if($ok == 1) { if($_FILES['bestand']['size']>$max_size) { echo "Het bestand is te groot, de maximale grootte is: <b>$max_size</b>"; exit; } if(!move_uploaded_file($_FILES['bestand']['tmp_name'], $locatie.$_FILES['bestand']['name'])) { echo "het bestand kan niet worden verplaatst"; exit; } echo "Het bestand ".$_FILES['bestand']['name']." is geupload<br> <a href='".$locatie."".$_FILES['bestand']['name']."' </a>"; } else { echo "Verkeerde extentie, de toegestane extensies zijn: <b>$toegestaan</b>"; } } else { echo "Het uploaden is mislukt, probeer het opnieuw"; } } ?> <title>test tittle</title> <style type="text/css"> <!-- body { margin-top: 0px; } --> </style></head> <body> <table width="1216" height="1191" border="0" cellpadding="0" cellspacing="0" background="back"> <tr> <td height="317" colspan="2"> </td> </tr> <tr> <td height="381"> </td> <td><p> </p> <form method="post" action="<?=$_SERVER['PHP_SELF']?>" enctype="multipart/form-data"> <table width="398" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="180"> </td> <td width="218"><input type="file" name="bestand" /> <input type="submit" name="upload" value="uploaden" /></td> </tr> <tr> <td> </td> <td> </td> </tr> </table> </form></td> </tr> <tr> <td width="420"> </td> <td width="796"> </td> </tr> </table> I currently have php code that outputs information from my database, but how do i make it also display the name of the fields beside each entry of the database? heres my PHP code: Code: [Select] <?php $server = ""; // Enter your MYSQL server name/address between quotes $username = ""; // Your MYSQL username between quotes $password = ""; // Your MYSQL password between quotes $database = ""; // Your MYSQL database between quotes $con = mysql_connect($server, $username, $password); // Connect to the database if(!$con) { die('Could not connect: ' . mysql_error()); } // If connection failed, stop and display error mysql_select_db($database, $con); // Select database to use // Query database $result = mysql_query("SELECT * FROM Properties"); if (!$result) { echo "Error running query:<br>"; trigger_error(mysql_error()); } elseif(!mysql_num_rows($result)) { // no records found by query. echo "No records found"; } else { $i = 0; echo '<div style="font-family:helvetica; font-size:15px; padding-left:15px; padding-top:20px;">'; while($row = mysql_fetch_array($result)) { // Loop through results $i++; echo '<img class="image1" src="'. $row['images'] .'" />'; //image echo "Displaying record $i<br>\n"; echo "<b>" . $row['id'] . "</b><br>\n"; // Where 'id' is the column/field title in the database echo $row['Location'] . "<br>\n"; // Where 'location' is the column/field title in the database echo $row['Property_type'] . "<br>\n"; // as above echo $row['Number_of_bedrooms'] . "<br>\n"; // .. echo $row['Purchase_type'] . "<br>\n"; // .. echo $row['Price_range'] . "<br>\n"; // .. } echo '</div>'; } mysql_close($con); // Close the connection to the database after results, not before. ?> thanks in advance Hi
I come from a desktop (vb.net) background and have used oridinary text files for my databases. I use file locking to prevent other processes from writing to the same file simultaneously.
Now I am moving over the PHP/MySQL - what precautions should I take to stop a simultaneous processes from writing to a table at the same time.?
Do I need to lock the table before writing to it?
Does MySQL deal with this automatically and just block my process until the table becomes free?
(I am talking about a single table here, not multiple dependant tables - I know that is another issue)
Thanks
Nigel
I'm using a woocommerce order report plugin, some customers order multiple products but order report shows only number of order and one product name: I want to see all product names: also I want to see customer notes it doesn't show up
<?php /** * Plugin Name: Custom Order Report * Description: Generates a report on individual WooCommerce products sold during a specified time period. * Version: 1.4.8 */ // Add the Product Sales Report to the WordPress admin add_action('admin_menu', 'hm_psrf_admin_menu'); function hm_psrf_admin_menu() { add_submenu_page('woocommerce', 'Custom Order Report', 'Custom Order Report', 'view_woocommerce_reports', 'hm_sbpf', 'hm_sbpf_page'); } function hm_psrf_default_report_settings() { return array( 'report_time' => '30d', 'report_start' => date('Y-m-d', current_time('timestamp') - (86400 * 31)), 'report_end' => date('Y-m-d', current_time('timestamp') - 86400), 'order_statuses' => array('wc-processing', 'wc-on-hold', 'wc-completed'), 'products' => 'all', 'product_cats' => array(), 'product_ids' => '', 'variations' => 0, 'orderby' => 'quantity', 'orderdir' => 'desc', 'fields' => array('product_id', 'product_sku', 'product_name', 'quantity_sold', 'gross_sales'), 'limit_on' => 0, 'limit' => 10, 'include_header' => 1, 'exclude_free' => 0 ); } // This function generates the Product Sales Report page HTML function hm_sbpf_page() { $savedReportSettings = get_option('hm_psr_report_settings'); if (isset($_POST['op']) && $_POST['op'] == 'preset-del' && !empty($_POST['r']) && isset($savedReportSettings[$_POST['r']])) { unset($savedReportSettings[$_POST['r']]); update_option('hm_psr_report_settings', $savedReportSettings); $_POST['r'] = 0; echo('<script type="text/javascript">location.href = location.href;</script>'); } $reportSettings = (empty($savedReportSettings) ? hm_psrf_default_report_settings() : array_merge(hm_psrf_default_report_settings(), $savedReportSettings[ isset($_POST['r']) && isset($savedReportSettings[$_POST['r']]) ? $_POST['r'] : 0 ] )); // For backwards compatibility with pre-1.4 versions if (!empty($reportSettings['cat'])) { $reportSettings['products'] = 'cats'; $reportSettings['product_cats'] = array($reportSettings['cat']); } $fieldOptions = array( 'order_id' => 'Order ID', /*'product_id' => 'Product ID',*/ 'customer_name' => 'Customer Name', /*'variation_id' => 'Variation ID',*/ 'city' => 'City', 'address' => 'Address', 'product_name' => 'Product Name', 'quantity_sold' => 'Quantity Sold', /*'product_sku' => 'Product SKU',*/ 'gross_sales' => 'Gross Sales', 'product_categories' => 'Schools', /*'variation_attributes' => 'Variation Attributes',*/ /*'gross_after_discount' => 'Gross Sales (After Discounts)'*/ 'ceremony_date' => 'Ceremony Date', 'ceremony_time' => 'Ceremony Time', ); include(dirname(__FILE__).'/admin.php'); } // Hook into WordPress init; this function performs report generation when // the admin form is submitted add_action('init', 'hm_sbpf_on_init', 9999); function hm_sbpf_on_init() { global $pagenow; // Check if we are in admin and on the report page if (!is_admin()) return; if ($pagenow == 'admin.php' && isset($_GET['page']) && $_GET['page'] == 'hm_sbpf' && !empty($_POST['hm_sbp_do_export'])) { // Verify the nonce check_admin_referer('hm_sbpf_do_export'); $newSettings = array_intersect_key($_POST, hm_psrf_default_report_settings()); foreach ($newSettings as $key => $value) if (!is_array($value)) $newSettings[$key] = htmlspecialchars($value); // Update the saved report settings $savedReportSettings = get_option('hm_psr_report_settings'); $savedReportSettings[0] = array_merge(hm_psrf_default_report_settings(), $newSettings); update_option('hm_psr_report_settings', $savedReportSettings); // Check if no fields are selected or if not downloading if (empty($_POST['fields']) || empty($_POST['hm_sbp_download'])) return; // Assemble the filename for the report download $filename = 'Product Sales - '; if (!empty($_POST['cat']) && is_numeric($_POST['cat'])) { $cat = get_term($_POST['cat'], 'product_cat'); if (!empty($cat->name)) $filename .= addslashes(html_entity_decode($cat->name)).' - '; } $filename .= date('Y-m-d', current_time('timestamp')).'.csv'; // Send headers header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename="'.$filename.'"'); // Output the report header row (if applicable) and body $stdout = fopen('php://output', 'w'); if (!empty($_POST['include_header'])) hm_sbpf_export_header($stdout); hm_sbpf_export_body($stdout); exit; } } // This function outputs the report header row function hm_sbpf_export_header($dest, $return=false) { $header = array(); foreach ($_POST['fields'] as $field) { switch ($field) { case 'order_id': $header[] = 'Order ID'; break; case 'product_name': $header[] = 'Product Name'; break; case 'quantity_sold': $header[] = 'Quantity Sold'; break; case 'gross_sales': $header[] = 'Gross Sales'; break; case 'product_categories': $header[] = 'Schools'; break; case 'customer_name': $header[] = 'Customer Name'; break; case 'city': $header[] = 'City'; break; case 'address': $header[] = 'Address'; break; case 'ceremony_date': $header[] = 'Ceremony Date'; break; case 'ceremony_time': $header[] = 'Ceremony Time'; break; } } if ($return) return $header; fputcsv($dest, $header); } // This function generates and outputs the report body rows function hm_sbpf_export_body($dest, $return=false) { global $woocommerce, $wpdb; $product_ids = array(); if ($_POST['products'] == 'cats') { $cats = array(); foreach ($_POST['product_cats'] as $cat) if (is_numeric($cat)) $cats[] = $cat; $product_ids = get_objects_in_term($cats, 'product_cat'); } else if ($_POST['products'] == 'ids') { foreach (explode(',', $_POST['product_ids']) as $productId) { $productId = trim($productId); if (is_numeric($productId)) $product_ids[] = $productId; } } // Calculate report start and end dates (timestamps) switch ($_POST['report_time']) { case '0d': $end_date = strtotime('midnight', current_time('timestamp')); $start_date = $end_date; break; case '1d': $end_date = strtotime('midnight', current_time('timestamp')) - 86400; $start_date = $end_date; break; case '7d': $end_date = strtotime('midnight', current_time('timestamp')) - 86400; $start_date = $end_date - (86400 * 6); break; case '1cm': $start_date = strtotime(date('Y-m', current_time('timestamp')).'-01 midnight -1month'); $end_date = strtotime('+1month', $start_date) - 86400; break; case '0cm': $start_date = strtotime(date('Y-m', current_time('timestamp')).'-01 midnight'); $end_date = strtotime('+1month', $start_date) - 86400; break; case '+1cm': $start_date = strtotime(date('Y-m', current_time('timestamp')).'-01 midnight +1month'); $end_date = strtotime('+1month', $start_date) - 86400; break; case '+7d': $start_date = strtotime('midnight', current_time('timestamp')) + 86400; $end_date = $start_date + (86400 * 6); break; case '+30d': $start_date = strtotime('midnight', current_time('timestamp')) + 86400; $end_date = $start_date + (86400 * 29); break; case 'custom': $end_date = strtotime('midnight', strtotime($_POST['report_end'])); $start_date = strtotime('midnight', strtotime($_POST['report_start'])); break; default: // 30 days is the default $end_date = strtotime('midnight', current_time('timestamp')) - 86400; $start_date = $end_date - (86400 * 29); } // Assemble order by string $orderby = (in_array($_POST['orderby'], array('product_id', 'gross', 'gross_after_discount')) ? $_POST['orderby'] : 'quantity'); $orderby .= ' '.($_POST['orderdir'] == 'asc' ? 'ASC' : 'DESC'); // Create a new WC_Admin_Report object include_once($woocommerce->plugin_path().'/includes/admin/reports/class-wc-admin-report.php'); $wc_report = new WC_Admin_Report(); $wc_report->start_date = $start_date; $wc_report->end_date = $end_date; //echo(date('Y-m-d', $end_date)); $where_meta = array(); if ($_POST['products'] != 'all') { $where_meta[] = array( 'type' => 'order_item_meta', 'meta_key' => '_product_id', 'operator' => 'in', 'meta_value' => $product_ids ); } if (!empty($_POST['exclude_free'])) { $where_meta[] = array( 'meta_key' => '_line_total', 'meta_value' => 0, 'operator' => '!=', 'type' => 'order_item_meta' ); } // Get report data // Avoid max join size error $wpdb->query('SET SQL_BIG_SELECTS=1'); // Prevent plugins from overriding the order status filter add_filter('woocommerce_reports_order_statuses', 'hm_psrf_report_order_statuses', 9999); // Based on woocoommerce/includes/admin/reports/class-wc-report-sales-by-product.php $sold_products = $wc_report->get_order_report_data(array( 'data' => array( '_product_id' => array( 'type' => 'order_item_meta', 'order_item_type' => 'line_item', 'function' => '', 'name' => 'product_id' ), '_qty' => array( 'type' => 'order_item_meta', 'order_item_type' => 'line_item', 'function' => 'SUM', 'name' => 'quantity' ), '_line_subtotal' => array( 'type' => 'order_item_meta', 'order_item_type' => 'line_item', 'function' => 'SUM', 'name' => 'gross' ), '_line_total' => array( 'type' => 'order_item_meta', 'order_item_type' => 'line_item', 'function' => 'SUM', 'name' => 'gross_after_discount' ), /*usama*/ 'order_id' => array( 'type' => 'order_item', 'order_item_type' => 'line_item', 'function' => '', 'name' => 'order_id' ) /*usama*/ ), 'query_type' => 'get_results', 'group_by' => 'order_id', 'where_meta' => $where_meta, 'order_by' => $orderby, 'limit' => (!empty($_POST['limit_on']) && is_numeric($_POST['limit']) ? $_POST['limit'] : ''), 'filter_range' => ($_POST['report_time'] != 'all'), 'order_types' => wc_get_order_types('order_count'), 'order_status' => hm_psrf_report_order_statuses() )); // Remove report order statuses filter remove_filter('woocommerce_reports_order_statuses', 'hm_psrf_report_order_statuses', 9999); if ($return) $rows = array(); // Output report rows foreach ($sold_products as $product) { $row = array(); /*usama*/ $order = wc_get_order($product->order_id); $customerName = $order->get_billing_first_name().' '.$order->get_billing_last_name(); $billingCity = $order->get_billing_city(); $billingAddress1 = $order->get_billing_address_1(); //echo $product->order_id; //echo $customerName.$city.$billingAddress1; //echo '<pre>';print_r($order);exit; /*usama*/ foreach ($_POST['fields'] as $field) { switch ($field) { case 'order_id': $row[] = $product->order_id; break; case 'product_name': $row[] = html_entity_decode(get_the_title($product->product_id)); break; case 'quantity_sold': $row[] = $product->quantity; break; case 'gross_sales': $row[] = $product->gross; break; /*case 'variation_id': $row[] = (empty($product->variation_id) ? '' : $product->variation_id); break; case 'product_sku': $row[] = get_post_meta($product->product_id, '_sku', true); break;*/ case 'product_categories': $terms = get_the_terms($product->product_id, 'product_cat'); if (empty($terms)) { $row[] = ''; } else { $categories = array(); foreach ($terms as $term) $categories[] = $term->name; $row[] = implode(', ', $categories); } break; case 'customer_name': $row[] = $customerName; break; case 'city': $row[] = $billingCity; break; case 'address': $row[] = $billingAddress1; break; /*case 'gross_after_discount': $row[] = $product->gross_after_discount; break;*/ /*usama*/ case 'ceremony_date': $row[] = $order->get_meta( '_billing_myfield12', true ); break; case 'ceremony_time': $row[] = $order->get_meta( '_billing_myfield13', true ); break; } } if ($return) $rows[] = $row; else fputcsv($dest, $row); } if ($return) return $rows; } add_action('admin_enqueue_scripts', 'hm_psrf_admin_enqueue_scripts'); function hm_psrf_admin_enqueue_scripts() { wp_enqueue_style('hm_psrf_admin_style', plugins_url('css/hm-product-sales-report.css', __FILE__)); wp_enqueue_style('pikaday', plugins_url('css/pikaday.css', __FILE__)); wp_enqueue_script('moment', plugins_url('js/moment.min.js', __FILE__)); wp_enqueue_script('pikaday', plugins_url('js/pikaday.js', __FILE__)); } // Schedulable email report hook add_filter('pp_wc_get_schedulable_email_reports', 'hm_psrf_add_schedulable_email_reports'); function hm_psrf_add_schedulable_email_reports($reports) { $reports['hm_psr'] = array( 'name' => 'Product Sales Report', 'callback' => 'hm_psrf_run_scheduled_report', 'reports' => array( 'last' => 'Last used settings' ) ); return $reports; } function hm_psrf_run_scheduled_report($reportId, $start, $end, $args=array(), $output=false) { $savedReportSettings = get_option('hm_psr_report_settings'); if (!isset($savedReportSettings[0])) return false; $prevPost = $_POST; $_POST = $savedReportSettings[0]; $_POST['report_time'] = 'custom'; $_POST['report_start'] = date('Y-m-d', $start); $_POST['report_end'] = date('Y-m-d', $end); $_POST = array_merge($_POST, array_intersect_key($args, $_POST)); if ($output) { echo('<table><thead><tr>'); foreach (hm_sbpf_export_header(null, true) as $heading) { echo("<th>$heading</th>"); } echo('</tr></thead><tbody>'); foreach (hm_sbpf_export_body(null, true) as $row) { echo('<tr>'); foreach ($row as $cell) echo('<td>'.htmlspecialchars($cell).'</td>'); echo('</tr>'); } echo('</tbody></table>'); $_POST = $prevPost; return; } $filename = get_temp_dir().'/Product Sales Report.csv'; $out = fopen($filename, 'w'); if (!empty($_POST['include_header'])) hm_sbpf_export_header($out); hm_sbpf_export_body($out); fclose($out); $_POST = $prevPost; return $filename; } function hm_psrf_report_order_statuses() { $wcOrderStatuses = wc_get_order_statuses(); $orderStatuses = array(); if (!empty($_POST['order_statuses'])) { foreach ($_POST['order_statuses'] as $orderStatus) { if (isset($wcOrderStatuses[$orderStatus])) $orderStatuses[] = substr($orderStatus, 3); } } return $orderStatuses; } /* Review/donate notice */ register_activation_hook(__FILE__, 'hm_psrf_first_activate'); function hm_psrf_first_activate() { $pre = 'hm_psr'; $firstActivate = get_option($pre.'_first_activate'); if (empty($firstActivate)) { update_option($pre.'_first_activate', time()); } } if (is_admin() && get_option('hm_psr_rd_notice_hidden') != 1 && time() - get_option('hm_psr_first_activate') >= (14*86400)) { add_action('admin_notices', 'hm_psrf_rd_notice'); add_action('wp_ajax_hm_psrf_rd_notice_hide', 'hm_psrf_rd_notice_hide'); } function hm_psrf_rd_notice() { $pre = 'hm_psr'; $slug = 'product-sales-report-for-woocommerce'; echo(' <div id="'.$pre.'_rd_notice" class="updated notice is-dismissible"><p>Do you use the <strong>Product Sales Report</strong> plugin? Please support our free plugin by <a href="" target="_blank">making a donation</a>!product-sales-report-for-woocommerce Thanks!</p></div> <script>jQuery(document).ready(function($){$(\'#'.$pre.'_rd_notice\').on(\'click\', \'.notice-dismiss\', function(){jQuery.post(ajaxurl, {action:\'hm_psrf_rd_notice_hide\'})});});</script> '); } function hm_psrf_rd_notice_hide() { $pre = 'hm_psr'; update_option($pre.'_rd_notice_hidden', 1); } ?>
I am using a script I adapted from a tutorial to print the contents of a text box to a txt file. Basically, it's a really simple way of seeing who has logged in. I only have a handful of users. The problem is, although the text file is being created in the proper folder, it isn't being written to and just remains blank. <div align="center"> <table width="300" border="2" bordercolor="#FFFFFF" style="-moz-border-radius: 18px; -webkit-border-radius: 18px;" height="120" cellpadding="0" cellspacing="0"> <tr> <form name="form1" method="post" action="checklogin.php"> <td> <table width="100%" border="0" cellpadding="3" cellspacing="1" background="images/loginbg.jpg" style="-moz-border-radius: 15px; -webkit-border-radius: 15px;"> <tr align="center"> <td colspan="3"><font color="#FFFFFF"><strong>Family Login </strong></font></td> </tr> <tr> <td width="78"><font color="#000000">Username</font></td> <td width="6">:</td> <td width="294"><input name="myusername" type="text" id="myusername"> <?php $myusername = $_POST['myusername']; $data = "$myusername\n"; //open the file and choose the mode $fh = fopen("logs/login.txt", "a"); fwrite($fh, $data); fclose($fh); ?></td> </tr> <tr> <td><font color="#000000">Password</font></td> <td>:</td> <td><input name="mypassword" type="password" id="mypassword"></td> </tr> <tr> <td> </td> <td> </td> <td><input type="submit" name="Submit" value="Login"> </td> </tr> </table> </td> </form> </tr> </table> </div> I'm not sure what's going wrong but I'm guessing it's the placing of the php, or at least some of it. I'd quite like to add the time they logged in as well. Any idea's anyone? |