CSV Post reload - php

hallo guys sorry for bothering ..the code is now working..i had so many problems on my previous posts but this is the last problems i am getting..i noticed when i insert the csv file it correctly inserting..but if i refresh the page data is being duplicated due to post data..how do i make this not to repeat? i am trying to paste this but i get an error
SAVED_REQUEST = $_REQEUST;
$SAVED_POST = $_POST;
$SAVED_GET = $_GET;
// FINALLY, IN YOUR LAST LINE ERASE THE PROBLEM VARIABLES...
$_REQUEST = $_POST = $_GET = NULL;
<?php $_REQUEST = $_POST = $_GET = NULL; ?>
this is my previous script
<form enctype="multipart/form-data" method="POST" action="" >
CSV<input type="file" name="file" />
<input type="submit" value="submit" name="submit"/>
</form>
<?php
$connection = mysql_connect("localhost","root","")
or die ("Couldn't connect to server");
$db = mysql_select_db("map", $connection)
or die ("Couldn't select database");
if(isset($_POST['submit']))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file,"r");
if (($handle = fopen($file, "r")) !== FALSE) {
while ($fileop = fgetcsv($handle,1000,",","'"))
{
$a = $fileop[0];
$b = $fileop[1];
$c = $fileop[2];
$d = $fileop[3];
$e = $fileop[4];
$f = $fileop[5];
$sql = mysql_query("INSERT INTO hzy3o_zhgooglemaps_markers (title, addresstext, published, baloon, icontype, mapid)
values('$a', '$b', '$c', '$d', '$e', '$f')");
}
}
}

After successful insert make redirect to the same page:
header("Location: http://www.yourwebsite.com/yourpage"); /* Redirect browser */
exit();
Also make a check in database to prevent data duplication.
Your refactored code:
<?php
if (isset($_POST['submit'])) {
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
if (($handle = fopen($file, "r")) !== false) {
while ($fileop = fgetcsv($handle, 1000, ",", "'")) {
list($a, $b, $c, $d, $e, $f) = $fileop;
$sql = mysql_query("
INSERT INTO hzy3o_zhgooglemaps_markers (title, addresstext, published, baloon, icontype, mapid)
values('$a', '$b', '$c', '$d', '$e', '$f')
");
}
}
}
?>
<?php if (isset($_POST) && count($_POST) > 0):?>
<form enctype="multipart/form-data" method="POST" action="" >
CSV<input type="file" name="file" />
<input type="submit" value="submit" name="submit"/>
</form>
<?php else: ?>
<?php
header("Location: http://www.shambani.org /index.php?option=com_zhgooglemap&view=zhgooglemap&id=1&mapzoom=13&placemarklistid=&explacemarklistid=&grouplistid=&categorylistid=¢erplacemarkid=¢erplacemarkaction=&externalmarkerlink=0&mapwidth=&mapheight=&Itemid=177");
exit();
?>
Try it.

many thanks to gurus who Assisted me to Develope this.. i thank you very much
<?php
$connection = mysql_connect("localhost","root","")
or die ("Couldn't connect to server");
$db = mysql_select_db("map", $connection)
or die ("Couldn't select database");
if(isset($_POST['submit']))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file,"r");
if (($handle = fopen($file, "r")) !== FALSE) {
while ($fileop = fgetcsv($handle,1000,",","'"))
{
$a = $fileop[0];
$b = $fileop[1];
$c = $fileop[2];
$d = $fileop[3];
$e = $fileop[4];
$f = $fileop[5];
$sql = mysql_query("INSERT INTO hzy3o_zhgooglemaps_markers (title, addresstext, published, baloon, icontype, mapid)
values('$a', '$b', '$c', '$d', '$e', '$f')");
}
}
}
?>
<?php
if (isset($_POST) && count($_POST) > 0) {
header("Location: http://localhost/map/"); /* Redirect browser */
exit();
}
?>
<form enctype="multipart/form-data" method="POST" action="" >
CSV<input type="file" name="file" />
<input type="submit" value="submit" name="submit"/>
</form>

Related

UTF8 in php mysql

