My project requires external CSV files to be uploaded to a database every week and required outputs are extracted whenever required. Currently am using the below to browse through a HTML form and upload to the table. It works fine!
if(isset($_POST['submit']))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file,"r");
while(($fileop = fgetcsv($handle,1000,",")) !==false)
{
$placement_name = $fileop[2];
$statistics_date = $fileop[0];
$impressions = $fileop[5];
$clicks = $fileop[6];
$sql = mysql_query("INSERT INTO 'table'(source,advertiser,campaign,placement_name,statistics_date,impressions,clicks) VALUES ('xxx','yyy','zzz','$placement_name','$statistics_date','$impressions',' $clicks')");}
But now, we might need to do this on a daily basis and automated (which we hope to do with scheduled cron jobs), so decision was to use LOAD DATA LOCAL INFILE. As you could see the values inserted for source, advertiser and campaign are custom ones. How could we use the LOAD DATA... instead of the browse function?
Related
I'm working on project for creating Online Exam for college Entrance. I am looking for solution to upload image and create folder using user serial id as which is as per mysql database primary increment idsave the images inside the folder.
Here is my solution where images are uploaded in already created folder called uploads. How to modify this for what I required.
<?php
session_start();
include('../connect.php');
$a = $_POST['name'];
// query
$file_name = strtolower($_FILES['file']['name']);
$file_ext = substr($file_name, strrpos($file_name, '.'));
$prefix = 'your_site_name_'.md5(time()*rand(1, 9999));
$file_name_new = $prefix.$file_ext;
$path = '../uploads/'.$file_name_new;
/* check if the file uploaded successfully */
if(#move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
//do your write to the database filename and other details
$sql = "INSERT INTO student (name,file) VALUES (:a,:h)";
$q = $db->prepare($sql);
$q->execute(array(':a'=>$a,':h'=>$file_name_new));
header("location: students.php");
}
?>
First: Be careful uploading files without correctly checking it's types;
Second: As Sean mentioned, this approach may get out of control.
--
The following example changed the steps that you tried.
First insert the user to get it's ID and then create the folder under '../uploads' with it.
This way you do not need to move the file two times (move the file to ../uploads, insert the user and then move the file again to ../uploads/userID)
<?php
...
$sql = "INSERT INTO student (name,file) VALUES (:a,:h)";
$q = $db->prepare($sql);
$q->execute(array(':a'=>$a,':h'=>$file_name_new));
// Get user id
$studentId = $db->lastInsertId();
// Create path with new userId just inserted
$path = "../uploads/$studentId/";
if(!file_exists($path)) { // maybe "&& !is_dir($path)" ?
// IMPORTANT NOTE: the second argument is the permission of the folder. 0777 is the default and may cause security flaws
mkdir($path, 0777, true);
}
// Move the uploaded file to new path with the userId
#move_uploaded_file($_FILES['file']['tmp_name'], $path.$file_name_new);
I think you need to check if the user already exists before inserting (but I don't know the details of your project)
I’m working on a page that keeps record of all the data and documents of employees in a company, part of its function is generating ID cards, which is the part i’m struggling with.
I downloaded the PHP Word by first installing the composer and using it to install the PHPWord library in the root of the project (where the php pages are) and it installed the following files and folder:
-composer.lock
-composer.json
-vendor (this one is a folder containing all the library)
“vendor” subfolders and files:
-autoload.php
-composer (folder)
-pclzip (folder)
-phpoffice (folder)
-zendframework (folder)
I assumed that was all there was to do for it to be installed so I proceeded to add the code, the problem is that it doesn’t work… here’s the code, i added comments to explain further:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
require_once 'conector_superadmin.php';
$link = connect($conn);
//Retrieving the id number sent via url to get the employee number
$idSelectedEmployee = $_GET['SelectedEmployee'];
//Data taken from small form with extra information for the ID Card
$idType = $_POST['idType'];
$ValidFrom = $_POST['ValidFrom'];
$ExpiresOn = $_POST['ExpiresOn'];
//Retrieving employee's information from "employees" table in db
$sql = "SELECT * FROM employees WHERE idEmployee = '$idSelectedEmployee'";
$result = mysqli_query($link, $sql);
while($row = mysqli_fetch_array($result)){
$FullName = $row['FullName'];
$Position = $row['Position'];
$EmployeeNum = $row['EmployeeNum'];
$BloodType = $row['BloodType'];
$Alergies = $row['Alergies'];
$PhoneNum = $row['PhoneNum'];
}
//The company uses two kinds of id cards, so i use these conditionals to get the type from a “select” field, it does work, i tested it
if($idType == "Plastic"){
//This code inside however is what isn’t working at all, it won't do anything despite taking this code from their template
include_once 'Sample_Header.php';
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('IDCards/Templates/ID_TEST.docx');
//I am using in the docx file the “${Variable}” format as the template and other documentation explains
$templateProcessor->setValue('EmployeeName', $FullName);
$templateProcessor->setValue('PhoneNum', $PhoneNum);
$templateProcessor->setValue('BloodType', $BloodType);
$templateProcessor->setValue('Alergies', $Alergies);
$templateProcessor->setValue('EmployeeNum', $EmployeeNum);
$templateProcessor->setValue('Position', $Position);
$templateProcessor->setValue('ValidFrom', $ValidFrom);
$templateProcessor->setValue('ExpiresOn', $ExpiresOn);
$templateProcessor->saveAs('IDCards/PlasticID.docx');
}
if($idType == "Paper"){
//Still empty
}
//I created this table to insert the data taken from the “employees’ table, just for the purpose of testing if all the information was retrieved correctly, needless to say, it works fine
$CredencialQuery = "INSERT INTO `idCards` (`idID`, `FullName`, `PhoneNum`, `BloodType`, `Alergies`, `EmployeeNum`, `Position`, `ValidFrom`, `ExpiresOn`, `idType`) VALUES (NULL, '$FullName', '$PhoneNum', '$BloodType', '$Alergies', '$EmployeeNum', '$Position', '$ValidFrom', '$ExpiresOn', '$idType');";
mysqli_query($link, $CredencialQuery);
}
?>
So yeah I realized the problem itself might be the PHPWord code, either something in my code is wrong or the library is not properly installed, i tried to run the php template itself to test if that one worked but it doesn’t work either
I am working on a CRM, on uploading a file in one upload form. Is it possible to get that file name inside choose file in another form without clicking the choose file option?
This is the code for selecting file in one form.
if ($_FILES['product_image']['name']!='') {
$target = "file_upload_source/";
$target1 =$target . #date(U)."_".( $_FILES['product_image']['name']);
$product_image=#date(U)."_".( $_FILES['product_image']['name']);
move_uploaded_file($_FILES['product_image']['tmp_name'], $target1);
$getlead_id1 = $_GET['leadid'];
// $appa = explode("_",$getlead_id1);
$data = explode("_",$getlead_id1);
$lead_id545=$data[0];
$type464 = $data[1];
$sl= "
INSERT INTO dizypro_file_order
SET lead_id = '$lead_id545',
description = '$description',
name = '$product_image',
type = '$type464',
upld_date = now(),
maker_date = now(),
maker_id = '".$_SESSION['ADMIN_GAME_ID']."',
divn_id = '".$_SESSION['SESS_Division']."',
comp_id = '".$_SESSION['SESS_COMPANY']."',
zone_id = '".$_SESSION['SESS_zone']."',
brnh_id = '".$_SESSION['SESS_Branch']."'
";
mysql_query($sl);
If I understand the question correctly, you want set the contents of a filefield to a predefined filename when you send a form. Every major browser will not let you do that, on security grounds. An unscrupulous site could display a filefield where the user can't see it, select the name of any file on your computer, put trick the user into uploading that file.
Short summary: Not possible!
Community,
I am currently working on a report builder. The objective of the report builder is to send out an email with an excel document with weekly information coming from an sql table. It is activated when the first person logs in for the day on Monday. If Monday is a holiday, and no one logs in that day, a timestamp will not be made in the database. When the user logs in Tuesday, it looks at the last timestamp to see if one was placed for the previous day. if not, it will fire on tuesday.
The first step in this process looks like this...
$today = cal_to_jd(CAL_GREGORIAN,date("m"),date("d"),date("Y"));
$yesterday = date('Y-m-d', strtotime($date .' -1 day'));
$holiday = false;
if(jddayofweek($today,1) == 'Tuesday')
{
if(mysql_num_rows(mysql_query("select report_date from report_builder where report_date = '{$yesterday}'")) == 0)
{
$holiday = true;
}
}
if(jddayofweek($today,1) == 'Monday' || $holiday === true)
{
$today = mysql_query("select report_date from report_builder where report_date = CURDATE()");
if(mysql_num_rows($today) == 0)
{
$date = date('Y-m-d H:i:s',time()-(7*86400));
mysql_query("INSERT into report_builder (report_date) VALUES (CURDATE())");
//More code here
**The question for this particular post is as follows:
Is it possible to send the information to a csv file that does not actually open so the user can see, but instead be saved to a temporary file? Can this be done in a way where it doesn't send the background html?**
Once this is accomplished, I wanted to send the file to a user using my current code that looks like this...
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->From = "**********";
$mail->AddAddress("*************");
$mail->Subject = "Test";
$mail->Body = "HI";
$fileName = $_FILES['file']['name'];
$tmpName = $_FILES['file']['tmp_name'];
$fileName = addslashes($fileName);
echo $fileName;
$mail->AddAttachment("temporary file path");
if(!$mail->Send())
{
echo 'Message was not sent.';
echo 'Mailer error:'.$mail->ErrorInfo;
}
Yes you can certainly write a files to disk and save it in any number of ways. I will however point you to something that might be a quick way to save some steps (i.e. not have to create a file in PHP) if you application server and your MySQL are on the same physical host. This is of course assuming that a CSV file would be suitable (i.e. you don't actually need to use a PHP Excel library to build an XLS or XLSX file)
SELECT [fields] INTO OUTFILE '/path/to/file'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM your_table;
This will directly create a CSV at location path/to/file on the machine which can then be sent via PHP. Please note that the file name must not be an existing file name as this approach will not allow you to overwrite an existing file.
If your MySQL host is remote or you need to manipualte the data before writing to file, I would suggest looking at fputcsv() (http://php.net/manual/en/function.fputcsv.php) in order to write the data from your query directly to a file in CSV format.
$file = fopen('/path/to/file.csv', 'w');
while ($row = [YOUR DATABASE FETCH HERE]) {
fputcsv($file, $row);
}
I am trying to create a php script that will be run by a cron job on a nightly basis.
The database holds entries from a contact form.
The idea is to run the php script (via cron) and have it export any new entries from the database from that day into a csv file on the server, overwriting that file each time for housekeeping. It needs to only export the entries to the database from that day.
Here is what I have at the moment:
<?php
// Connect and query the database for the users
$conn = new PDO("mysql:host=localhost;dbname=dbname", 'username', 'password');
$sql = "SELECT * FROM enquiries ORDER BY firstname";
$results = $conn->query($sql);
// Pick a filename and destination directory for the file
// Remember that the folder where you want to write the file has to be writable
//$filename = "/tmp/db_user_export_".time().".csv";
$filename = "/home/domain/public_html/csv/db_user_export.csv";
// Actually create the file
// The w+ parameter will wipe out and overwrite any existing file with the same name
$handle = fopen($filename, 'wb');
// Write the spreadsheet column titles / labels
fputcsv($handle, array('FirstName','Email'));
// Write all the user records to the spreadsheet
foreach($results as $row)
{
fputcsv($handle, array($row['firstname'], $row['email']));
}
// Finish writing the file
fclose($handle);
?>
Your sql must by:
SELECT * FROM enquiries where DATE(DateField) = CURDATE() ORDER BY firstname