Import CSV file data into MySQL table [duplicate] - php

This question already has answers here:
Insert and update CSV file data into MySQL table using PHP
(2 answers)
Closed 7 years ago.
I am inserting record from CSV file to MySQL table; if any record already exists update that record and insert other records and if there is no match of the record insert all records.
Here is my code
<?php
$connect = mysql_connect('localhost','root','root');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
$cid =mysql_select_db('bizin490_devcredit',$connect);
define('CSV_PATH', '/home/ubc/Documents/');
$csv_file = CSV_PATH . "test.csv";
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
$i = 0;
while (!feof($csvfile)) {
$csv_data[] = fgets($csvfile, 1024);
$csv_array = explode(",", $csv_data[$i]);
$insert_csv = array();
$insert_csv['name'] = $csv_array[0];
$insert_csv['email'] = $csv_array[1];
$query = mysql_query("select name from test where name='" . $insert_csv['name'] . "'");
$count = mysql_num_rows($query);
if ($count == 0) {
$query = "INSERT INTO test(name,email)VALUES('" . $insert_csv['name'] . "','" . $insert_csv['email'] . "')";
$n = mysql_query($query, $connect);
} else {
$sql = "update test set email='".$insert_csv['email']."'";
//echo "<pre>";print_r($sql);
$qu = mysql_query($sql);
echo "<pre>";print_r($_POST);
}
$i++;
//die;
}
fclose($csvfile);
echo "File data successfully imported to database!!";
mysql_close($connect);
?>

Something like:
LOAD DATA INFILE '/home/ubc/Documents/test.csv'
REPLACE
INTO TABLE `test`
(name, email)

Related

How to get last inserted id in mysql and use it to insert it in another table?

I'm trying to get last id which i inserted already in database through another php file and in current php file i can't get last id to use it.
This is my code.
<?php
include "connection.php.php";
$sucess = 105;
$fail = 107;
$planImage = $_POST['projects_plan_images'];
$planFilename = $_POST['projectsPlanImagesNames'];
$last_id = mysqli_insert_id($con);
$planLength = count($planFilename);
for($i = 0; $i < $planLength; $i++) {
$imageNow = time();
$new_imageFilename = $imageNow . "_" . $planFilename[$i];
$sql6 = "INSERT INTO projects_plans_images(project_id, plan_image, plan_name) VALUES ('$last_id','$new_imageFilename','$new_imageFilename')";
$result6 = mysqli_query($con, $sql6);
$binary=base64_decode($planImage[$i]);
$file = fopen('files/plans_images/' . $new_imageFilename, 'wb');
fwrite($file, $binary);
fclose($file);
}
$jsonResult = '{"state":';
if($result){
$jsonResult.= $sucess;
}else {
$jsonResult.= $fail;
}
$jsonResult .="}";
print_r($jsonResult);
?>

Excel date is changed to different date in mysql

