dbDelta no está creando tablas

12

Pasé por muchos subprocesos, página de códice e intenté jugar con muchas cosas, pero mi código no parece estar creando las tablas. Y no soy capaz de averiguar a dónde me voy mal. Revisé booking_db_version en la base de datos, se actualiza cuando lo actualizo en el archivo.

Aquí está el código

global $booking_db_version;
$booking_db_version = "1.0.0";

function booking_install() {
    global $wpdb;
    global $booking_db_version;
    global $tableprefix;
    $installed_version = get_option('booking_db_option');

    $tableprefix = $wpdb->prefix . 'booking_';

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

    if ( $installed_version !== $booking_db_version ) {
        /* Create table for packages */
        $packagetable = $tableprefix . 'packages';
        $sql = "create table  $packagetable (
            id mediumint(9) NOT NULL AUTO_INCREMENT, 
            name text NOT NULL, 
            description text NOT NULL, 
            city1 text NOT NULL, 
            city2 text NOT NULL,
            PRIMARY KEY  (id)
        );";
        dbDelta($sql);

        /* Create table for hotels */
        $hoteltable = $tableprefix . 'hotels';
        $sql = "create table $hoteltable (
            id mediumint(9) NOT NULL AUTO_INCREMENT, 
            name text NOT NULL, 
            city text NOT NULL, 
            price decimal(10,2) NOT NULL,
            PRIMARY KEY  (id)
        );";
        dbDelta($sql);

        /* Create table for addons */
        $addontable = $tableprefix . 'addons';
        $sql = "create table $addontable (
            id mediumint(9) NOT NULL AUTO_INCREMENT, 
            name text NOT NULL, 
            addongroup text NOT NULL, 
            price decimal(10,2) NOT NULL,
            PRIMARY KEY  (id)
        );";
        dbDelta($sql);

        /* Create table for addon groups */
        $addongrouptable = $tableprefix . 'addon_groups';
        $sql = "create table $addongrouptable (
            id mediumint(9) NOT NULL AUTO_INCREMENT, 
            name text NOT NULL, 
            perhead text NOT NULL,
            PRIMARY KEY  (id)
        );";
        dbDelta($sql);

        update_option('booking_db_version', $booking_db_version);
    }
}
register_activation_hook(__FILE__, 'booking_install');
    
pregunta mehulved 26.12.2012 - 10:41

4 respuestas

14

De WordPress-codex sobre dbDelta :

La función dbDelta examina la estructura de tabla actual, la compara con la estructura de tabla deseada y agrega o modifica la tabla según sea necesario, por lo que puede ser muy útil para las actualizaciones (consulte wp-admin / upgrade-schema.php para más ejemplos de cómo usar dbDelta). Tenga en cuenta que la función dbDelta es bastante exigente, sin embargo. Por ejemplo:

  • Debe poner cada campo en su propia línea en su declaración SQL.
  • Debe tener dos espacios entre las palabras CLAVE PRIMARIA y la definición de su clave principal.
  • Debe usar la palabra clave CLAVE en lugar de su sinónimo ÍNDICE y usted debe incluir al menos una CLAVE.
  • No debe usar apóstrofes ni comillas invertidas alrededor de los nombres de los campos.

Con estas advertencias, aquí están las siguientes líneas en nuestra función, que en realidad crearán o actualizarán la tabla. Deberá sustituir su propia estructura de tabla en la variable $ sql.

He cambiado tu sql: "create table $packagetable (

A esto: "CREATE TABLE " . $packagetable . " (

Aquí hay una copia de trabajo de su código:

global $booking_db_version;
$booking_db_version = "1.0.0";

function booking_install() {
    global $wpdb;
    global $booking_db_version;
    global $tableprefix;
    $installed_version = get_option('booking_db_option');

    $tableprefix = $wpdb->prefix . 'booking_';

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

    if ( $installed_version !== $booking_db_version ) {
        // Create table for packages 
        $packagetable = $tableprefix . 'packages';
        $sql = "CREATE TABLE " . $packagetable . " (
            id INT NOT NULL AUTO_INCREMENT, 
            name TEXT NOT NULL, 
            description TEXT NOT NULL, 
            city1 TEXT NOT NULL, 
            city2 TEXT NOT NULL,
            PRIMARY KEY  (id)
        ) ". $charset_collate .";";
        dbDelta($sql);

        // Create table for hotels 
        $hoteltable = $tableprefix . 'hotels';
        $sql = "CREATE TABLE " . $hoteltable . " (
            id mediumint(9) NOT NULL AUTO_INCREMENT, 
            name text NOT NULL, 
            city text NOT NULL, 
            price decimal(10,2) NOT NULL,
            PRIMARY KEY  (id)
        ) ". $charset_collate .";";
        dbDelta($sql);

        // Create table for addons 
        $addontable = $tableprefix . 'addons';
        $sql = "CREATE TABLE " . $addontable . " (
            id mediumint(9) NOT NULL AUTO_INCREMENT, 
            name text NOT NULL, 
            addongroup text NOT NULL, 
            price decimal(10,2) NOT NULL,
            PRIMARY KEY  (id)
        ) ". $charset_collate .";";
        dbDelta($sql);

        // Create table for addon groups 
        $addongrouptable = $tableprefix . 'addon_groups';
        $sql = "CREATE TABLE " . $addongrouptable . " (
            id mediumint(9) NOT NULL AUTO_INCREMENT, 
            name text NOT NULL, 
            perhead text NOT NULL,
            PRIMARY KEY  (id)
        ) ". $charset_collate .";";
        dbDelta($sql);

        update_option('booking_db_version', $booking_db_version);
    }
}
register_activation_hook(__FILE__, 'booking_install');
    
respondido por el Pontus Abrahamsson 26.12.2012 - 13:35
0

Puede probar esta función :

$table_name = "ratings";

$table_columns = "id INT(6) UNSIGNED AUTO_INCREMENT,
                    rate tinyint(1) NOT NULL,
                    ticket_id bigint(20) NOT NULL,
                    response_id bigint(20) NOT NULL,
                    created_at TIMESTAMP";

$table_keys = "PRIMARY KEY (id),
                    KEY ratings_rate (rate),
                    UNIQUE KEY ratings_response_id (response_id)";

create_table($table_name, $table_columns, $table_keys);
    
respondido por el motto 31.03.2016 - 14:58
0

El uso de 'CREAR TABLA' en lugar de 'crear tabla' solucionó el problema para mí.

    
respondido por el Kallol 03.07.2017 - 09:25
-2

Las palabras clave de SQL, como CREAR TABLA y ACTUALIZAR, deben estar en mayúsculas. así que cambia la línea de crear tabla a:

"CREATE TABLE " . $packagetable . "( 

y

id mediumint(9) NOT NULL AUTO_INCREMENT,

a:

id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,

o esto:

name text NOT NULL, 

a:

name TEXT NOT NULL, 

y así sucesivamente

    
respondido por el shirin niki 08.01.2017 - 14:22

Lea otras preguntas en las etiquetas