我有一个我在Wordpress中编写的php函数。我正在将一个CSV文件放在与我的插件功能相同的文件夹中,并尝试将其输入数据库。
我在wp-config.php中启用了错误报告 以及我自己的php
我收到一条错误消息。
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'wuno_inventory' already exists
我的代码会删除表并创建它。分别和一起测试。一旦我进入导入csv文件部分没有任何反应。
所以我的代码正在被阅读,但显然没有执行。
任何想法都将不胜感激。非常感谢你。
function productsExec() {
$hostname='localhost';
$username='username';
$password='password';
$database='databaseName';
$table_name = "wuno_inventory";
// path where your CSV file is located
define('CSV_PATH','');
// Name of your CSV file
$csv_file = CSV_PATH . "inventory.csv";
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$database",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "DROP TABLE IF EXISTS $table_name";
$dbh->query($sql);
$sql = "CREATE TABLE " . $table_name . " (
id int(8) NOT NULL AUTO_INCREMENT,
wuno_product varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
wuno_description varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
wuno_alternates varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
wuno_onhand varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
wuno_condition varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;";
$dbh->query($sql);
if (($handle = fopen($csv_file, "r")) !== FALSE) {
fgetcsv($handle);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
$col[$c] = $data[$c];
}
$col1 = $col[0];
$col2 = $col[1];
$col3 = $col[2];
$col4 = $col[3];
$col5 = $col[4];
// SQL Query to insert data into DataBase
$query = "INSERT INTO " . $table_name . "(wuno_product, wuno_description, wuno_alternates, wuno_onhand, wuno_condition)
VALUES('".$col1."','".$col2."','".$col3."','".$col4."','".$col5."')";
$results = $dbh->query( $query );
}
fclose($handle);
}
if ($dbh->query($sql)) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
}
else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
csv文件
Product,Description,Alternates,Onhand,Condition
8855K5,,MS21026-B211,12,12
M39029/5-117,,,13,13
Q4559,,PROD CODE: 40579,1,1
,,40579,,
RESTOCKING CHARGE,,,1,1
TAS8732-1C2,,,7,7
TEST REPORTS,,,6,6
答案 0 :(得分:0)
我从你已经尝试wpdb->query($sql);
??
编辑:
在$ sql查询字符串的末尾添加分号:)
$sql = "DROP TABLE IF EXISTS $table_name;"; // see the ; inside the quotes
和
$query = "INSERT INTO " . $table_name . " (wuno_product, wuno_description, wuno_alternates, wuno_onhand, wuno_condition)
VALUES('".$col1."','".$col2."','".$col3."','".$col4."','".$col5."');";
//从最后一个角色添加了第3个:;在引号内,以及'('
之前的空格最后,就我所知,$ col4和$ col5是未定义的,所以这可能会导致整个查询无效。