I have written the following PHP code to load a CSV file into database. But the query isn't executing.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(mysqli_select_db($conn,"test"))
{
printf("Success");
}
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "LOAD DATA INFILE 'output.csv' INTO TABLE new COLUMNS TERMINATED BY ',' ENCLOSED BY '\"\' ESCAPED BY '\"\' " ;
printf($query);
if(mysqli_query($conn,$query))
{
printf("query executed");
}
mysqli_close($conn);
?>
Please tell me what is the problem. Thanks in advance.
I have a feeling this comes from a mangled conversion from regular text to PHP string:
ENCLOSED BY '\"\' ESCAPED BY '\"\'
This should probably be:
ENCLOSED BY '\"' ESCAPED BY '\"'
The query itself is invalid. You should be getting an error back.
Related
'LINES TERMINATED BY' PROBLEM - PHP, SQL database, CSV file'
Im learning how to update database with PHP, from local file.
It is working fine, except just the last entry from my CSV file is inserted into all fields in database table.
I've tried inspecting CSV with HEX, and also all thinkable versions of LINES TERMINATED BY (\r\n, \n etc.).
Here is my CSV file
This image shows the code was executed properly.
https://imgur.com/p13OAoj
Here is my PHP code:
$dbhost = 'hidden';
$dbuser = 'hidden';
$dbpass = 'hidden';
$dbname = 'hidden';
// connect to the database
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
mysqli_options($conn, MYSQLI_OPT_LOCAL_INFILE, true);
// check connection
if(!$conn){
echo 'Connection error: '. mysqli_connect_error();
}
// create temporary table
$create = 'CREATE TABLE tmp
(
name_id varchar(255),
phone varchar(255),
INDEX (name_id)
)';
// check if creation was successful
if(mysqli_query($conn, $create)){
echo "Records were updated successfully CREATE.";
} else {
echo "ERROR: Could not able to execute $create. " . mysqli_error($conn);
} ?><br><br><?php
// load data from local file into temp table
$load = "LOAD DATA LOCAL INFILE 'try1.csv'
INTO TABLE tmp
FIELDS TERMINATED BY ';'
LINES TERMINATED BY '\r\n' IGNORE 1 LINES
(#name_id, #phone)" ;
// check if load was successful
if(mysqli_query($conn, $load)){
echo "Records were updated successfully LOAD.";
} else {
echo "ERROR: Could not able to execute $load. " . mysqli_error($conn);
} ?><br><br><?php
// set/update temp table with info from csv file
$set = "UPDATE tmp SET
name_id = #name_id,
phone = #phone "
;
// check if update was successful
if(mysqli_query($conn, $set)){
echo "Records were updated successfully SET.";
} else {
echo "ERROR: Could not able to execute $set. " . mysqli_error($conn);
}
mysqli_close($conn);
I would expect all 4 entries in CSV file to be inserted, instead I get the last rows values in all 4 entries in database.
This image shows the result in my database table.
https://i.imgur.com/2lKB2Ix.png
You need to modify two things in your code:
You don't need to update your data if you just have added the data.
The names of the columns in your load data are incorrect (you shoulkd remove the #), so you are inserting null lines. (If you only have those two columns in your table, you don't need to specify the names, so you can remove them too.)
Modify your code as:
$dbhost = 'hidden';
$dbuser = 'hidden';
$dbpass = 'hidden';
$dbname = 'hidden';
// connect to the database
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
mysqli_options($conn, MYSQLI_OPT_LOCAL_INFILE, true);
// check connection
if(!$conn){
echo 'Connection error: '. mysqli_connect_error();
}
// create temporary table
$create = 'CREATE TABLE tmp
(
name_id varchar(255),
phone varchar(255),
INDEX (name_id)
)';
// check if creation was successful
if(mysqli_query($conn, $create)){
echo "Records were updated successfully CREATE.";
} else {
echo "ERROR: Could not able to execute $create. " . mysqli_error($conn);
} ?><br><br><?php
// load data from local file into temp table
$load = "LOAD DATA LOCAL INFILE 'try1.csv'
INTO TABLE tmp
FIELDS TERMINATED BY ';'
LINES TERMINATED BY '\r\n' IGNORE 1 LINES
(name_id, phone)" ;
// check if load was successful
if(mysqli_query($conn, $load)){
echo "Records were updated successfully LOAD.";
} else {
echo "ERROR: Could not able to execute $load. " . mysqli_error($conn);
} ?><br><br><?php
mysqli_close($conn);
I have a csv file and I am using LOAD DATA LOCAL INFILE command to load it inside mysql, but I've got no idea why it only reads 5 lines of it.
Here is my php code:
<?php
include "../config.php";
$conn = new mysqli( $servername, $username, $password, $dbname );
if ( $conn->connect_error ) {
die( "Connection failed: " . $conn->connect_error );
} //$conn->connect_error
$sql= "LOAD DATA LOCAL INFILE 'uploads/cell.csv'
INTO TABLE table3
CHARACTER SET UTF8
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'";
$result = $conn->query( $sql );
echo("Error description: " . mysqli_error($conn));
?>
and the csv file is attached in link below.
cell.csv
Mysql after executing the php code looks like this:
I finally figured it out by myself, the problem was /r/n, somr of lines finish with /r and some finish with /r/n, i chenged the code to:
<?php
include "../config.php";
$conn = new mysqli( $servername, $username, $password, $dbname );
if ( $conn->connect_error ) {
die( "Connection failed: " . $conn->connect_error );
} //$conn->connect_error
$sql= "LOAD DATA LOCAL INFILE 'uploads/cell.csv'
INTO TABLE table3
CHARACTER SET UTF8
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r'";
$result = $conn->query( $sql );
echo("Error description: " . mysqli_error($conn));
?>
and it fixed the problem.
I am having issues trying to create a new MySQL database in php,
my code is:
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = ‘somepassword’;
$conn = new mysqli($dbhost, $dbuser, $dbpass);
if(!$conn->connect_error )
{
die('Could not connect: %s' . $conn->connect_error);
}
echo "Connected successfully\n";
$sql = "CREATE DATABASE TUTORIALS2";
if($conn->query($sql)===TRUE){
echo "Created the database\n";
}
else {
echo "Failed to create the database".$conn->error;
}
//Close the database
$conn->close();
?>
MySQL connects fine but it won't allow me to create a new database. Not a clue what I'm doing wrong here. Any pointers would be greatly appreciated!
Second Edit:
I somehow missed this, apologies.
You have a mistake here:
if(!$conn->connect_error )
should be
if($conn->connect_error )
see here http://php.net/manual/en/mysqli.connect-error.php
Edit:
run this query SHOW GRANTS FOR 'root'#'localhost'; either from php or from PhpMyAdmin or similar and see if the user root has the privilege to create databases.
More here http://dev.mysql.com/doc/refman/5.0/en/show-grants.html
First of all you need to enable error_reporting and second you have some bad quotes on this line
$dbpass = ‘somepassword’;
replace like this
$dbpass = 'somepassword';
I am trying to import data from a CSV file to my table using PHP. I have tried using the exact same code without the backslash for ENCLOSED BY '"' on phpmyadmin and the import is successful.
I have also checked the user permissions for admin.
Here is my code:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$pdo = new PDO('mysql:dbname=mydatabase;host=localhost;charset=utf8', 'admin', 'admin');
$pdo->exec('SET CHARACTER SET utf8');
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try{
$query = $pdo->prepare("LOAD DATA LOCAL INFILE 'C:\feed.csv' IGNORE INTO TABLE tablename
fields terminated by ','
enclosed by '\"'
lines terminated by '\n'
IGNORE 1 LINES
(field1, field2, field3, field4)", array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));
$query->execute();
$query->fetchAll();
} catch (PDOException $e) {
echo 'error: ' . $e->getMessage();
}
?>
When running this code I am seeing this error:
General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.
I don't no what is wrong in your code but you can use my code it is help full to you I think
I have implement this code and it is tested code. I think it is very use full
You have follow some rule:-
1.your csv file according to database table name (ex: db table name is users then csv should be users.csv)
2.Your csv file's first row should be db table fields name (ex: Id, name etc) after the start your data entry
3.you can download data source class from :- http://code.google.com/p/php-csv-parser/ because i have require below the code: require_once 'CSV/DataSource.php';
<?php
ini_set('memory_limit','512M');
$dbhost = "localhost";
$dbname = "excel_import";
$dbuser = "root";
$dbpass = "";
$conn=mysql_connect ($dbhost, $dbuser, $dbpass) or die ("I cannot connect to the database because: " . mysql_error());
mysql_select_db($dbname) or die("Unable to select database because: " . mysql_error());
require_once 'CSV/DataSource.php';
$filename = "users.csv";
$ext = explode(".",$filename);
$path = "uploads/".$filename;
$dbtable = $ext[0];
import_csv($dbtable, $path);
function import_csv($dbtable, $csv_file_name_with_path)
{
$csv = new File_CSV_DataSource;
$csv->load($csv_file_name_with_path);
$csvData = $csv->connect();
$res='';
foreach($csvData as $key)
{
$myKey ='';
$myVal='';
foreach($key as $k=>$v)
{
$myKey .=$k.',';
$myVal .="'".$v."',";
}
$myKey = substr($myKey, 0, -1);
$myVal = substr($myVal, 0, -1);
$query="insert into ".$dbtable." ($myKey)values($myVal)";
$res= mysql_query($query);
}
if($res ==1)
{
echo "record successfully Import.";
}else{
echo "record not successfully Import.";
}
}
Pretty simple stuff, I know, but am getting an error
<?php
session_start();
$dbhost = "###"; // this will ususally be 'localhost', but can sometimes differ
$dbname = "###"; // the name of the database that you are going to use for this project
$dbuser = "###"; // the username that you created, or were given, to access your database
$dbpass = "###"; // the password that you created, or were given, to access your database
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
mysql_select_db("###", $con);
$safe_email = mysql_real_escape_string($_POST['email']);
$sql="INSERT INTO register (email) VALUES ('{$safe_email}')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
$con is not defined anywhere in your code, before you use it in the query call. You should have:
$con = mysql_connect(...) or die(mysql_error());
Beyond that, your code is WIDE open to SQL injection attacks. You should have:
$safe_email = mysql_real_escape_string($_POST['email']);
$sql="INSERT INTO register (email) VALUES ('{$safe_email}')";
Assuming the following:
You don't have a lot of experience with PHP
The information that has been provided to you is correct
This is an example script and you know the values that need to be substituted for $dbname, $dbhost, $dbuser and $dbpass
Please try the following and report back if you get any output at all to screen:
<?php
session_start();
print "Connecting and inserting email: ".$_POST['email']."...";
$dbhost = "###"; // this will ususally be 'localhost', but can sometimes differ
$dbname = "###"; // the name of the database that you are going to use for this project
$dbuser = "###"; // the username that you created, or were given, to access your database
$dbpass = "###"; // the password that you created, or were given, to access your database
$con = mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
$safe_email = mysql_real_escape_string($_POST['email']);
$sql="INSERT INTO register (email) VALUES ('{$safe_email}')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
print "success! Inserted email with row id: ".mysql_insert_id();
mysql_close($con)
?>
this may just be me but you should but strings on a single line or use the concatenation (.) for the strings
$sql="INSERT INTO register (email) VALUES ('$_POST[email]')";
Other than that you should clean the information before adding it into the database otherwise your asking for sql injection attacks.
now to the actual problem. your using a variable that is undefined called conn. i am assuming your referencing the connection made, but you never set that variable to the connection like so
$conn = mysql_connect($dblocal,$dbuser,$dbpass) or die(xxx);