• Hello friends,

    I did a form and through a plugin i coded in php, iā€™d like to insert the result of this form into my wordpress database. But i run into a problem cause nothing is inserted in my database despite the log not pointing any error. My log tell me the insertion was sucessfull. However, my table is empty.

    This is my php code that is supposed to insert it

    echo "<pre>";
    echo "Table name is :" . $table_name;
    echo "</pre>";
    
         // Create an array with the reply
    $reply= array();
    
    // Liste des champs que vous voulez insƩrer
    $champs = ['FirstName', 'LastName', 'Adress'];
    
    foreach ($champs as $champ) {
        if (!empty($_POST[$champ])) {
            $reply[$champ] = sanitize_text_field($_POST[$champ]);
        }
    }
    
    $result = $wpdb->insert($table_name, $reply);
    
    if ($result === false) {
      echo "Error : " . $wpdb->last_error;
    } else {
        echo "Data insertion was sucessfull";
    }
    
    echo "<pre>";
    print_r($wpdb->last_query);
    echo "</pre>";
    
    echo "<pre>";
    echo $wpdb->last_error;
    echo "</pre>";
    
    }
    }

    So what i get as result of all thoses echos is :

    The correct name of my table which is : wp_inscriptions_majeurs

    Then :

    Data insertion was sucessfull

    Then nothing for print_r($wpdb->last_query) :

    INSERT INTO wp_inscriptions_majeurs (FirstName, LastName, Adress) VALUES ('Test', 'Test', '21 Boulevard de Larramet')
    

    My echo $wpdb->last_error return an empty bloc. There is literally no error.

    Can someone help me on this ?