I am trying to import data from xls to mysql via php. I am facing issue in save UTF-8 text via it. I am getting it saved as ???????. My database table structure is utf8_general_ci as well my php code is like below
<?php
$con = mysqli_connect('localhost', 'myuser', 'mypass', 'mydb');
if(isset($_POST["submit"]))
{
mysqli_query($con,'SET character_set_results=utf8');
mysqli_query($con,'SET names=utf8');
mysqli_query($con,'SET character_set_client=utf8');
mysqli_query($con,'SET character_set_connection=utf8');
mysqli_query($con,'SET character_set_results=utf8');
mysqli_query($con,'SET collation_connection=utf8_general_ci');
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$i = 0;
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$option1 = $filesop[0];
$option2 = $filesop[1];
$option3 = $filesop[2];
$option4 = $filesop[3];
$correctans = $filesop[4];
$question_text = $filesop[5];
$cat_id = $filesop[6];
$sub_cat_id = $filesop[7];
$level_id = $filesop[8];
$quesimage = $filesop[9];
$sql = mysqli_query($con,"INSERT IGNORE INTO questions (option1, option2,option3,option4,correctans,question_text,cat_id,sub_cat_id,level_id,quesimage) VALUES ('".$option1."','".$option2."','".$option3."','".$option4."','".$correctans."','".$question_text."','".$cat_id."','".$sub_cat_id."','".$level_id."','".$quesimage."')");
$i = $i + 1;
}
//echo $sql;
if($sql)
{
echo "You database has imported successfully. You have inserted ". $i ." records";
}
else
{
echo "Sorry!";
}
}
?>
<html>
<head>
<title>Import Questions</title>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
Upload Excel File : <input type="file" name="file" /><br />
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>
its working fine with English Text but getting issue in Hindi or Gujarati Text. How can I solve it ?
Thanks
Note that when using fgetcsv() function for reading data the locale setting is taken into account. If LANG is e.g. en_US.UTF-8, files in one-byte encoding are read wrong by this function.
You can try another thing - to convert your .csv document on-the-fly (change the UCS-2 with the your file encoding):
function parse_csv($filename) {
if (($handle != fopen($filename, "r"))) return false;
while (($cols = fgetcsv($handle, 1000, "\t")) !== FALSE) {
foreach( $cols as $key => $value ) {
$cols[$key] = trim( $cols[$key] );
$cols[$key] = iconv('UCS-2', 'UTF-8', $cols[$key]."\0") ;
$cols[$key] = str_replace('""', '"', $cols[$key]);
$cols[$key] = preg_replace("/^\"(.*)\"$/sim", "$1", $cols[$key]);
}
echo var_dump($cols); //This will display an array of your data
}
}
Using the same idea of the previous post, with a little modification:
function global_client_charset($charset){
if(!isset($charset)){
$user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
if(strrpos($user_agent,"linux")){
$GLOBALS["CHARSET"] = "UTF-8";
}else if(strrpos($user_agent,"windows")){
$GLOBALS["CHARSET"] = "ISO-8859-1";
}
}else{
$GLOBALS["CHARSET"] = $charset;
}
}
function toUTF8($data){
if($GLOBALS["CHARSET"] === "ISO-8859-1"){
return iconv("ISO-8859-1", "UTF-8", trim($data));
}else if($GLOBALS["CHARSET"] === "UTF-8"){
return trim($data);
}else{
return trim($data);
}
}
if(isset($_POST["submit"]))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$i = 0;
//do you know the charset you are receiving ??
//global_client_charset("ISO-8859-1");
global_client_charset();
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$option1 = $filesop[0];
$option2 = $filesop[1];
$option3 = $filesop[2];
$option4 = $filesop[3];
$correctans = $filesop[4];
$question_text = $filesop[5];
$cat_id = $filesop[6];
$sub_cat_id = $filesop[7];
$level_id = $filesop[8];
$quesimage = $filesop[9];
$query = "INSERT IGNORE INTO questions (option1, option2,option3,option4,correctans,question_text,cat_id,sub_cat_id,level_id,quesimage) VALUES ('".
$option1."','".$option2."','".$option3."','".$option4."','".$correctans."','".$question_text."','".
$cat_id."','".$sub_cat_id."','".$level_id."','".$quesimage."')";
//echo toUTF8($query); die();
$sql = mysqli_query($con,toUTF8($query));
$i = $i + 1;
}
if($sql)
{
echo "You database has imported successfully. You have inserted ". $i ." records";
}
else
{
echo "Sorry!";
}
}
?>
<html>
<head>
<title>Import Questions</title>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
Upload Excel File : <input type="file" name="file" /><br />
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>

PHP/MYSQL: Importing csv files through php into a mysql table

