i m try to use uniqid() to genrate the uniqname of the file and send it to the sql db by spliting seprate comma like('pic.jpg','pic1.jpg','pic2.jpg')
in place of pic i need a uniq name each and every time at the time of uploading of the file,i store all uploaded file into a folder and send the path of the image to the sql
<?php
if (isset($_POST['btnSubmit'])) {
$rep=$_FILES['files']['name'];
for ($i = 0; $i < count($rep); $i++) {
if ($_FILES["files"]["size"][$i] < 1000000) { // Check File size (Allow 1MB)
$nam=$_FILES["files"]["name"][$i];
// $nm = $_FILES["files"]["name"];
$album_cat = "";
$l = 0;
foreach ($rep as $album_cat1) {
$album_cat .= $album_cat1 . ",";
$l++;
}
$_POST['$album_cat'] = $album_cat;
$_POST['$album_cat_count'] = $l;
$temp = $_FILES["files"]["tmp_name"][$i];
$name = pathinfo($nam);
$profile = "group_images/" . uniqid() . '.' . $name['extension'];
if (empty($temp)) {
break;
}
if ($i == 0) {
$err = "File uploaded successfully";
$cls = "success";
}
$groupalbum = "UPDATE group_master SET group_photo='".$_POST['$album_cat']."' WHERE group_id='4'";
//$groupalbum = "UPDATE group_master SET group_photo='$profile' WHERE group_id='4'";
if ($conn->query($groupalbum) === TRUE) {
} else
echo "Error updating record: " . $conn->error;
move_uploaded_file($temp, $profile);
}
else {
$err = "File size is more than 1MB";
$cls = "danger";
}
}
}
?>
When I need an uniqid for a set of elements, I usually call uniqid() only once and after that I use an index (just for optimizing the speed of the script). So, you can call uniqid() before the for declaration:
$rep=$_FILES['files']['name'];
$uniqid = uniqid();
for ($i = 0; $i < count($rep); $i++) {
and then use $i as a suffix for your files
$profile = "group_images/".$uniqid.'-'.$i.'.'.$name['extension'];
On the other hand, you are calling move_uploaded_file($temp, $profile); only if your sql fails.
if ($conn->query($groupalbum) === TRUE) {
} else
echo "Error updating record: " . $conn->error;
move_uploaded_file($temp, $profile);
}
Are you sure that the logic is correct? Don't you need something like:
if ($conn->query($groupalbum) === TRUE) {
if (move_uploaded_file($temp, $profile)) {
// file has been uploaded successfully
} else {
// error in file upload process
}
} else
echo "Error updating record: " . $conn->error;
}
And the final point, your code is open for sql injection
$groupalbum = "UPDATE group_master SET group_photo='".$_POST['$album_cat']."' WHERE group_id='4'";
You should not use $_POST values directly into sql statements.
I have been Trying to check if selected row is last in MYSQL data records, if it is last then go back to first record.
Here is what I have done so far:
$fps = #fopen('number.txt', "r+");
$somay = fread($fps, filesize('number.txt'));
fclose($fps);
$num = ($somay+1);
$file = "number.txt";
$fh = fopen($file,'w+') or die("cant open file");
fwrite($fh,$num);
fclose($fh);
$sql = "SELECT #last_id := MAX(id),token FROM `token` where `id` = '".$somay."'";
if (!$result = $mysqli->query($sql)) {
echo "Sorry, the website is experiencing problems.";
echo "Error: Our query failed to execute and here is why: \n";
echo "Query: " . $sql . "\n";
echo "Errno: " . $mysqli->errno . "\n";
echo "Error: " . $mysqli->error . "\n";
exit;
}
if ($result->num_rows === 0) {
echo "We could not find a match for ID, sorry about that. Please try again.";
exit;
}
while ($tokennek = $result->fetch_assoc()) {
$token = $tokennek[token];
$tokenid = $tokennek[last_id];
}
if($somay == $tokenid){
$file = "number.txt";
$fh = fopen($file,'w+') or die("cant open file");
fwrite($fh,1);
fclose($fh);
}
Let me make it more clear here what I am doing is saving a file named number.txt to keep record of token which is already been used and go to next token/row.
I got a very annoying problem at the moment. I try to create a CSV upload that writes to a MySQL database. The system works, but only when i got 1 row. When I got more rows, the error "Column count doesn't match value count at row 1" shows up.
Here's my php code:
DEFINE('DB_HOST', 'localhost'); // Server naam
DEFINE('DB_USERNAME', 'root'); // Gebruikersnaam
DEFINE('DB_PASSWORD', 'root'); // Wachtwoord
DEFINE('DB_DATABASE', 'wp3'); // Database naam
// Initialisatie
$databasetable = "users";
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = "backups/compleet.csv";
$output = "";
// Database connection
$con = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
mysqli_set_charset($con, "utf8");
if (mysqli_connect_errno())
{
die('Service kan niet geladen worden.');
}
// Perform checks with CSV file
if(!file_exists($csvfile))
{
echo "File not found. Make sure you specified the correct path.\n";
exit;
}
$file = fopen($csvfile, "r");
if(!$file)
{
echo "Error opening data file.\n";
exit;
}
$size = filesize($csvfile);
if(!$size)
{
echo "File is empty.\n";
exit;
}
// Get content from CSV file
$csvcontent = fread($file, $size);
fclose($file);
// Initialize CSV file variables
$lines = 0;
$queries = "";
$linearray = array();
// Read each line from CSV file, clean data and put data in database
foreach(explode($lineseparator, $csvcontent) as $line)
{
$lines++;
$line = trim($line, " \t");
$line = str_replace("\r", "", $line);
$line = str_replace("'", "\'", $line);
$linearray = explode($fieldseparator, $line);
$linemysql = implode("','", $linearray);
$query = "INSERT INTO $databasetable VALUES('', '$linemysql')";
// $queries .= $query . "\n";
if (!mysqli_query($con, $query))
{
echo 'Fout: ' . $sql . '<br>' . mysqli_error($con);
}
}
// Read all the rows from the table and print to screen
$sql = "SELECT * FROM $databasetable";
$result = mysqli_query($con, $sql);
$columns_total = mysqli_num_fields($result);
while ($row = mysqli_fetch_array($result))
{
for ($i=0; $i<$columns_total; $i++)
{
$output .= $row["$i"] . ', ';
}
$output .= '<br>';
}
echo "<p>Er zijn $lines regels aan de tabel toegevoegd.</p>";
echo "<p>De database bevat nu de volgende data:<br>$output</p>";
And here is my csv file:
id,username,password,firstname,lastname,permissions,image,thumb,header
3,Frank,password,Frank,VanDeursen,author,frankImg.jpg,frankImg.jpg,tropical.jpg
4,Kevin,password,Kef,Borgh,author,kev.jpg,kev.jpg,ocean.jpg
Thank for the help!
David, password, david, backname, author, stock.jpg, image.jpg, stock.jpg
Frank, password, frank, backname, admin, stock,jpg, image,jpg, stock,jpg
Your csv file has more columns in the second row check carefully stock,jpg, image,jpg, stock,jpg all having comma's instead of dots!
I'm importing my csv fine now except one thing, how do i get the import to ignore the data in the first row? Employees will be uploading the same format which has the column names in that first row.
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File " . $_FILES['filename']['name'] . " uploaded successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['filename']['tmp_name']);
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import = "INSERT into tictoc(employee,taskname,tasktime,sessiontime,sessionstart,sessionend,sessionnotes) values('" . $userinfo['first_name'] . " " . $userinfo['last_name'] . "','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
}
just set a variable $i = 0 Then only insert when $i = 1 or more
if (isset($_POST['submit'])) {
$i=0; //so we can skip first row
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['filename']['tmp_name']);
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($i>0) {
$import="INSERT into tictoc(employee,taskname,tasktime,sessiontime,sessionstart,sessionend,sessionnotes) values('".$userinfo['first_name']." ".$userinfo['last_name']."','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')";
mysql_query($import) or die(mysql_error());
}
$i++;
}
fclose($handle);
print "Import done";
}
You can simply use MySQL's LOAD DATA INFILE command, which will be considerably faster than parsing the CSV into PHP, constructing an INSERT statement for every record, submitting it as a string to MySQL and having MySQL parse said string for SQL (at risk of SQL injection):
LOAD DATA INFILE ? INTO TABLE tictoc
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
IGNORE 1 LINES
(tasktime, sessiontime, sessionstart, sessionend, sessionnotes)
SET employee = ?, taskname = ?
Using PDO:
$dbh = new PDO('mysql:dbname='.$dbname, $username, $password);
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
$qry = $dbh->prepare('
LOAD DATA INFILE :filepath INTO TABLE tictoc
FIELDS TERMINATED BY \',\' OPTIONALLY ENCLOSED BY \'"\'
IGNORE 1 LINES
(tasktime, sessiontime, sessionstart, sessionend, sessionnotes)
SET employee = :employee, taskname = :taskname
');
$qry->execute(array(
':filepath' => $_FILES['filename']['tmp_name'],
':employee' => $userinfo['first_name'],
':taskname' => $userinfo['last_name']
));
}
maybe you can use this way if you like:
$i=0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$i++;
if($i==1) continue;
$import="INSERT into tictoc(employee,taskname,tasktime,sessiontime,sessionstart,sessionend,sessionnotes) values('".$userinfo['first_name']." ".$userinfo['last_name']."','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')";
mysql_query($import) or die(mysql_error());
}
No variable needed. It is much simpler than this. Here is a solution that requires the least amount of foreign code, and works just fine. Try putting:
$headers = fgetcsv($handle, 1000, ",");
Before your while() loop that grabs the CSV data. That grabs the headers, but leaves them out from being inserted into the database. Once the while loop begins, the first line has already been returned thus leaving them out of the mysql insert. On top of this it appears the headers were needed and so this solves that as well.
So in the end,
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File " . $_FILES['filename']['name'] . " uploaded successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['filename']['tmp_name']);
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
//Grab the headers before doing insertion
$headers = fgetcsv($handle, 1000, ",");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import = "INSERT into tictoc(employee,taskname,tasktime,sessiontime,sessionstart,sessionend,sessionnotes) values('" . $userinfo['first_name'] . " " . $userinfo['last_name'] . "','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
}
You can try this:
array_shift($data);
I have implement this code and it is tested code. I think it is very use full
You have follow some rule:-
1.your csv file according to database table name (ex: db table name is users then csv should be users.csv)
2.Your csv file's first row should be db table fields name (ex: Id, name etc) after the start your data entry
3.you can download data source class from :- http://code.google.com/p/php-csv-parser/ because i have require below the code: require_once 'CSV/DataSource.php';
<?php
ini_set('memory_limit','512M');
$dbhost = "localhost";
$dbname = "excel_import";
$dbuser = "root";
$dbpass = "";
$conn=mysql_connect ($dbhost, $dbuser, $dbpass) or die ("I cannot connect to the database because: " . mysql_error());
mysql_select_db($dbname) or die("Unable to select database because: " . mysql_error());
require_once 'CSV/DataSource.php';
$filename = "users.csv";
$ext = explode(".",$filename);
$path = "uploads/".$filename;
$dbtable = $ext[0];
import_csv($dbtable, $path);
function import_csv($dbtable, $csv_file_name_with_path)
{
$csv = new File_CSV_DataSource;
$csv->load($csv_file_name_with_path);
$csvData = $csv->connect();
$res='';
foreach($csvData as $key)
{
$myKey ='';
$myVal='';
foreach($key as $k=>$v)
{
$myKey .=$k.',';
$myVal .="'".$v."',";
}
$myKey = substr($myKey, 0, -1);
$myVal = substr($myVal, 0, -1);
$query="insert into ".$dbtable." ($myKey)values($myVal)";
$res= mysql_query($query);
}
if($res ==1)
{
echo "record successfully Import.";
}else{
echo "record not successfully Import.";
}
}
Declare one variable before while loop
$row=1;
then in while loop put this condition
if($row==1){
$row++;
continue;
}
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File " . $_FILES['filename']['name'] . " uploaded successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['filename']['tmp_name']);
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
fgetcsv($handle); //skip the reading of the first line from the csv file
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import = "INSERT into tictoc(employee,taskname,tasktime,sessiontime,sessionstart,sessionend,sessionnotes) values('" . $userinfo['first_name'] . " " . $userinfo['last_name'] . "','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
}
I'm having an Excel sheet with the format 01-Mar-10. When I import that csv file into my database it is storing as 0000-00-00. How to convert the dateformat while importing, or is there any other way?
This is the code im using to import to database
$databasetable = "sample";
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = "../uploads/" . basename( $_FILES['file']['name']);
$addauto = 0;
$save = 1;
$outputfile = "../temp/output.sql";
if(!file_exists($csvfile)) {
#echo $csvfile;
echo "File not found. Make sure you specified the correct path.\n";
return 0;
exit;
}
$file = fopen($csvfile,"r");
if(!$file) {
#echo "Error opening data file.\n";
return 0;
exit;
}
$size = filesize($csvfile);
if(!$size) {
echo "File is empty.\n";
return 0;
exit;
}
$csvcontent = fread($file,$size);
fclose($file);
$lines = 0;
$queries = "";
$linearray = array();
foreach(split($lineseparator,$csvcontent) as $line) {
$lines++;
$line = trim($line," \t");
$line = str_replace("\r","",$line);
$line = str_replace("'","\'",$line);
$linearray = explode($fieldseparator,$line);
$linemysql = implode("','",$linearray);
if($addauto)
$query = "insert into $databasetable values('','$linemysql');";
else
$query = "insert into $databasetable values('$linemysql');";
$queries .= $query . "\n";
#mysql_query($query);
why not use 'LOAD DATA INFILE' with mysql's date formatting?
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
http://dev.mysql.com/doc/refman/5.0/en/load-data.html
$d = "01-Mar-10";
$in_db = date('Y-m-d', strtotime($d));
echo $in_db;
Output:
2010-03-01
Use date() conversion to get valid form of date for storing in database. Use strtotime() to convert excel date format to timestamp.
After exploding data to $linearray use
$linearray[ID]=date('Y-m-d', strtotime($linearray[ID]));
to change it's value to proper format. Replace ID with array index of element with date field.