How do I insert data from a CSV file into my database? - php

I'm trying to upload my txt file into my database but I don't think anything happens. I checked my database in phpmyadmin but nothing was inserted. How do I load and insert my data into mysql database?
Here's my code:
<?php
$conn = mysql_connect("localhost", "login", "password") or die(mysql_error());
mysql_select_db("database", $conn);
if(!isset($_POST['submit']))
{
$uploadtxt = "nyccrash.txt";
$handle= fopen($uploadtxt, "r");
// error checking.
if($handle === false) {
die("Error opening $uploadtxt");
}
while($fileop = fgetcsv($handle, 1000, ",") !== false) {
$crash_year = $fileop[0];
$accident_type = $fileop[1];
$collision_type = $fileop[2];
$weather_condition = $fileop[3];
$light_condition = $fileop[4];
$x_coordinate = $fileop[5];
$y_coordinate = $fileop[6];
$sql = mysql_query("INSERT INTO nyccrash (crash_year, accident_type, collision_type, weather_condition, light_condition, x_coordinate, y_coordinate) VALUES ($crash_year, $accident_type, $collision_type, $weather_condition, $light_condition, $x_coordinate, $y_coordinate)");
} }
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> NYC Crash Data </title>
<link ref="stylesheet" type "text/css" href="../style/style.css" />
</head>
<body>
<div id="mainWrapper">
<form method="post" action="" enctype="multipart/form-data">
<input type="file" name="file"/>
<br/>
<input type="submit" name="submit" value="submit"/>
</form>
</div>

If this is text data then you forgot ' around data
$sql = mysql_query("INSERT INTO nyccrash (crash_year, accident_type,
collision_type, weather_condition, light_condition, x_coordinate, y_coordinate)
VALUES ('$crash_year', '$accident_type', '$collision_type',
'$weather_condition', '$light_condition', '$x_coordinate', '$y_coordinate')");

Here's how to parameterise SQL statements with untrusted input.
$stmt = $db->prepare("INSERT INTO nyccrash (crash_year, accident_type,
collision_type, weather_condition, light_condition, x_coordinate, y_coordinate)
VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param('sssssss', $crash_year, ...);
$stmt->execute();
See http://codular.com/php-mysqli for more info on this.
If you don't understand why you should be doing it this way, look up SQL injection, and don't write another line of code until you do understand it.

You can do it with the library of this answer
$csv = New CSVReader();
$result = $csv->parse_file('Test.csv');//path to file should be csv
echo '<pre>'; //
print_R($result); // Only for testing
if($result){
foreach($result as $row){
$crash_year = $row['crash_year'];
$accident_type = $row['accident_type'];
$collision_type = $row['collision_type'];
$weather_condition = $row['weather_condition'];
$light_condition = $row['light_condition'];
$x_coordinate = $row['x_coordinate'];
$y_coordinate = $row['y_coordinate'];
$query = "INSERT INTO nyccrash";
$query .= "(crash_year, accident_type, collision_type, weather_condition, light_condition, x_coordinate, y_coordinate)";
$query .= " VALUES ";
$query .= "('$crash_year','$accident_type','$collision_type', '$weather_condition', '$light_condition', '$x_coordinate', '$y_coordinate')";
mysqli_query($query);
unset($query);
}
}
One thing i noticed that in the insert query you must have some varchar fields in your database table and for that you are missing commas. Wrap the varchar fields with commas. This might be the problem and use die and mysql_error to see what the error really is.

Related

php Real-Time form post submit