I have been trying this code I found from this site here: https://www.johnboyproductions.com/blog/tutorial-import-a-csv-file-using-php-and-mysql
It works perfectly for me locally, but when I try the code on a live site. It says that the data is imported but does not reflect in the database. I am adding the code below:
if ($_FILES[csv][size] > 0) {
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
mysqli_query("INSERT INTO tablename VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."'
)
");
}
} while ($data = fgetcsv($handle,1000,",","'"));
//
//redirect
header('Location: filename.php?success=1'); die;
}
That's the functionality part, I will post the form section below:
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
Choose your file: <br />
<input name="csv" type="file" id="csv" />
<input type="submit" name="Submit" value="Submit" />
</form>
Any help will be greatly appreciated. Thanks
I have tried another code that was used initially which is working now:
if(isset($_POST['Submit']))
{
if ($_FILES['csv']['size'] > 0)
{
//get the csv file
$file = $_FILES['csv']['tmp_name'];
$handle = fopen($file,"r");
$firstRow = true;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
if($firstRow) { $firstRow = false; }
else {
$str="INSERT INTO tablename VALUES
('' ,
'".addslashes($data[0])."',
'".addslashes($data[1])."'
) ";
$result = mysqli_query($connection,$str);
if($result)
$cnt++;
}
}
fclose($handle);
//redirect
// header('Location: filename.php?success=1'); die;
}
}

Reading csv to insert in mysql. fill empty columns with previous line

I have a csv file. I'm trying to read this file and import data to mysql database.
For example
OrderID,ProductId,ProductDescription
100001962,15,Product1
"",32,Product2
"",31,Product3
100001546,24,Product4
How can i have my database like
100001962,15,Product1
100001962,32,Product2
100001962,31,Product3
100001546,24,Product4
new.php
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="csv" value="" />
<input type="submit" name="submit" value="Save" />
</form>
</body>
</html>
upload.php
header('Content-Type: text/html; charset=UTF-8');
require_once 'db.php';
if($_FILES['csv']['error'] == 0){
$name = $_FILES['csv']['name'];
$ext = strtolower(end(explode('.', $_FILES['csv']['name'])));
$type = $_FILES['csv']['type'];
$tmpName = $_FILES['csv']['tmp_name'];
// check the file is a csv
if($ext === 'csv'){
if(($handle = fopen($tmpName, 'r')) !== FALSE) {
// necessary if a large csv file
set_time_limit(0);
mysqli_set_charset($connection,"utf8");
$success = 0;
$nosuccess = 0;
while(( $data = fgetcsv($handle, 1000, ',')) !== FALSE) {
// number of fields in the csv
$csv[$row]['col1'] = str_replace("'", " ", $data[0]);//orderid
$csv[$row]['col2'] = str_replace("'", " ", $data[1]);//productid
$csv[$row]['col3'] = str_replace("'", " ", $data[2]);//productdesc
if ($csv[$row]['col1']==0){
if ($csv[$row-1]['col1']!=0){
$sql = "INSERT INTO csv (orderid, orderdate, orderstatus) VALUES ('". $csv[$row-1]['col1']."','". $csv[$row-1]['col2']."','". $csv[$row-1]['col3']."')";
}
if ($csv[$row-2]['col1']!=0){
$sql = "INSERT INTO csv (orderid, orderdate, orderstatus) VALUES ('". $csv[$row-2]['col1']."','". $csv[$row-2]['col2']."','". $csv[$row-2]['col3']."')";
}
//etc
}
else
{
$sql = "INSERT INTO csv (orderid, orderdate, orderstatus) VALUES ('". $csv[$row]['col1']."','". $csv[$row]['col2']."','". $csv[$row]['col3']."')";
}
mysqli_query($connection, $sql);
}
}
}
but doesn't work

html form with select box cannot get value in another php page

i have a php page called page1.php with this form
<form id="myForm" action="page2.php" method="post">
<label for="name">a label:</label><input type="submit" name="SubmitCar" value="Done" id="fbutton" /> <br />
<br />
<select name="selectCar">
<?php
session_start();
$user = "cardatabase";
$password = "";
$host = "";
$database = "my_cardatabase";
$connessione = mysql_connect($host, $user, $password) or die( mysql_error() . " <br/> could not connect to server");
mysql_select_db($database, $connessione) or die( mysql_error() . " <br/> could not connect datbase");
$id = $_SESSION['myid'];
$query = "select IDCar
from Car";
$result = mysql_query($query, $connessione) or die(mysql_error());
if( mysql_num_rows($result) > 0 ) {
$array = array();
$i = 0;
while ($row = mysql_fetch_array($result)) {
$array[$i] = $row['IDCar'];
++$i;
}
for ($i = 0; $i < count($array); ++$i) {
echo "<option value='$array[$i]'>$array[$i]</option>";
}
}
mysql_close();
?>
</select>
</form>
Simply fill the select box from DB. Now here's the problem. When i reach page2.php i need the value of the select box and i tried this
page2.php
<?php
$value = $_POST['selectCar'];
?>
But it's not working, so i tried to use sessions in this way
page1.php
</form>
<?php
if(isset($_POST['SubmitCar'])){
$_SESSION['idAuto'] = $_POST['selectCar'];
}
?>
out of the form, but still not working. What can i do to get this value in page2.php??
Try using this code to build your <option> , and use mysqli when working with the database
$result = mysqli_query($connessione, $query) or die(mysql_error());
if( mysqli_num_rows($result) > 0 ) {
$i=0;
while ($row = mysqli_fetch_row$result)) {
echo "<option value='".$row[$i]."'>".$row[$i]."</option>";
$i++;
}
}
Also, it's not indicated to have mysql tables with names in uppercase, or fields with names in uppercase.
Page2.php
You forgot to echo it.
<?php
$value = $_POST['selectCar'];
echo $value;
?>
I found a simple workaround for my problem. It might not be perfect but it works.
i deleted the action="page2.php" in the form of page1
in page1.php add this code outside the form
This will do the trick
if(isset($_POST['SubmitCar'])){
$_SESSION['idCar'] = $_POST['selectCar'];
header('Location:page2.php');
}

