wordpresspluginswordpress-plugin-creation

plugin that connects to an external database on wordpress


I would like to create a WordPress plugin that connects to an external database on the same server:

<?php
/*
Plugin Name: External DB Connector
Description: Connects to an external WordPress database and retrieves data.
Version: 1.0
Author: Your Name
*/

// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit;
}

// Hook into WordPress
add_action('admin_menu', 'external_db_connector_menu');

function external_db_connector_menu()
{
    add_menu_page(
        'External DB Connector',
        'External DB Connector',
        'manage_options',
        'external_db_connector',
        'external_db_connector_page'
    );
}

function external_db_connector_page()
{
    ?>
    <div class="wrap">
        <h2>External DB Connector</h2>
        <?php
        // Connect to the external database
        $external_db = new wpdb('root', '', 'students', 'localhost');

        // Check the connection
        if ($external_db->last_error) {
            echo '<p>Error connecting to the external database: ' . esc_html($external_db->last_error) . '</p>';
        } else {
            echo '<p>Successfully connected to the external database.</p>';

            // Retrieve data from the 'student' table and 'ali' column
            $table_name = $external_db->prefix . 'students';
            $column_name = 'ali';

            // Perform the query
            $result = $external_db->get_results("SELECT $column_name FROM $table_name");

            // Check if the query was successful
            if ($result === null) {
                echo '<p>No data found in the "ali" column.</p>';
            } elseif ($external_db->last_error) {
                echo '<p>Error retrieving data: ' . esc_html($external_db->last_error) . '</p>';
            } else {
                echo '<p>Data from column "ali":</p>';
                foreach ($result as $row) {
                    echo '<p>' . esc_html($row->$column_name) . '</p>';
                }
            }
        }
        ?>
    </div>
    <?php
}

but it is still give the error:

Successfully connected to the external database. No data found in the "ali" column.

but I have "ali" column in my database.

enter image description here

what is the problem?

I think that related to connection to the database

Thanks


Solution

  • In your code example you try to get data from student table

    $table_name = $external_db->prefix . 'student';
    

    And on screenshot, there is students table.

    Also, your code for checking the database connection is not working correctly. You need to replace

    if ($external_db->last_error) {
    

    with

    if (null !== $external_db->error) {