0

I am trying to get all data fields name and data types from an array, but the query is not working.

<?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;
?>
2

This is a code review question more than a WordPress question. Please post these in the Code Review Stack Exchange in the future.

You have a couple things wrong or not according to best practices. Comments inline for where I made changes.

$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 );
  • 1
    Thank you very much for the help, Mike :-) But $sql = rtrim( $sql, ',' ); is not working for last comma so i replaced it with -> $sql = substr(trim($sql), 0, -1); – gaurav mishra Apr 23 at 4:52
  • Thanks for pointing that out. It was missing a space. I edited my answer. – MikeNGarrett Apr 23 at 13:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.