Viewing 13 replies - 1 through 13 (of 13 total)
  • Hello @louma333,

    Based on the code, it seems that you’re trying to insert data into a database table using PHP and WordPress. whatever, you are not getting any error message. Here are a few things you can check.

    Verify your table name: Make sure that $table_name variable contains the correct table name. Double-check the spelling and case sensitivity.

    Check your database connection: Ensure that you have established a proper connection to the database using WordPress’s $wpdb object. Make sure you have included the necessary WordPress files and initialized the $wpdb object before executing the insert query.

    Check field names: Confirm that the field names in the $champs array (FirstName, LastName, Adress) match the actual column names in the database table. Again, verify the spelling and case sensitivity.

    Verify form data: Ensure that the form fields with names FirstName, LastName, and Adress are present and not empty in the $_POST data. You can add some debug statements to check the values of $_POST[$champ] before the if condition.

    Moderator bcworkz

    (@bcworkz)

    Using the phpMyAdmin app, navigate to the WP DB and your table. Open the Privileges tab for that table and check the privileges assigned to the user that WP has defined in wp-config.php. The user should have either all privileges or at least the privileges needed to adequately manage the data in the DB: select, update, insert, etc….

    Thread Starter louma333

    (@louma333)

    Hello to both of you.
    Thanks for your help.

    To Aminul >
    As you can see at the start of the code i already check my database and table name. Both are perfectly exact.
    You asked me if i established the proper connection, but my code is in a plugin activated, so the connection to the database should normally be done automatically.
    When you ask me if i included the wordpress files to do it i’m confuse as i dont think i need to include anything else, and if so, what are those files ?
    For the fieldName and the data, i already checked everything here and everything is exactly right.

    To bcworkz >
    When im in my phpmyadmin, i can find no option, window or table related to priviledge.
    I know my acc username, and know my acc password. They are in the wp_config and i easly acess to the database. But there is nothing related to database priledge here. I don’t know why and if it’s normal.
    When i work on my localhost phpmyadmin, i always have all those option but in my wordpress database i don’t have it.
    However : If i do the mysql request to insert data into the database it actually work. I can’t insert data through my php code since the data doesn’t appear. But if i do a mysql code directly on my database and insert data in my table it 100% work.

    Do you have an idea of what it could be ?

    Moderator bcworkz

    (@bcworkz)

    Hosts often limit your own privileges in phpMyAdmin as a way of improving security, meaning that you cannot manage other privileges.

    So you executed the query from $wpdb->last_query within phpMyAdmin and it worked as expected? But the same from PHP does not? That really does indicate a privileges issue for the user credentials that WP is using. Are the WP credentials the same as what you use to access phpMyAdmin? If not, more evidence towards privileges. Does your PHP work on your own localhost installation but not on your production server? If so, evidence there’s nothing wrong with your PHP.

    If all evidence points to privileges but there is no such UI in phpMyAdmin, you’ll need your host to help you. There still are privileges, except your user doesn’t have adequate privilege to manage them.

    Thread Starter louma333

    (@louma333)

    bcworkz >

    To be fair, i don’t know too much. I connect myself to phpmyadmin using the logs that are in my wp_config. And i since i coded this php code as a plugin, by default, i think the code is ran with the same user defined in wp_config right ? I mean the user that is defined there is supposed to be the one using the database through wordpress. So i don’t understand how it could be different.

    If it’s really about priviledge, i suppose i have to contact my host ? Since the database is provided by the hosting service it’s about them right ?

    Thanks again for your help

    Moderator bcworkz

    (@bcworkz)

    Yes, your plugin accesses the DB using the credentials in wp-config.php. But you use a custom DB table. Every table can have its own unique set of privileges. How did you create the table? If you used phpMyAdmin to manually create it, it likely is lacking the correct privileges for the wp-config.php user. But if you created the table with a SQL query made from WP PHP, I think it’d inherit that user’s privileges. Not sure though, as I’ve always added custom tables through phpMyAdmin.

    If table privileges are suspected as the issue and your instance of phpMyAdmin has no privileges tab, then you will need your host’s assistance to correct the table privileges.

    Thread Starter louma333

    (@louma333)

    bcworkz > Thanks for your reply.
    I’m currently contacting my host to see what i can get from them.

    One thing i don’t get is, why would my other plugins work with the database and not the one i did code personally ? I mean there are other plugin on my wp website that i did install from internet. Those plugins insert data in the data base. So why those plugin work but when i do it myself it doesnt ?
    If anything those plugin working are the proof that my wp have the priviledge to insert data, right ?

    For the table, i did create via mysql directly in the phpmyadmin. Is it bad ? I did it like that :

    CREATE TABLE wp_inscriptions_majeurs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        FirstName VARCHAR(255) NOT NULL,
        LastName VARCHAR(255),
        Adress VARCHAR(255)
    )
    Moderator bcworkz

    (@bcworkz)

    Privilege assigned to a new table by default depends on what DB user created the table. Plugins typically do so via the $wpdb object, so the DB user is whomever is assigned in wp-config.php. When you create through phpMyAdmin, you may or may not be that same user. Since the INSERT query works through phpMyAdmin but not through $wpdb->query(), I’m guessing that the users are not the same. In such a situation when I’ve created custom tables, I’ve had to explicitly assign privileges for the wp-config.php user.

    I’ll allow that I could be all wrong about this, but it’s my best assessment based on the limited clues that we have available. It’d all be confirmed or denied quickly if you only had access to table privileges, but it’s apparently not meant to be so easy.

    Thread Starter louma333

    (@louma333)

    bcworkz i’ll test something right away, i’ll try to insert my data in another plugin database just to see if it can be added here. If so, then you are prolly right and we know what to do.

    I’ll be back with result soon

    Thread Starter louma333

    (@louma333)

    bcworkz i tried to insert the data through my form to another working database tied to another plugin and it didn’t work. I had exactly the same issue. Everything seems to work, but nothing is inserted.

    Now i’m trying to create a database table though the activation of my plugin so i could try to insert data in it, but it doesn’t work. And again, same problem, i don’t have error, it just doesn’t create the table :

    register_activation_hook(__FILE__, 'creer_table_reponses');
    
    
    
    function creer_table_reponses() {
        try {
            error_log('La fonction creer_table_reponses est appelƩe');
    
            global $wpdb;
            $wpdb->show_errors();
            if(is_null($wpdb)) {
                error_log('Objet global $wpdb non disponible');
                return;
            }
            error_log('Objet global $wpdb chargƩ');
    
            $charset_collate = $wpdb->get_charset_collate();
            $table_majeurs = 'wp_inscriptions_majeurs';
            $table_mineurs = 'wp_inscriptions_mineurs';
    
            $sql_majeurs = "CREATE TABLE {$table_majeurs} (
                id mediumint(9) NOT NULL AUTO_INCREMENT,
                nom text NOT NULL,
                prenom text NOT NULL,
                adresse text NOT NULL,
                PRIMARY KEY  (id)
            ) {$charset_collate} ENGINE=InnoDB;";
            
            $sql_mineurs = "CREATE TABLE {$table_mineurs} (
                id mediumint(9) NOT NULL AUTO_INCREMENT,
                nom text NOT NULL,
                prenom text NOT NULL,
                adresse text NOT NULL,
                PRIMARY KEY  (id)
            ) {$charset_collate} ENGINE=InnoDB;";
    
    $error = $wpdb->print_error();
    if (!empty($error)) {
        error_log($error);
    }
            error_log('RequĆŖtes SQL crĆ©Ć©es');
    
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            error_log('Fichier upgrade.php inclus');
    
            dbDelta($sql_majeurs);
            error_log('RequĆŖte SQL pour table majeurs exĆ©cutĆ©e');
    
            dbDelta($sql_mineurs);
            error_log('RequĆŖte SQL pour table mineurs exĆ©cutĆ©e');
    
            error_log('La fonction creer_table_reponses a terminĆ© avec succĆØs');
    
        } catch (Exception $e) {
            error_log('Erreur lors de la crƩation des tables : ' . $e->getMessage());
        }
    }

    In my error_log i have everything except the catch (Exception $e) sentence. Meaning everything is currently working but nothing is added. I’m going insane lol. I already checked if the database was the right one connected to my wordpress and it is. So why does it say it is adding data but doesn’t ?

    Also : I finally managed to find where i could see the prilivedge of the user i’m connected with (so basically the wp user, since that’s the user in wp-config), and it says : No priviledge.
    But then how is it possible that my other plugin can add data to the database through wordpress ?

    • This reply was modified 1 year, 5 months ago by louma333.
    Moderator bcworkz

    (@bcworkz)

    Every table can have its own privileges. The plugin that can add data is adding it to a different table, yes? That table would have the correct privileges. You should be able to successfully add data there as well.

    As for your table that you’ve now added, perhaps try using a GRANT query to set the table’s privileges? Probably not allowed, just a thought. You can see table privileges but cannot alter them?

    I wonder if the table creation process goes more smoothly by using dbDelta(). I’ve never used it myself, so IDK. I’ve been able to set privileges in phpMyAdmin so wasn’t an issue for me.

    Thread Starter louma333

    (@louma333)

    bcworkz strangely enough, i actually solved this issue by… sending the data of the form to the database of my other wordpress website. So i can’t event understand why it didn’t work on his own database but it surely work perfectly in the database of my other website

    Moderator bcworkz

    (@bcworkz)

    Sounds more and more like privileges to me ?? Sending one site’s data to another is unorthodox (unless the other site needs the data as well), but as a one time workaround it’ll work. Not ideal, but working is better than not working ??

    It seems the phpMyAdmin login you were provided doesn’t have full privileges. I’ve run into that once in a while. It’s frustrating to not have access to what you’re used to having.

Viewing 13 replies - 1 through 13 (of 13 total)
  • The topic ‘$wpdb->insert ā€“ Not working’ is closed to new replies.