Let me explain what I want to.
I want to add a value in a list with db add without page change when I input in form, and click submit.
but in this code, I must refresh one more time to add, and also added twice a time.
How can I do that?
<?php
$conn = mysqli_connect('127.0.0.1','MYID','MYPASS','MYDB');
$sql = "SELECT * FROM MYTABLE";
$rs = mysqli_query($conn, $sql);
$list = '';
while($row = mysqli_fetch_array($rs)) {
$list = $list."<li>{$row['title']}</li>";
}
$article = array(
'title' => 'Welcome!',
'description' => 'Hello, Web!'
);
if (isset($_GET['id'])){
$filtered_id = mysqli_real_escape_string($conn, $_GET['id']);
$sql = "SELECT * FROM topic WHERE id={$filtered_id}";
$rs = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($rs);
$article['title'] = $row['title'];
$article['description'] = $row['description'];
}
if ($_POST['title'] != null){
$sql_in = "INSERT INTO topic (title, description, created) VALUES ('{$_POST['title']}', '{$_POST['description']}', NOW())";
$rs_in = mysqli_query($conn, $sql_in);
if ($rs_in === false) {
$msg = mysqli_error($conn);
} else {
$msg = 'Success.';
}
} else {
$msg = 'Fill in';
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>WEB</title>
</head>
<body>
<h1>WEB</h1>
<ol>
<?=$list?>
</ol>
<details>
<summary>Create</summary>
<form action="./index.php" method="POST">
<p><input type="txt" name="title" placeholder="title"></p>
<p><textarea name="description" placeholder="description"></textarea></p>
<p><input type="submit"></p>
<p><?=$msg?></p>
</form>
</details>
</body>
</html>
<h2><?=$article['title']?></h2>
<?=$article['description']?>
</body>
</html>
In php realtime isn't a thing but there is a workaround you can use events services like pusher https://pusher.com/docs and receive the events in client side instantly .
there other website offers this so do your search before choosing them also you can always build your event server in node.js , c# , go

store gujarati data from csv to MySQL database using php

Following code which is used to browse csv file.
Fatch data from csv and store in a MySQL database.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
</head>
<body>
<form name="import" method="post" enctype="multipart/form-data">
કેમ છે: <input type="file" name="file" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
include ("connection.php");
if(isset($_POST["submit"]))
{
$file = $_FILES['file']['name'];
$handle = fopen($file, "r");
$c = 0;
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$name = $filesop[0];
$marks = $filesop[1];
mysql_query("set name utf8");
$query = "INSERT INTO temp (name, marks) VALUES ('".$name."','".$marks."')";
echo $query;
$sql = mysql_query($query);
}
}
?>
</div>
</body>
</html>
Following code is used connect database.
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$database = "test";
$conn = mysql_connect("$hostname","$username","$password") or die(mysql_error());
mysql_select_db("$database", $conn) or die(mysql_error());
?>
When I run code its stored data like "????????".
My CSV file like below
Following phpmyadmin version information
Following is my table structure
if you're getting stored ???????? in database, then,
You need to check the database collation first, change it to utf8_general_ci or utf8mb4_general_ci if simple utf_general_ci doesn't work.
Second, if collation is fine then it could also be possible that string is already in utf8 format, and you're converting it forcefully again.
Use following function to convert string to utf8.
function convToUtf8($str){
if( mb_detect_encoding($str,"UTF-8, ISO-8859-1, GBK")!="UTF-8" )
return iconv("gbk","utf-8",$str);
else
return $str;
}
Then in your code
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$name = convToUtf8($filesop[0]);
$marks = convToUtf8($filesop[1]);
//mysql_query("set name utf8"); No need to do this now
$query = "INSERT INTO temp (name, marks) VALUES ('$name','$marks')";
echo $query;
$sql = mysql_query($query);
}
and look here and set db collation

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

Query was empty while submitting the form

