2014-09-24 35 views
0

所以我试图让这个函数执行一个从数据库导出的.sql文件。该功能的基本作用是在所需表格为空时导入表格数据。我已经做了一个函数,检查表是否为空,但不能让这个表运行。到目前为止,我想出了这个..如果不存在导入表数据的函数

function importdata($file) { 

global $wpdb; 
require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); 

// Name of the file 
$plugindir = dirname(__FILE__); 
$filename = $plugindir . '/metaboxes/database/' . $file; 

// Temporary variable, used to store current query 
$templine = ''; 
// Read in entire file 
$lines = file($filename); 

// Loop through each line 
foreach ($lines as $line) 
{ 
// Skip it if it's a comment 
if (substr($line, 0, 2) == '--' || $line == '') 
continue; 

// Add this line to the current segment 
$templine .= $line; 



// If it has a semicolon at the end, it's the end of the query 
if (substr(trim($line), -1, 1) == ';') 
{ 
    // Perform the query 
    $wpdb->query('$line'); 

    // Reset temp variable to empty 
    $templine = ''; 
    echo "if is running"; 
    } 
} 
} 

我在if条件添加回声来检查它是否达到了条件。显然,它是达到如果条件,但不添加行。

+0

哪个'if'条件?另外,“添加行”的部分在哪里?在打开'<?php'标签后立即在文件顶部添加错误报告 'error_reporting(E_ALL); ini_set('display_errors',1);'看看它是否产生任何东西。 – 2014-09-24 22:30:14

+0

'if(substr(trim($ line),-1,1)==';')' – 2014-09-24 22:31:38

+0

@ Fred-ii-好吧让我看看 – 2014-09-24 22:34:56

回答

1

对于那些需要为此的答案,问题是在wpdb->查询。我所做的解决这个问题的方法是用$ templine替换$ line。发生这个问题是因为$ line只有';'而其他数据存储在$ templine中。正在运行的最终功能是...

function importdata($file) { 

global $wpdb; 
require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); 

// Name of the file 
$plugindir = dirname(__FILE__); 
$filename = $plugindir . '/metaboxes/database/' . $file; 

// Temporary variable, used to store current query 
$templine = ''; 
// Read in entire file 
$lines = file($filename); 

// Loop through each line 
foreach ($lines as $line) 
{ 
// Skip it if it's a comment 
if (substr($line, 0, 2) == '--' || $line == '') 
continue; 

// Add this line to the current segment 
$templine .= $line; 



// If it has a semicolon at the end, it's the end of the query 
if (substr(trim($line), -1, 1) == ';') 
{ 
    // Perform the query 
    $wpdb->query($templine); 
    // Reset temp variable to empty 
    $templine = ''; 
    echo "if is running"; 
    } 
} 
} 
+0

+1自我解决。很高兴听到您发现错误。 – 2014-09-24 23:14:25

+1

@ Fred-ii-感谢您的帮助... – 2014-09-24 23:21:58

+0

不客气Fahad,*欢呼声* – 2014-09-24 23:22:59