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 ) );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.