以下是我尝试运行加载查询的代码,但由于$qry
字符串中的管理不当,它没有运行。请解释我如何纠正查询以便它可以执行。
<?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);
}
?>
答案 0 :(得分:0)
不要惊慌失措。我做了类似的解决方案。以下是我的所作所为。我用pdo-&gt; quote()来逃避我的引用。应该解决你的问题。
$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 ) );