导入表数据的功能(如果不存在)

时间:2014-09-24 22:21:17

标签: php mysql wordpress

所以我试图创建这个函数,它执行从数据库导出的.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条件中添加了一个echo来检查它是否达到了条件。显然,它正在达到if条件但不添加行..

1 个答案:

答案 0 :(得分:1)

对于需要此答案的人来说,问题出在wpdb->查询中。我所做的一切都是用$ templine替换了$ line。之所以出现这个问题,是因为$ line只获得了&#39 ;;'在文件中,而其他数据存储在$ 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";
    }
 }
}