I am trying to import the excel file to mysql database. I have got date and IMEI field in excel to import to database. But while importing to database my date is changd to different date and IMEI no is changed to exponential format. How can I resolve that problem.
here is the picture.
And here is the code.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "portal";
//$exceldata = array();
// Create connection
$con = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
/** Set default timezone (will throw a notice otherwise) */
date_default_timezone_set('Asia/Kolkata');
include 'Classes2/PHPExcel/IOFactory.php';
if(isset($_FILES['file']['name'])){
// $file_name = $_FILES['file']['name'];
// $ext = pathinfo($file_name, PATHINFO_EXTENSION);
//Checking the file extension
$file_name = $_FILES['file']['tmp_name'];
$inputFileName = $file_name;
if(is_uploaded_file($inputFileName)){
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch (Exception $e) {
die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
. '": ' . $e->getMessage());
}
//Table used to display the contents of the file
echo '<center><table style="width:50%;" border=1>';
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// Loop through each row of the worksheet in turn
for ($row = 2; $row <= $highestRow; $row++) {
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL, TRUE, FALSE);
//check whether member already exists in database with same email
$prevQuery = "SELECT id FROM activereport WHERE aIMEI = '".$rowData[0][1]."' ";
// $prevResult = $con->query($prevQuery);
$prevResult = mysqli_query($con,$prevQuery);
$count = mysqli_num_rows($prevResult);
if($count > 0){
// //update member data
$sql = " UPDATE activereport SET modelno= '".$rowData[0][0]."', dateOfActivation='" . $rowData[0][2] . "' WHERE aIMEI = '" .$rowData[0][1]."' ";
}
else{
$sql = " INSERT INTO activereport (modelno, aIMEI, dateOfActivation) VALUES ('".$rowData[0][0]."','".$rowData[0][1]."','".$rowData[0][2]."')";
}
if (mysqli_query($con, $sql)) {
$exceldata[] = $rowData[0];
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
echo '</table></center>';
//redirect to the listing page
header("Location: Import_Active_Data.php");
}
else{
echo '<p style="color:red;">Please upload valid</p>';
}
}
?>
One reason for this behavior could be the way excel stores dates: by counting the days since Jan 1, 1900. if you pass that as an argument to your sql query, it could do weird things.
Try converting the excel date to a string first and pass that to the sql query.
So, I'd change this block:
if($count > 0){
// //update member data
$sql = " UPDATE activereport SET modelno= '".$rowData[0][0]."', dateOfActivation='" . $rowData[0][2] . "' WHERE aIMEI = '" .$rowData[0][1]."' ";
}
else{
$sql = " INSERT INTO activereport (modelno, aIMEI, dateOfActivation) VALUES ('".$rowData[0][0]."','".$rowData[0][1]."','".$rowData[0][2]."')";
}
into this:
if($count > 0){
// Date-to-string conversion start
$exceldate = $rowData[0][2];
$phpdate = new DateTime();
$phpdate->setDate(1899, 12, 30);
$dateint = new DateInterval("P" . $exceldate . "D");
$phpdate->add($dateint);
$datestring = $phpdate->format("Y-m-d");
// Date-to-string conversion end
// //update member data
$sql = " UPDATE activereport SET modelno= '".$rowData[0][0]."', dateOfActivation='" . $datestring . "' WHERE aIMEI = '" .$rowData[0][1]."' ";
}
else{
$sql = " INSERT INTO activereport (modelno, aIMEI, dateOfActivation) VALUES ('".$rowData[0][0]."','".$rowData[0][1]."','".$datestring."')";
}
Instead of using the rowData[0][2] directly, this will convert the value of that Excel cell (2017-11-11 = 43050) into a php-string ('2017-11-11'), which you can then pass to the sql query.

How to Validate Employee Id in Importing File in .CSV format to SQL?

