Following is my code where I am trying to run the load query, but it's not running because of mismanaged quotes in the $qry string. Please explain how I can correct the query so that it can execute.
<?php
include 'connection.php';
$list=array();
//array_push($list,"304_updated_24may.csv");
array_push($list,"filename1.csv");
array_push($list,"filename2.csv");
array_push($list,"filename3.csv");
array_push($list,"filename4.csv");
try
{
foreach($list as $array)
{
echo 'hi';
$qry='LOAD DATA LOCAL INFILE '.$array.' INTO TABLE tablename FIELDS TERMINATED BY ',' ENCLOSED BY '/"' LINES TERMINATED BY '\n' IGNORE 1 ROWS';
print($qry);
print($qry);
$sqlvar= mysqli_query($mysqli, $qry) or printf("Errormessage2: %s\n", $mysqli->error);
}
}
catch(Exception $e)
{
var_dump($e);
}
?>
Don't Panic is rigth above. I did a similar solution. The following is what i did. I used pdo->quote() to escape my quotations. Should get around your problem.
$databasehost = "your database host";
$databasename = "your database name";
$databasetable = "table name";
$databaseusername = "database username";
$databasepassword = "database password";
$fieldseparator = ",";
$lineseparator = "\r\n";
$enclosedby = '\"'; // notice that we escape the double quotation mark
$csvfile = "your_csv_file_name.csv"; // this is your $list of csv files... replace as $list = array(); and array_push into list.
// check to see if you have the file in the first place
if(!file_exists( $csvfile )) {
die( "File not found. Make sure you specified the correct path." );
}
try {
$pdo = new PDO( "mysql:host=$databasehost;dbname=$databasename",
$databaseusername, $databasepassword,
array(
PDO::MYSQL_ATTR_LOCAL_INFILE => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
} catch ( PDOException $e ) {
die("database connection failed: ".$e->getMessage());
}
// Load your file into the database table, notice the quote() function, protects you from dangerous quotes
$qry = $pdo->exec( "
LOAD DATA LOCAL INFILE " . $pdo->quote( $csvfile ) . " INTO TABLE $databasetable FIELDS TERMINATED BY " . $pdo->quote( $fieldseparator ) .
" OPTIONALLY ENCLOSED BY " . $pdo->quote( $enclosedby ) .
" LINES TERMINATED BY " . $pdo->quote( $lineseparator ) );
Related
I am trying to use this code to import a csv file into my MySQL database:
... Thanks for solved that question!! ....
What am I doing wrong?
Guys I could solved that problem but now... I have an other problem, this is the code now:
<?php
$databasehost = "localhost";
$databasename = "cauctti";
$databasetable = "sample";
$databaseusername="root";
$databasepassword = "toor";
$fieldseparator = ";";
$lineseparator = "\r|n";
$csvfile = "Reporting.csv";
if(!file_exists($csvfile)) {
die("File not found. Make sure you specified the correct path.");
}
try {
$pdo = new PDO("mysql:host=$databasehost;dbname=$databasename",
$databaseusername, $databasepassword,
array(
PDO::MYSQL_ATTR_LOCAL_INFILE => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
)
);
} catch (PDOException $e) {
die("database connection failed: ".$e->getMessage());
}
$affectedRows = $pdo->exec("
LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." INTO TABLE `$databasetable`
FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)."
LINES TERMINATED BY ".$pdo->quote($lineseparator));
echo "Loaded a total of $affectedRows records from this csv file.\n";
?>
When I try to run it, only insert one row on the table...
Loaded a total of 1 records from this csv file.
Why it only gets one row when my csv file have like 5.000 entries...
As found here
You should set CHARACTER SET UTF8 in your query.
Example:
LOAD DATA INFILE 'file'
IGNORE INTO TABLE table
CHARACTER SET UTF8
FIELDS TERMINATED BY ';'
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
Have a look here --> Here
<?php
$table = "tableName";
$fileName = "States.csv";
$ignoreFirstRow = 1;
if (($handle = fopen($fileName, "r")) !== FALSE){
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
if($ignoreFirstRow != 1){
$sql = "insert into ".$table." values(";
$sql .= '"'.implode('","',$data).'"';
echo "".$sql.');';
$sql = "";
}
$ignoreFirstRow++;
}
fclose($handle);
}
?>
I have a .sql file and want to replace the already existing database by clicking a button. Everything works fine. Except the create query. Is there any query or command to import whole databases?
$filename = 'file.sql';
// MySQL host
$mysql_host = 'localhost';
// MySQL username
$mysql_username = 'user';
// MySQL password
$mysql_password = 'pw';
// Database name
$mysql_database = 'dbName';
// Connect to MySQL server
mysql_connect($mysql_host, $mysql_username, $mysql_password) or die('Error connecting to MySQL server: ' . mysql_error());
// Select database
mysql_select_db($mysql_database) or die('Error selecting MySQL database: ' . mysql_error());
$drop_db = "DROP DATABASE dbName";
mysql_query($drop_db) or die ("error");
$create_db = "";
I got it. The solution is to drop the tables not the whole database.
function resetClient() {
$erg = false;
try {
// get all tablenames
$sql = "SHOW TABLES FROM dbName";
$res = $this->conn->query($sql);
$this->conn->query("SET FOREIGN_KEY_CHECKS=0");
// drop all tables in db
if (is_object($res)) {
if (($res->num_rows > 0)) {
while ($row = $res->fetch_row()) {
$this->conn->query ("DROP TABLE " . $row[0]);
}
}
}
$this->conn->query("SET FOREIGN_KEY_CHECKS=1");
//pause
time_nanosleep(0, 250000000);
// create tables from script
$sql = file_get_contents('./scripts/file.sql');
$this->conn->multi_query($sql);
$erg = true;
error_log(date("Y-m-d H:i:s")." - DB resetted\n", 3,
"./scripts/success.log");
} catch (Exception $e) {
// log
error_log(date("Y-m-d H:i:s")." - DB error\n"
. "resetClientDB() \n"
. "Reset error \n"
. $e->getMessage() . "\n" , 3,
"./scripts/error.log");
}
return $erg;
}
You could try something like:
$cmds=array_filter( file( $filename ) );
foreach( $cmds as $cmd ){
echo $cmd;
}
If that looks ok substitute the echo for mysql_query( $cmd )... totally untested btw.
$sql=array();
$sourcefile='C:\data\db_20101222_0957.sql';
$cmds = file( $sourcefile, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES );
foreach( $cmds as $cmd ){
if ( substr( $cmd, 0, 2) == '--' || $cmd == '' || substr( $cmd,0, 2)=='/*' ) continue;
$sql[]=$cmd;
if ( substr( trim( $cmd ), -1, 1 ) == ';' ){
/* Query */
$query=implode( PHP_EOL, $sql );
/* Execute query */
echo '<pre>',$query,'</pre>';
$sql=array();
}
}
I have a func.php file that grabs three .txt files from my server and inputs the data into a table in a MySQL database. I recently upgraded my PHP to 5.4 from 5.3 and this has caused an issue where it doesn't pull in the .txt files anymore but just deletes the table. In the update_training_db function, it runs empty_table but not move_file and load_csv. This code was working in 5.3 but I am not sure why it isn't grabbing the text files anymore. Can anyone help?
The whole PHP script consists of 4 functions as seen in the whole code. empty_table, move_file, load_csv, and update_training_db to execute everything.
The Problem:
function update_training_db($dbt){
empty_table($dbt, 'customers');
move_file('/training/TrainingCustomerList.txt');
load_csv($dbt, '/training/TrainingCustomerList.txt', 'customers');
}
Whole file:
<?php
header('Content-Type: application/json; charset=UTF-8');
$argv = $_SERVER['argv'];
$totalArgv = count($argv);
// Use PDO to connect to the DB
$dsn_training = 'mysql:dbname=training;host=127.0.0.1';
$user = 'training';
$password = 'training';
try {
$dbt = new PDO($dsn_training, $user, $password);
$dbt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo 'Connected to SQL Server';
}
function empty_table($dbconn, $tablename){
try{
$sql = "TRUNCATE TABLE " . $tablename;
$sth = $dbconn->prepare($sql);
//$sth->bindParam(':tablename', $tablename, PDO::PARAM_STR);
// The row is actually inserted here
$sth->execute();
//echo " [+]Table '" . $tablename . "' has been emptied.<br>";
$sth->closeCursor();
}
catch(PDOException $e) {
die_with_error($e->getMessage());
}
}
function move_file($filename){
$source ="/public_html/b3/" . $filename;
$dest = "/public_html/includes/sfupdate/" . $filename;
if(!copy($source, $dest)){
throw new Exception("Failed to copy file: " . $filename);
}
else{
//echo "Successfully moved $filename.<br>";
}
}
function move_files(){
try {
move_file('training/TrainingCustomerList.txt');
}
catch(Exception $e){
die_with_error($e->getMessage());
}
//sleep(1);
//Return JSON
$return["json"] = json_encode($return);
//echo json_encode($return);
}
function load_csv($dbconn, $filename, $tablename){
try{
$sql = "LOAD DATA LOCAL INFILE '/includes/sfupdate/" . $filename . "' INTO TABLE " . $tablename . " FIELDS TERMINATED BY '\\t' ENCLOSED BY '\"' ESCAPED BY '\\\' LINES TERMINATED BY '\\n'";
$sth = $dbconn->prepare($sql);
// The row is actually inserted here
$sth->execute();
//echo " [+]CSV File for '" . $tablename . "' Table Imported.<br>";
$sth->closeCursor();
}
catch(PDOException $e) {
die_with_error($e->getMessage());
}
}
function update_training_db($dbt){
empty_table($dbt, 'customers');
move_file('/training/TrainingCustomerList.txt');
load_csv($dbt, '/training/TrainingCustomerList.txt', 'customers');
}
I am trying to adapt my code, which works in a SELECT, to perform an UPDATE. Here, there is no error, but it does not update anything, it even does not even enter the loop. It is supposed to update the room type for the chosen days ($value).
I echoed all values to check them up and they are correct.
$bdd = mysqli_connect('localhost', 'root', '', 'webpage')
$roomty = 1;
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
}
foreach ($_SESSION['datesBooked_1_month'] as $key => $value)
{
$stmt = mysqli_stmt_init($bdd);
if ( mysqli_stmt_prepare( $stmt , "UPDATE '".$_SESSION['tab_from_month_year']."'
SET '".$_SESSION['roomtype_x']."'='".$_SESSION['roomtype_x']."' + ? WHERE day = ?"))
{
mysqli_stmt_bind_param( $stmt ,'is', $roomty , $value );
mysqli_stmt_execute( $stmt );
mysqli_stmt_close($stmt);
echo " Booked !<br /> ";
}
}
Please try the following code with the new MySql driver of PHP.
you put the quote for a integer value, that is wrong
do you named column with numbers? That is not comfortable.
Are you sure that $value is a string?
Why did you use $key => $value in the foreach loop?
Here the code:
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=webpage;host=127.0.0.1';
$user = 'root';
$password = 'dbpass'; #put here yor password
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
foreach $_SESSION['datesBooked_1_month'] as $value) {
#I hope that following variables don't contain space
$query = "UPDATE " .$_SESSION['tab_from_month_year'];
$temp = $_SESSION['roomtype_x'] + $roomty ;
#you wrote that $value is a string, are you sure?
$query .= " SET ".$_SESSION['roomtype_x']. "=$temp WHERE day='$value'" ;
$dbh->query($query);
}
I found out, the problem was the single quotes before the double quotes. It seems to be working very well with only double quotes like this :
if ( mysqli_stmt_prepare( $stmt , "UPDATE ".$_SESSION['tab_from_month_year']." SET ".$_SESSION['roomtype_x']." = ".$_SESSION['roomtype_x']." + ? WHERE day = ?"))
If this is the full code you need to select a database, currently the statement is being sent to the server but not to any database, there for you get no errors. You should use:
mysqli_select_db("You database goes here");
I'm having a problem with my update script. Basically I enter values into textboxes and when I click on 'Add' these values get added to the database.
At the moment it is allowing me to enter intergers and these getting added to the database but when I try to add text it doesn't. The database field types are set to varchar(20) and this is my PHP code:
public function insert($tableName,$fieldArray,$fieldValues) {
$pdo = new SQL();
$dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);
$this->sql = "INSERT INTO " . $tableName . " (".implode(',', $fieldArray).") VALUES (".implode(',', $fieldValues).")";
try {
// Query
$stmt = $dbh->prepare($this->sql);
$stmt->execute();
$count = $stmt->rowCount();
echo $count.' row(s) inserted by SQL: '.$stmt->queryString;
$stmt->closeCursor();
}
catch (PDOException $pe) {
echo 'Error: ' .$pe->getMessage(). 'SQL: '.$stmt->queryString;
die();
}
// Close connection
$dbh = null;
}
Please let me know what I am doing wrong! :)
Change the sql query line to:
$this->sql = "INSERT INTO " . $tableName . " (`".implode('`, `', $fieldArray)."`) VALUES ('".implode("', '", $fieldValues) . "')";
The thing is you are not escaping strings with quotes. Like 'someText'
You need to enclose your fields into quotes.
Put the text as such
$text = "text"; //How you're doing it now
$text = "'text'"; //How you ought to (after sql escaping)
Or try this:
$this->sql = "INSERT INTO " . $tableName . " (`".implode('`,`', $fieldArray)."`) VALUES ('".implode("','", $fieldValues)."')";