Convert a csv to mysql through php starting from a particular line? - php

I have the following code below which works, but I want to insert values to my database from the second row of my csv file. Please any pointers will be great.
$con = #mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
#mysql_select_db($databasename) or die(mysql_error());
$row = 1;
if (($handle = fopen($csvfile, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
$query = "INSERT into $databasetable(email,emailSource,espBanner,firstName,lastName,Address,City,
State,zip,home,mobile,card,ethnicity,language,gender,filename,is_uploaded)
values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]'
,'$data[7]','$data[8]','$data[9]','$data[10]','$data[11]','$data[12]','$data[13]',
'$data[14]','$data[15]','$data[16]')";
mysql_query($query) or die(mysql_error());
}
fclose($handle);
}
The result will insert every row of the csv.

$con = #mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
#mysql_select_db($databasename) or die(mysql_error());
$start_from_row = 2;
$row = 0;
if (($handle = fopen($csvfile, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br></p>\n";
$row++;
if($row < $start_from_row)
continue;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br>\n";
}
$query = "INSERT into $databasetable(email,emailSource,espBanner,firstName,lastName,Address,City,
State,zip,home,mobile,card,ethnicity,language,gender,filename,is_uploaded)
values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]'
,'$data[7]','$data[8]','$data[9]','$data[10]','$data[11]','$data[12]','$data[13]',
'$data[14]','$data[15]','$data[16]')";
mysql_query($query) or die(mysql_error());
}
fclose($handle);
}

Related

Search a keyword "royal enfield" from database using preg_match() php function but didn't works no error even i'm getting

I want to print some keyword i.e "Royal enfield" from database using php function preg_match() but i'm unable to do that how can i approad to search that keyword which is "Royal enfield" from my databse using preg_match() fucntion.
<?php
$url='localhost';
$username='readonly';
$password='';
$db_name = 'impact';
$conn=mysqli_connect($url,$username,$password,"impact");
if(!$conn){
die('Could not Connect My Sql:' .mysql_error());
}
//import.php
echo "<pre>";
//print_r($_POST);die();
$keyword = $_POST['keyword'];
$csvname = $_POST['csv_file'];
$row = 0;
if (($handle = fopen("idata.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
// echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
$query = "SELECT * FROM wm_article WHERE id = '".$data[$c]."'";
$exec = mysqli_query($conn, $query);
$details = mysqli_fetch_array($exec);
$description = $details['title'] ." ".$details['description'];
echo $description ;
$pattern = "/royal enfield/" ;
if (preg_match($pattern, $keyword)) {
echo $description ;
}
else {
echo "No match found!" ;
}
}
}
fclose($handle);
}
?>

get specific row from csv file when importing into phpmysqladmin

I'm new in here, I'm trying to get a Specific rows for a calendar csv file and import to phpmysql database but could not actually get it, hoping someone can hep me
this is my csv file
this is my database look like, i want to get row 4,6,8...so on from csv file and import to table:calendar, column:day and get row 3,5,7...to the same table but column:date
And this is my code
<?php
include "dbFunctions.php"; //Connect to Database
$deleterecords = "TRUNCATE TABLE calendar"; //empty the table of its current records
mysqli_query($link, $deleterecords);
//Upload File
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
//exclude the first row title
$row = 1;
if(($handle = fopen($_FILES['filename']['tmp_name'], "r")) !== FALSE){
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($i=0; $i<=38; $i++){
if($firstRow) { $firstRow = false; }
else {
$import="INSERT into class(day, date)
values('$data[0]','$data[1]')";
mysqli_query($link, $import) or die(mysqli_error($link));
}
echo $data[$i] . "<br />\n";
}}
fclose($handle);
}
//view upload form
}else {
print "Upload csv file and clicking on Upload<br />\n";
print "<form enctype='multipart/form-data' action='uploadCalendar.php' method='post'>";
print "csv File to import:<br />\n";
print "<input size='50' type='file' name='filename'><br />\n";
print "<input type='submit' name='submit' value='Upload'></form>";
}
?>
Since the patterns are odd and even rows.
$row = 0;
$i = 0;
$container = array();
if(($handle = fopen($_FILES['filename']['tmp_name'], "r")) !== FALSE){
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($row > 2) {
if ($row % 2 == 0) {
$i = $i - 6;
$v = 'day';
} else {
$v = 'date';
}
foreach ($data as $column) {
$container[$i][$v] = $column;
$i++;
}
}
$row++;
}
fclose($handle);
}
foreach ($container as $value) {
$import="INSERT into class(day, date)
values('".$value['day']."','".$value['date']."')";
mysqli_query($link, $import) or die(mysqli_error($link));
}
The $container should contain the date paired to the day. Like,
$container = [['day' => 'W1D1', 'date' => '19-Oct'], ['day' => 'W1D2', 'date' => '20-Oct']];
And you can use loop to insert into database.

Import particular Colums of csv in database in php/sql

I have a CSV which contains 15 columns.
But I want to import only 2 columns from the CSV in database.
whats should I do?
I tried importing but it's importing all the columns.
<?php
//database connection details
$connect = mysql_connect('localhost','root','123456');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
//your database name
$cid =mysql_select_db('test',$connect);
// path where your CSV file is located
define('CSV_PATH','C:/wamp/www/');
// Name of your CSV file
$csv_file = CSV_PATH . "test.csv";
if (($handle = fopen($csv_file, "r")) !== FALSE) {
fgetcsv($handle);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
$col[$c] = $data[$c];
}
$col1 = $col[0];
$col2 = $col[1];
$col3 = $col[2];
// SQL Query to insert data into DataBase
$query = "INSERT INTO csvtbl(ID,name,city) VALUES('".$col1."','".$col2."','".$col3."')";
$s = mysql_query($query, $connect );
}
fclose($handle);
}
echo "File data successfully imported to database!!";
mysql_close($connect);
?>

alert duplicate records in csv upload

my csv upload code is like this want to alert duplicate records which are already exists in database i am getting result with $status variable what should i do to alert every duplicate records what is way to alert every duplicate records
if(isset($_POST["Import"]))
{
$filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$row = 1;
if (($handle = fopen("$filename", "r")) !== FALSE)
{
while (($data = fgetcsv($handle)) !== FALSE)
{
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
if($c!="" && $c+1!="" && $c+2!=""){
$a[] = $data[$c];
}
}
}
$total = count($a);
$m=0;
$k = 1;
for ($c=0; $c < $total; $c++)
{
$address[$m][] = $a[$c] ;
$z = $address[$m][0];
$q = $address[$m][1];
$q .= $address[$m][2];
$q .= $address[$m][3];
$q .= $address[$m][4];
$q .= $address[$m][5];
$q .= $address[$m][6];
$q .= $address[$m][7];
$q .= $address[$m][8];
$q .= $address[$m][9];
if($a[$c]=="")
{
if($k!=1)
{
$selectcon = "SELECT user_id FROM contact
WHERE user_id = '".$z."'";
$selectRes = mysql_query($selectcon);
if($rows = mysql_fetch_array($selectRes))
{
$user_id = $rows['user_id'];
if($user_id == $z)
{
$staus = 1;
}
else
{
$staus = 1;
}
}
$insertParty = "INSERT INTO contact(user_id)values('$z')";
$res = mysql_query($insertParty);
$contact_id = mysql_insert_id();
$insertAddress = "INSERT INTO address(contact_id,address)VALUES($contact_id,'$q')";
$insertAddressRes = mysql_query($insertAddress);
if(!$insertAddressRes)
{
echo "<sctipt>";
echo "sweetAlert('oops','Import Data Fail','error')";
echo "</sctipt>";
}
else
{
echo "<script>";
echo "swal('Sucess!', 'File Imported Sucessfully!','success')";
echo "</script>";
}
$m++;
}
$k++;
}
}
fclose($handle);
}
}
}
?>
You need to make a unique row inside database. You can't do it with PHP.
Add all columns to a single UNIQUE index, the you can't insert duplicate rows in that table.

Separate CSV import fields in a query

I would to load a csv into MySQL and manage the single field. the original code uploaded the content with automatic VALUES('','$linemysql');. How can I separate the fields? I would a query like:
$sql = "INSERT IGNORE INTO `database`.`table` (`field1`,field2`, `field3`, `field4`, `field5`) VALUES(`csvfield1`,csvfield2`, `csvfield3`, `csvfield4`, `csvfield5`);";
This because I can manage which row will be included
$lines = 0;
$queries = "";
$linearray = array();
$allLines = split($lineseparator,$csvcontent);
array_shift($allLines); // removes the 1st element
foreach($allLines as $line) {
$lines++;
$line = trim($line," \t");
$line = str_replace("\r","",$line);
/************************************
This line escapes the special character. remove it if entries are already escaped in the csv file
************************************/
$line = str_replace("'","\'",$line);
/*************************************/
$linearray = explode($fieldseparator,$line);
$linemysql = implode("','",$linearray);
if($addauto)
/* Change This query VALUES('','$linemysql'); */
$query = "INSERT IGNORE INTO `database`.`table` (`field1`,field2`, `field3`, `field4`, `field5`) VALUES('','$linemysql');";
else
$query = "insert into $databasetable values('$linemysql');";
$queries .= $query . "\n";
Use PHP's built in CSV functionality including fgetcsv(). From the docs:
<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
You can modify your query like this
$query = "INSERT IGNORE INTO `database`.`table` (`field1`,field2`, `field3`, `field4`, `field5`) VALUES("'.$linemysql[0].'","'.$linemysql[1].'","'.$linemysql[2].'","'.$linemysql[3].'","'.$linemysql[4].'");";
Thanks

Categories