可以使用数组和循环创建一个WordPress表吗?

时间:2019-04-22 作者:gaurav mishra

我试图从数组中获取所有数据字段的名称和数据类型,但查询不起作用。

<?php
$cr_table_array = array(
array(
\'data_field\' => "id",
\'data_type\' => "mediumint(12) NOT NULL AUTO_INCREMENT"
),
array(
\'data_field\' => "your_name",
\'data_type\' => "varchar(200) NOT NULL"
),
array(
\'data_field\' => "your_eamil",
\'data_type\' => "varchar(200) NOT NULL"
)
);


global $wpdb;
$sql =  "CREATE TABLE IF NOT EXISTS " . $wpdb->prefix.\'credofy_contact_form\'. " (
foreach($cr_table_array as $file) {
    echo $file[\'data_field\'] .\' \'. $file[\'data_type\'].\' \'
    }
             PRIMARY KEY (id));";
$wpdb->query($sql);
require_once(ABSPATH . \'wp-admin/includes/upgrade.php\');
dbDelta($sql);
echo $sql;
?>

1 个回复
SO网友:MikeNGarrett

这是一个代码审查问题,而不是WordPress问题。请在Code Review Stack Exchange 未来

根据最佳实践,您有两件事做错了或不正确。我所做更改的内联注释。

$cr_table_array = array(
    array(
        \'data_field\' => \'id\',
        // Add primary key here to allow you to keep definitions in one place.
        \'data_type\'  => \'MEDIUMINT(12) NOT NULL AUTO_INCREMENT PRIMARY KEY\',
    ),
    array(
        \'data_field\' => \'your_name\',
        \'data_type\'  => \'VARCHAR(200) NOT NULL\',
    ),
    array(
        // misspelled
        \'data_field\' => \'your_email\',
        \'data_type\'  => \'VARCHAR(200) NOT NULL\',
    ),
);


global $wpdb;
// Use .= to append your statement pieces into a single variable.
// Use curly braces for inline vaiables.
$sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}credofy_contact_form( ";
foreach ( $cr_table_array as $file ) {
    $sql .= $file[\'data_field\'] . \' \' . $file[\'data_type\'] . \', \';
}
// Remove the final comma to prevent sql errors.
$sql  = rtrim( $sql, \', \' );
$sql .= \')\';

// This will create your database. You can stop here.
$wpdb->query( $sql );

global $wpdb;

$statement = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}credofy_contact_form( ";
foreach ( $cr_table_array as $file ) {
    $statement .= $file[\'data_field\'] . \' \' . $file[\'data_type\'] . \', \';
}
$statement  = rtrim( $statement, \', \' );
$statement .= \' )\';

$wpdb->query( $statement );

相关推荐

WordPress中MySQL的CRUD前端

我希望我来对地方了。我想用MySQL数据库的前端丰富我的Wordpress站点,我将其托管在与我的WP站点相同的服务器上。实际上,我已经将(以前的)MS Access数据库迁移到MySQL,并且我确实使用wpdatables获得了对它的“表读/写”访问权限。我想,我要找的基本上是WP上MySQL的CRUD接口。我知道,我可以自己用很多php代码来构建它。但必须有一种方法,使用多种形式的引擎(重力、wp形式、强大……)并让好看的表单显示单个表记录,允许编辑它们,然后将它们写回MySQL数据库。。。这里有什么