Creating a CSV Upload to Mysql

I have a table in MYSQL where I wish to have the option that my customer can upload a CSV file. By default I want this to add information which isn't there and automatically update it if there is information there.
These are the columns I have:
id customer_name customer_name_letterhead customer_notes systype status signaltype verification address postcode telephone mobile mobiletwo email mainarea installation Contract expiration SPA nservice maintenance monitoring MS certdate
I already know that I need to have an excel document with all of these in the headers of the rows. E.g A1-V1 has those headers.
edit:
I have made this:
<?PHP if(isset($_POST['SUBMIT']))
{
$fname = $_FILES['sel_file']['name'];
$chk_ext = explode(".",$fname);
if(strtolower($chk_ext[1]) == "csv")
{
$filename = $_FILES['sel_file']['tmp_name'];
$handle = fopen($filename, "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$sql = "INSERT into Customers(id,customer_name,customer_name_letterhead,customer_notes,systype,status,signaltype,verification,address,postcode,telephone,mobile,mobiletwo,email,mainarea installation,Contract,expiration,SPA,nservice,maintenance,monitoring,MS,certdate) 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]','$data[17]','$data[18]','$data[19]','$data[20]','$data[21]','$data[22]','$data[23]','$data[24]')";
mysql_query($sql) or die(mysql_error());
}
fclose($handle);
echo "Successfully Imported";
}
else
{
echo "Invalid File";
}
}?>
<form action='<?php echo $_SERVER["PHP_SELF"];?>' method='post'>
Import File : <input type="file" name="sel_file" id="sel_file">
<input type='submit' name='submit' value='submit'>
</form>
Upon clicking submit, nothing happens.
Here is a picture of my csv file:
I ended up searching for a video on YouTube which really did help. It ended up giving me this:
<?PHP
if(isset($_POST['submit']))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file,"r");
while(($fileop = fgetcsv($handle,1000, ",")) !== false)
{
$customer_name = $fileop[0];
$customer_name_letterhead = $fileop[1];
$customer_notes = $fileop[2];
$systype = $fileop[3];
$status = $fileop[4];
$signaltype = $fileop[5];
$verification = $fileop[6];
$address = $fileop[7];
$postcode = $fileop[8];
$telephone = $fileop[9];
$mobile = $fileop[10];
$mobiletwo = $fileop[11];
$email = $fileop[12];
$mainarea = $fileop[13];
$installation = $fileop[14];
$Contract = $fileop[15];
$expiration = $fileop[16];
$SPA = $fileop[17];
$nservice = $fileop[18];
$maintenance = $fileop[19];
$monitoring = $fileop[20];
$MS = $fileop[21];
$certdate = $fileop[22];
$sql = mysqli_query($GLOBALS["___mysqli_ston"], "INSERT INTO Customers (
customer_name,
customer_name_letterhead,
customer_notes,
systype,
status,
signaltype,
verification,
address,
postcode,
telephone,
mobile,
mobiletwo,
email,
mainarea,
installation,
Contract,
expiration,
SPA,
nservice,
maintenance,
monitoring,
MS,
certdate
) VALUES (
'$customer_name',
'$customer_name_letterhead',
'$customer_notes',
'$systype',
'$status',
'$signaltype',
'$verification',
'$address',
'$postcode',
'$telephone',
'$mobile',
'$mobiletwo',
'$email',
'$mainarea',
'$installation',
'$Contract',
'$expiration',
'$SPA',
'$nservice',
'$maintenance',
'$monitoring',
'$MS',
'$certdate'
)");
if($sql)
{
echo 'Uploaded '. $sql . ' entries';
}
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<br>
<input type="submit" name="submit" value="Upload CSV File">
</form>
not used it myself but have you tried this,
http://php.net/manual/en/function.str-getcsv.php
you could also try breaking the csv up into lines using explode on \n and then splitting it up further based on the ,.
once you have all the chunks push it into the database.

Categories