Best practice for AJAX db login

One of my components requires info from a database that’s in the same schema, but a different table. I’m still new to working through the practice of backend throughput, but am wondering how best to log into the database without putting plaintext passwords into Sage theme functions.

Ideally a function like the following wouldn’t include the actual credentials (also my code probably is shotty…)

public function tidestations() {
    $host = "localhost";
    $user = "test";
    $pass = "test1234";

    $dbname = 'test';
    $dbtable = "example";

    $conn = mysql_connect($host, $user, $pass, $dbname);
    $dbs = mysql_select_db($dbname, $conn);

    $sql = mysql_query("SELECT id, status, cargo, berth");
    $shiparray = mysql_fetch_row($sql);

    $result = $conn->query($sql);

    echo json_encode($shiparray);

As an aside, when I run the above I get the error, ‘Call to undefined function App\Controllers\mysql_connect()’ but I suspect that’s probably one of my configuration errors. mysqli is undefined too if I switch it to that.

Fatal error: Uncaught Error: Class ‘App\Controllers\wpdb’ not found

The above is why I was trying to use mysqli/msql_connect. Maybe I should have opened with that…

How would be the best way to instantiate wpdb for bedrock in this case?

From @Log1x’s link:

Warning: Methods in the wpdb() class should not be called directly. Use the global $wpdb object instead!

WordPress provides a global object variable, $wpdb , which is an instantiation of the wpdb class defined in /wp-includes/wp-db.php. By default, $wpdb is instantiated to talk to the WordPress database. To access $wpdb in your WordPress PHP code, declare $wpdb as a global variable using the global keyword , or use the superglobal $GLOBALS […]

So something like this:

global $wpdb;

$wpdb->get_results("SOME SQL");
1 Like
use Sober\Controller\Controller;

class App extends Controller

    public function tidestations() {
        global $wpdb;

        $wpdb = get_results("SELECT exampletable FROM exampledb");



In blade:

{!! $tidestations !!}


Result: Uncaught Error: Call to undefined function App\Controllers\get_results()

Thanks in advance for your help on this. Let me know if there are any other areas or logs to output for review.

Answered my own question with a facepalm… overlooked the = change to ->

How do I send you guys beer and whiskey?

Glad you figured it out!

If you’re serious about the beer and whiskey thing:


1 Like

Done and done! Nice to support some people making stuff that helps me create stuff, instead of watch them sail around the world haha.

Now I have a new conundrum…

This topic was automatically closed after 42 days. New replies are no longer allowed.