How to Validate Employee Id in Importing File in .CSV format to SQL?
*a code that check if the data is already exist.
-->sample: if the Employee Id already exist it promts "Employee ID already Exist"..
if the rows in csv, you can make a array of csv rows.
$list =array();
$id = array();
while( ($rows= getcsv($hande)) !== false)
{
array_push($list, $rows);
array_push($id, $rows['emplyee_id']);
}
then check mysql or database
$check_id = implode(",", $id);
$que = "select employ_id from table where employ_id in ($check_id)";
at this time you can find employ_ids from database.
if you make employee_id column unique, your code would be like this
$result=mysqli_query($db_con", "insert into table (employ_id) values ('$empoy_id')";
if($result == false) // if employ_id alreay exists in table $result is false
{
}
but as i know, the best way using index is checking key is exists before inserting data not after inserting query failed.
This is my code:
`<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
$a=$_FILES["file"]["tmp_name"];
echo $a;
$connect = mysql_connect('localhost','root','');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
//your database name
$cid =mysql_select_db('cgi_warehouse',$connect);
// path where your CSV file is located
//define('CSV_PATH','C:/xampp/htdocs/');
//<!-- C:\\xampp\\htdocs -->
// Name of your CSV file
$csv_file = $a;
if (($getfile = fopen($csv_file, "r")) !== FALSE) {
$data = fgetcsv($getfile, 1000, ",");
while (($data = fgetcsv($getfile, 1000, ",")) !== FALSE) {
//$num = count($data);
//echo $num;
//for ($c=0; $c < $num; $c++) {
$result = $data;
$str = implode(",", $result);
$slice = explode(",", $str);
$col1 = $slice[0];
$col2 = $slice[1];
$col3 = $slice[2];
$col4 = $slice[3];
$col5 = $slice[4];
$col6 = $slice[5];
$col7 = $slice[6];
$col8 = $slice[7];
$col9 = $slice[8];
$col10 = $slice[9];
$col11 = $slice[10];
$col12 = $slice[11];
$col13 = $slice[12];
$col14 = $slice[13];
$col15 = $slice[14];
$col16 = $slice[15];
$query = "INSERT INTO tools(tools_id, item_description, category_id, sn, qty, price, supplier, frm, location, ref_no, sender, receiver, date_receive, date_added, status, remarks) VALUES('".$col1."','".$col2."','".$col3."','".$col4."','".$col5."','".$col6."','".$col7."','".$col8."','".$col9."','".$col10."','".$col11."','".$col12."','".$col13."','".$col14."','".$col15."','".$col16."')";
$s=mysql_query($query, $connect );
}
}
echo "<script>alert('Record successfully uploaded.');window.location.href='#';</script>";
mysql_close($connect);
}
?>`

How to import data from a single .csv file and save it in three different tables by mentioning the specific columns

I am working on a plugin, it create a three different tables "wp_foo_songs", "wp_foo_playlist", "wp_foo_rating".
In plugin i make a feature that export data from these 3 tables in one .csv file, it export data successfully.
In plugin there is also a feature that import the data from .csv file. Now i want that when a user upload that csv file, the data stored in 3 tables with respectively columns. I write the different queries but i failed.
Here is my code:
Export Query:
$pre = $wpdb->prefix;
$query = "SELECT plist.*, psong.*, prate.*
FROM " . $pre . "foo_playlists As plist
LEFT JOIN " . $pre . "foo_songs As psong
On plist.playlist_name = psong.splaylist_name
LEFT JOIN " . $pre . "foo_rating As prate
On psong.song_id = prate.rsong_id";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$line = "";
$comma = "";
foreach ($row as $name => $value) {
$line .= $comma . '"' . str_replace('"', '""', $name) . '"';
$comma = ",";
}
$line .= "\n";
$out = $line;
mysql_data_seek($result, 0);
while ($row = mysql_fetch_assoc($result)) {
$line = "";
$comma = "";
foreach ($row as $value) {
$line .= $comma . '"' . str_replace('"', '""', $value) . '"';
$comma = ",";
}
$line .= "\n";
$out.=$line;
}
$csv_file_name = 'songs_' . date('Ymd_His') . '.csv'; # CSV FILE NAME WILL BE table_name_yyyymmdd_hhmmss.csv
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=" . $csv_file_name);
header("Content-Description:File Transfer");
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Type: application/octet-stream');
echo __($out, "hmp");
exit;
It gives me the right result look like this jsfiddle
Import Query:
$fileName = $_FILES['filename']['tmp_name'];
// Playlist Import Query
$query = "LOAD DATA LOCAL INFILE '" . $fileName . "' INTO TABLE `wp_foo_playlists`
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n' IGNORE 1 LINES
(#pcol1,#pcol2,#pcol3,#pcol4)
Set playlist_id=#pcol1,playlist_name=#pcol2,playlist_description=#pcol3,
playlist_shortcode=#pcol4";
$result = mysql_query($query) or die(mysql_error());
// Songs Import Query
$query1 = "LOAD DATA LOCAL INFILE '" . $fileName . "' INTO TABLE `wp_foo_songs`
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n' IGNORE 1 LINES
(#scol1,#scol2,#scol3,#scol4,#scol5,#scol6,#scol7,#scol8,#scol9,#scol10,
#scol11,#scol12,#scol13,#scol14,#scol15,#scol16)
Set song_id=#scol1,list_order=#scol2,splaylist_name=#scol3,mp3=#scol4,
ogg=#scol5,title=#scol6,buy=#scol7,buyy=#scol8,buyyy=#scol9,price=#scol10,
cover=#scol11,duration=#scol12,artist=#scol13,total_votes=#scol14,
song_shortcode=#scol15,song_slug=#scol16";
$result1 = mysql_query($query1) or die(mysql_error());
// Rating Import Query
$query2 = "LOAD DATA LOCAL INFILE '" . $fileName . "' INTO TABLE `wp_foo_rating`
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n' IGNORE 1 LINES
(#rcol1,#rcol2,#rcol3,#rcol4)
Set rate_id=#rcol1,rsong_id=#rcol2,rating_value=#rcol3,user_ip=#rcol4";
$result2 = mysql_query($query2) or die(mysql_error());
It store the first table data correctly, but in two tables it save the first table data again and then save another data.
Any one please help i have no idea.
Ok i get answer by my own.
I am using "fgetcsv" instead of "LOAD DATA LOCAL INFILE"
Here is my code:
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
// echo "File " . $_FILES['filename']['name'] . " uploaded successfully." . "";
// echo "<h2>Displaying contents:</h2>";
// readfile($_FILES['filename']['tmp_name']);
$fileName = $_FILES['filename']['tmp_name'];
//$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(preg_match("/\.(csv)$/", $fileName)){
die("Please upload CSV format only");
}
$link = mysql_connect($mysql_host, $mysql_user, $mysql_pass) or die('Could not connect: ' . mysql_error());
$db = mysql_select_db($mysql_db, $link) or die('Could not select database: ' . $mysql_db);
$handle = fopen($fileName,"r");
$i = 0;
while(($fileop = fgetcsv($handle, 1000, ",")) !== false){
$playlist_id = $fileop[0];
$playlist_name = $fileop[1];
$playlist_description = $fileop[2];
$playlist_shortcode = $fileop[3];
$song_id = $fileop[4];
$list_order = $fileop[5];
$playlist_name = $fileop[6];
$mp3 = $fileop[7];
$ogg = $fileop[8];
$title = $fileop[9];
$buy = $fileop[10];
$buyy = $fileop[11];
$buyyy = $fileop[12];
$price = $fileop[13];
$cover = $fileop[14];
$duration = $fileop[15];
$artist = $fileop[16];
$total_votes = $fileop[17];
$song_shortcode = $fileop[18];
$song_slug = $fileop[19];
$rate_id = $fileop[20];
$song_id = $fileop[21];
$rating_value = $fileop[22];
$user_ip = $fileop[23];
if($i > 0){
$playlist_insert = "Insert Into wp_foo_playlists(playlist_id,playlist_name,playlist_description,playlist_shortcode) Value('$playlist_id','$playlist_name','$playlist_description','$playlist_shortcode')";
mysql_query($playlist_insert);
$song_insert = "Insert Into wp_foo_songs(song_id,list_order,splaylist_name,mp3,ogg,title,buy,buyy,buyyy,price,cover,duration,artist,total_votes,song_shortcode,song_slug) Value('$song_id','$list_order','$playlist_name','$mp3','$ogg','$title','$buy','$buyy','$buyyy','$price','$cover','$duration','$artist','$total_votes','$song_shortcode','$song_slug')";
mysql_query($song_insert);
$rate_insert = "Insert Into wp_foo_rating(rate_id,rsong_id,rating_value,user_ip) Value('$rate_id','1','$rating_value','$user_ip')";
mysql_query($rate_insert);
}
$i++;
}
fclose($handle);
}
To ignore the first row from csv file i am using this coindtion
$i = 0;
if($i > 0){
// Insert Queries
}
$i++;
You are going to have to split the file into three files somehow if you want to use load data infile.
Alternatively, build an import routine in PHP to do exactly what you want

check if valor exist in mysql table [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Check if value exist in mysql
I have a small script to upload data to mysql database from a csv file and I want to check the list of values that are inside of the csv file.
This is the CSV File to check if values from csv exist in db:
code,alert_quantity
12345,10
This my proeject PHP File:
<?php
$link_id = mysql_connect("localhost", "root", "")
or die("Could not connect.");
if(!mysql_select_db("database",$link_id))
die("database was not selected.");
function _checkIfCodeExists($code){
$sql = "SELECT COUNT(*) AS count_no FROM products WHERE code = ?";
$count = $sql;
if($count > 0){
return true;
}else{
return false;
}
}
function _updateData($line_of_data){
$code = $line_of_data[0];
$newAlert = $line_of_data[1];
$sql = "UPDATE ";
}
$file_handle = fopen("file.csv", "r");
while (($line_of_data = fgetcsv($file_handle, 1000, ",")) !== FALSE) {
$query = mysql_query("SELECT * FROM products WHERE code ='$line_of_data[0]'") or die(mysql_error());
$message = '';
$count = 1;
if(_checkIfCodeExists($line_of_data[0])){
try{
_updateData($_data);
$message .= $count . '> Success:: Product with code (' . $line_of_data[1] . ') Exist (' . $line_of_data[0] . '). <br />';
}catch(Exception $e){
$message .= $count .'> Error:: While updating alert (' . $line_of_data[1] . ') of code (' . $line_of_data[0] . ') => '.$e->getMessage().'<br />';
}
}else{
$message .= $count .'> Error:: Product code (' . $line_of_data[0] . ') Doesnt exist<br />';
}
$count++;
echo $message;
}
?>
I don't know what you're doing here, but it isn't going to work:
$sql = "SELECT COUNT(*) AS count_no FROM products WHERE code = ?";
$count = $sql;
if($count > 0){
return true;
This is equivalent to:
if ("SELECT COUNT(*)..." > 0)
That will never be true.

Categories