Custom PHP code within a WP webpage won’t connect to an alternate mySQL database on the same server

Question

On a new page in an existing WP website, I used a page_custom.php template to create a form where the user enters their product’s serial numbers in 2 input boxes, clicks a “Submit” button, and the code displays a table with their associated data including photos. The code queries a mySQL database that resides on the same server as the WP database, but is separate and properly named. When I run the code using the same database local on my wampserver, the code runs error free and returns the correct information. However, when I place the code into the page_custom.php file, it won’t connect to the database. This is my wampserver connection code that works as an include file tagdbconn.php using the statement
“include_once ‘includes/tagdbconn.php’;”.

<?php
//tagdbconn.php
    $dbServername="testsite";
    $dbUsername="root";
    $dbPassword = '';
    $dbName="build_data";

    // Connect to the MySQL database
    $conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);

    // If the connection fails, display an error message
    if (!$conn) {
        echo 'Error Code: ' . mysqli_connect_errno() . '<br>';
        echo 'Error Message: ' . mysqli_connect_error() . '<br>';
        exit;
    }
?>

When I substitute the correct $dbservername="localhost", $dbusername="...", $dbpassword='...', and $dbname="build_data" values in the code and run it on the remote server from the WP page, I get the message:

Error Code: 1044
Error Message: Access denied for user ‘…’@’localhost’ to database ‘build_data’

I’ve removed the query and all the data handling so the error seems to be in making the connection. The page.custom.php can echo a variable if I create it inside tagdbconn.php so the include reference is working.

Have tried the statement:

$conn = new mysqli($dbServername, $dbUsername, $dbPassword, $dbName);

and I don’t get the error message, but it won’t return a query result and magically the sidebar and footer of the site disappear.

What is the proper way to connect to the database please? I’ve seen that there is a wpdb function and that then the queries change from SQL. I know SQL and would rather keep using it instead of learning something new today unless I absolutely have to.

Thanks for any help.

0
meracer 3 months 2021-05-03T19:26:23-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse