I have a simple uploading page that will allow a user to upload CSV file into the server.
After the uploading, the page will display the CSV file into an html table format
Code to Display CSV File to HTML:
<?php
echo "<table class='tbl1'>\n\n";
echo "<tr>";
echo "<th>GOUP NO</th>";
echo "<th>PID CODE</th>";
echo "<th>ID CODE</th>";
echo "<th>DESCRIPTION</th>";
echo "</tr>";
$f = fopen("upload\micro_center.csv", "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
echo "\n</table>";
?>
I want to add a query on how to insert the data in the CSV file or displayed html table into MSSQL database.
Note: Table headers and Database Table Columns are with the same name
CSV File:
0,G068,CNDLDS,Candelaria District
0,CNDLDS,CNDLDSA,Babancal ES
0,CNDLDS,CNDLDSB,Binabalian ES
0,CNDLDS,CNDLDSC,Candelaria Central
0,CNDLDS,CNDLDSD,Catol ES
Thank You for your answers
Use the below code:
//get the csv file
$file = $_FILES[csv][tmp_name]; // your csv file here
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
mysql_query("INSERT INTO your table (GOUP_NO, PID_CODE, ID_CODE, DESCRIPTION) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."',
'".addslashes($data[3])."'
)
");
}
} while ($data = fgetcsv($handle,1000,",","'"));
//
Related
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.
I got a problem and could't find a solution for me.
I want to insert with a php script in my mysql database from a csv file.
The database got a primary key, which is created automatically on every insert.
The csv file grows with time, but the existed date should not be inserted again! I could not check the primary key in this case, because it is generated on every insert.
This is my file so far:
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import = "INSERT INTO xt_products(
products_owner,
products_quantity,
products_shippingtime,
products_model,
products_model_original,
products_price,
products_tax_class_id
) VALUES (
'$data[0]',
'$data[1]',
'$data[2]',
'$data[3]',
'wayne_$data[4]',
'$data[5]',
'$data[6]'
)";
mysql_query($import) or die (mysql_error());
}
I know about where exists or if exists bgin end, but I could not get it to work.
Edit: Forgot to mention it, it should check, whether the products_model is already in the database. That would be the $data[3] field there
You just have to add the duplicate statement
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import = "INSERT INTO xt_products(
products_owner,
products_quantity,
products_shippingtime,
products_model,
products_model_original,
products_price,
products_tax_class_id
) VALUES (
'$data[0]',
'$data[1]',
'$data[2]',
'$data[3]',
'$data[4]',
'$data[5]',
'$data[6]'
)
ON DUPLICATE KEY UPDATE products_owner='$data[0]'
";
mysql_query($import) or die (mysql_error());
}
<?php
include ("config.php"); //Connect to Database
//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
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import="INSERT into table(something,something,something,something,something,something,something) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
//view upload form
}else {
print "Upload new csv by browsing to file and clicking on Upload<br />\n";
print "<form enctype='multipart/form-data' action='import.php' method='post'>";
print "File name to import:<br />\n";
print "<input size='50' type='file' name='filename'><br />\n";
print "<input type='submit' name='submit' value='Upload'></form>";
}
?>
config.php
<?php
$db = mysql_connect('localhost', 'user', 'pass') or die("Could not connect.");
if(!$db)
die("no db");
if(!mysql_select_db("database",$db))
die("No database selected.");
?>
Currently I am doing a project in php for uploading CSV file and to insert data into database. Before Inserting I need to display the data in checkboxes and to insert the values that are checked.
With this code after uploading it displays data with checkbox but on clicking the checkbox the values are not inserting into database.
if(isset($_POST['upload']))
{
if (is_uploaded_file($_FILES['filename']['tmp_name']))
{
echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
}
$handle = fopen($_FILES['filename']['tmp_name'], "r");
echo("<table border='1'>");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
echo("<tr>\r\n");
foreach ($data as $index=>$val)
{
echo("\t<td><input type='checkbox' name='chk1[]' value='$val'>$val</td>\r\n");
}
echo("</tr>\r\n");
}
echo("</table>");
echo("<td><input type='submit' name='insert' id='insert' value='Submit' /></td>");
fclose($handle);
}
For Inserting the selected data into database I am using this code.
if(isset($_POST['insert']))
{
for($i=0;$i < sizeof($checkbox1);$i++)
{
$query = "INSERT INTO uploadmail (name,email) VALUES ('$name','".$checkbox1[$i]."')";
echo $query;
$result = mysql_query($query);
}
}
After clicking checkboxes when I click Submit button it is not doing any action.So Please give me any suggestions.
THANKS IN ADVANCE.
Your table closed before the form submit. And please maintain the table structure if you are using form in a table. Close all input fields in table's td followed by "tr".
And here its understood that you assigned $checkbox1 = $_POST['chk1'];
Currently I am doing a project in php for uploading CSV file and to insert data into database.After CSV file uploaded it displays the data present in file with checkboxes.On Clicking the checkbox the values are not getting inserted into the table.
The Coding I used
if(isset($_POST['upload']))
{
if (is_uploaded_file($_FILES['filename']['tmp_name']))
{
echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
}
$handle = fopen($_FILES['filename']['tmp_name'], "r");
echo("<table border='1'>");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
echo("<tr>\r\n");
foreach ($data as $index=>$val)
{
echo("\t<td><input type='checkbox' name='chk1[]' value='$val'>$val</td>\r\n");
}
}
echo("</tr>\r\n");
echo("</table>");
echo("<input type='submit' name='insert' id='insert' value='Submit' />");
fclose($handle);
}
On Uploading the file the values get displayed,but clicking on submit button no action is performed.
The Code for Submit button is:
if(isset($_POST['insert']))
{
for($i=0;$i < sizeof($checkbox1);$i++)
{
$query = "INSERT INTO uploadmail (name,email) VALUES ('$name','".$checkbox1[$i]."')";
$result = mysql_query($query);
}
}
The values displayed like this
Please give your suggestions.THANKS IN ADVANCE.
You can download reader.php and oleread.inc zip folder from this site http://sourceforge.net/projects/phpexcelreader/
and rest of code to insert data in database
require_once 'Excel/reader.php';
// ExcelFile($filename, $encoding);
$data = new Spreadsheet_Excel_Reader();
// Set output Encoding.
$data->setOutputEncoding('CP1251');
$data->read($_FILES['excel_upload']['tmp_name']);
error_reporting(E_ALL ^ E_NOTICE);
for ($i=1;$i<=$data->sheets[0]['numRows'];$i++)
{
$EmailAdd = $data->sheets[0]['cells'][$i][1];
$NameAdd = $data->sheets[0]['cells'][$i][2];
$Phone = $data->sheets[0]['cells'][$i][3];
$Address = mysql_real_escape_string($data->sheets[0]['cells'][$i][4]);
if(filter_var($EmailAdd, FILTER_VALIDATE_EMAIL))
{
$currentId = mysql_query("INSERT INTO `Student` (`StudentEmail_email`,StudentEmail_Name`,`StudentEmail_Mobile`,`StudentEmail_Address`) VALUES ('$EmailAdd','$NameAdd','$ContactAdd','$Address')");
}
}
Remarks:
I have included some explanations in the code quoted in /* */.
I changed your insert query to MySQLi Prepared Statement rather than the
deprecated MySQL.
Here's a code that you can use.
if(isset($_POST['upload']))
{
if (is_uploaded_file($_FILES['filename']['tmp_name']))
{
echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
}
$handle = file_get_contents($_FILES['filename']['tmp_name']); /* GET THE CONTENT OF UPLOADED FILE */
$val = explode(',',$handle);
$count = count($val); /* COUNT THE TOTAL EXPLODED RESULT */
echo("<table border='1'>");
for($x=0;$x<=$count;$x++){ /* START THE LOOP BASED FROM THE COUNTED RESULT */
echo("<tr>\r\n");
echo("\t<td><input type='checkbox' name='chk1[$x]' value='$val[$x]'>$val[$x]</td>\r\n"); /* GET THE VALUE AND STORE IT INTO THE chk1 ARRAY */
echo("</tr>\r\n");
} /* END OF FOR LOOP */
echo("</table>");
echo("<input type='submit' name='insert' id='insert' value='Submit' />");
} /* END OF ISSET UPLOAD */
I just noticed that you don't have the move_uploaded_file. Or you just didn't include it in your sample code?
And after selecting/checking the check boxes and submitting the form:
if(isset($_POST['insert']))
{
$comp=count($_POST['chk1']); /* COUNT THE TOTAL SUBMITTED CHECKBOX */
$checkbox1=$_POST['chk1'];
for($i=0;$i<=$comp;$i++)
{
if(!empty($checkbox1[$i])){ /* IF SUBMITTED DATA IS CHECKED */
/* WHERE DOES YOUR $name VARIABLE CAME FROM? */
$stmt = $YourSQLConnection->prepare("INSERT INTO uploadmail (name,email) VALUES (?, ?)");
$stmt->bind_param('ss', $name,$checkbox1[$i]); /* BIND THE VALUE TO STRINGS */
}
}
}
I have simple script that uploads CSV files to a MySQL database. It works ok but if user misses selecting some CSV file to upload and pushes the UPLOAD button, the script tries to insert thousand of 0 lines in the data base.
I wonder if there is a way to check befoere upload file if user has allready selected FILE.
Here is my code:
<?php
include("conection.php"); //Connect to Database
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<br><center><p>" . " ". $_FILES['filename']['name'] ." " . "</p></center>";
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
$count = 0; //skip first line of the CSV file
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
if($count) //skip first line of the CSV file
{
$import="INSERT into PAX (name,surname,group) VALUES('$data[0]','$data[1]','$data[2]')";
mysql_query($import) or die(mysql_error());
}
$count++;
}
fclose($handle);
print "<br><center><p>UPLOADED </p></center> ";
print "<br> ";
print "<center><a href='index.php'><button>HOME</button</a></center> ";
//view upload form
}else {
print "<center><br><p><b>UPLOAD</b> </p>\n";
print "<center><br>Select the file for Upload \n";
print "<form enctype='multipart/form-data' action='upload.php' method='post'>";
print "<center><input size='50' type='file' name='filename'><br />\n";
print "<br>";
print "<input type='submit' name='submit' value='UPLOAD'></form>";
}
?>
Hard to say definitively with your code as it is presented & without seeing the original data, but I believe simply setting a conditional that checks $data is enough to prevent the issue you are seeing:
So this line:
if ($count) //skip first line of the CSV file {
Changes to this:
if ($count && !empty($data)) //skip first line of the CSV file {
And here is your code adjusted and indents cleaned up for readability. EDIT And I have edited it so there is now a $SUCCESS_SUBMIT variable. That way if the submission is successful & that is true or false you can act on it.
include("conection.php"); //Connect to Database
$SUCCESS_SUBMIT = false;
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<br><center><p>" . " ". $_FILES['filename']['name'] ." " . "</p></center>";
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
$count = 0; //skip first line of the CSV file
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
if ($count && !empty($data)) //skip first line of the CSV file {
$import = "INSERT into PAX (name,surname,group) VALUES('$data[0]','$data[1]','$data[2]')";
mysql_query($import) or die(mysql_error());
$SUCCESS_SUBMIT = true;
}
$count++;
}
fclose($handle);
}
if ($SUCCESS_SUBMIT) {
print "<br><center><p>UPLOADED </p></center> ";
print "<br> ";
print "<center><a href='index.php'><button>HOME</button</a></center> ";
}
else {
print "<center><br><p><b>UPLOAD</b> </p>\n";
print "<center><br>Select the file for Upload \n";
print "<form enctype='multipart/form-data' action='upload.php' method='post'>";
print "<center><input size='50' type='file' name='filename'><br />\n";
print "<br>";
print "<input type='submit' name='submit' value='UPLOAD'></form>";
}
"There is a way to show user if hasnt selected any csv file give a message file "please select file" or something like this"
you could use javascript to have a message, if not file selected:
print "<form enctype='multipart/form-data' action='upload.php'
onsubmit='return validateUpload();' name='formUpload'
method='post'>";
print "<center><input size='50' type='file' name='filename'><br />\n";
print "<br>";
print "<input type='submit' name='submit' value='UPLOAD'></form>";
}
?>
<script type="text/javascript" >
function validateUpload()
{
var fName = document.forms["formUpload"]["filename"].value;
if (fName==null || fName=="")
{
alert("Please select file !");
return false;
}
}
</script>