/Form design/
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<form name="form1" method="post" action=""><label><center>Register Form</center></label>
<p><center></center><label>Name:</label>
<input type="text" name="name"></center>
</p>
<p><label>Rollno:</label>
<input type="text" name="rno">
</p>
<p><label>Address:</label>
<input type="text" name="add">
</p>
<p>
<input type="submit" name="Submit" value="Submit">
</p>
</form>
/***********PHP******************/
/Form submission/
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("alpha") or die( "Unable select database");
// Check connection
// escape variables for security
$name = mysql_real_escape_string($_POST['name'],$con);
$rno = mysql_real_escape_string( $_POST['rno'],$con);
$add = mysql_real_escape_string($_POST['add'],$con);
$sql=mysql_query("INSERT INTO test (name, rno, add)
VALUES ('$name','$rno','$add')",$con);
$result=mysql_query($sql) or die(mysql_error());
if (!mysql_query($result,$con)) {
die(mysql_error($con));
}
echo "1 record added";
mysql_close($con);
?>
</body>
</html>
some one please help me with this error.
i am getting the message query was empty.
how can i fix this.
i am new to php and my sql.
i dont know how to solve this issue.
mysql_query should execute a query :
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("alpha") or die( "Unable select database");
// Check connection
// escape variables for security
$name = mysql_real_escape_string($_POST['name'],$con);
$rno = mysql_real_escape_string( $_POST['rno'],$con);
$add = mysql_real_escape_string($_POST['add'],$con);
$query = sprintf("INSERT INTO test (name, rno, add)
VALUES ('%s','%s','%s')", $name, $rno, $add);
$result = mysql_query($query, $con);
if (!$result) {
$message = 'Invalid request : ' . mysql_error() . "\n";
$message .= 'Your query : ' . $query;
die($message);
}
// #see http://php.net/manual/en/function.mysql-affected-rows.php
echo mysql_affected_rows() + " record added";
mysql_close($con);
?>
Try this
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("alpha") or die( "Unable select database");
// Check connection
// escape variables for security
$name = mysql_real_escape_string($_POST['name']);
$rno = mysql_real_escape_string( $_POST['rno']);
$add = mysql_real_escape_string($_POST['add']);
$sql=mysql_query("INSERT INTO test (name, rno, add) VALUES ('$name','$rno','$add')",$con);
if ($sql) {
echo "1 record added";
}
else {
die(mysql_error($con));
}
mysql_close($con);
First of all, if you have kept your html form code and php code in the same page, you will need a conditional operator to check whether the form has been submitted or not. In your code above, the php code are executed even when the form is not submitted.
Make sure your form data are fetched by using any of the following:
var_dump($_POST);
print_r($_POST);
If it displays the data you have entered then so far you are good.
In your code above you have:
$result=mysql_query($sql) or die(mysql_error());
When you have done the above, you will not need the following code as the die() function will do the same. And the following code will also make your query run twice.
if (!mysql_query($result,$con)) {
die(mysql_error($con));
}

Removing the first row in a csv file upload to mysql database

I have the following code for uploading a csv file to a mysql database. Its working just fine, but if the csv file contains a heading for each column its getting uploaded in the first row of the table. I want to remove the first row of the csv file while getting stored in the database. How can i do that ?
<?php
//connect to the database
$connect = mysql_connect("localhost","root","");
mysql_select_db("crm",$connect); //select the table
//
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]) {
mysql_query("INSERT INTO lead (name, lead_value, status) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."'
)
");
}
} while ($data = fgetcsv($handle,1000,",","'"));
//
//redirect
header('Location: import.php?success=1'); die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File with PHP & MySQL</title>
</head>
<body>
<?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?>
<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>
</body>
</html>
example code from what I'm using, and it should work because I'm using it in production environment
$handle = fopen("stuff.csv","r");
/* assuming that first row has collumns names */
$query = "INSERT INTO table(";
$cols = fgetcsv($handle,100000,';','"');
$query .= implode(", ",$cols).") VALUES";
$values = "";
/* cycle through each row and build mysql insert query */
while($data = fgetcsv($handle,100000,';','"')) {
$values .= " ( ";
foreach($data as $text) {
$values .= "'".$text."', ";
}
$values = substr($values,0,-2);
$values .= "), ";
}
/* remove last 2 chars */
$values = substr($values,0,-2);
$query .= $values;
echo $query;
fclose($handle);
Mind the fact that this script will return the mysql query... not execute it, so alter it to your needs.
I think you mean that you want to not insert the first row of the CSV data into your table. Working on that assumption (note that I'm not a PHP programmer, so the changes I've made should be taken as pseudocode):
if ($_FILES[csv][size] > 0) {
$first_time = true;
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($first_time == true) {
$first_time = false;
continue;
}
if ($data[0]) {
mysql_query("INSERT INTO lead (name, lead_value, status) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."'
)
");
}
} while ($data = fgetcsv($handle,1000,",","'"));
//redirect
header('Location: import.php?success=1'); die;
}
If I am understanding you correctly you want to remove the header row? I would use LOAD DATA instead of INSERT INTO
LOAD DATA INFILE '/tmp/test.csv' INTO TABLE test FIELDS TERMINATED BY ',' IGNORE 1 LINES;
LOAD DATA is vastly superior performance-wise than INSERT.
MySQL - LOAD DATA

Categories