Zuenie
Zuenie

Reputation: 973

Connecting to mysql database within WordPress server

We are trying to create a login screen for a WordPress website. I think the way to connect to the database is good. The code also seems to be good, we have a layout where someone types the username and password. Those are stored in variables and then it should connect to a database.

Before the following lines of code the ?> TEST prints out TEST. However when you try to login the error 500 pops up, and no print of TEST. The error code 500 is very wide unfortunately.

We are working outside the code of WordPress in a different folder. WordPress has 3 folders on the server named wp-admin, wp-content and wp-includes. We just created a folder next to it and are trying to build it there. I'd like to find out the options why it is not working, some internet research here brought me to the wp-config. But that didn't work out for us yet.

$connection = mysql_connect("IP", "username", "password");

?>
<HTML><BODY>TEST</BODY></HTML>
<?php

// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

// Selecting Database
$db = mysql_select_db("db_name", $connection) 
or die("no connection to database");    

I can add the code of the login screen as well if its necessary, just comment if that is needed.

**** I used old functionalities of PHP and that is why it is not connecting. For WordPress do not use mysql_connect but mysqli_connect.

Upvotes: 0

Views: 2441

Answers (1)

Purvik Dhorajiya
Purvik Dhorajiya

Reputation: 4870

The best way to load only load the core functionality of WordPress is to use the wp-load.php.

$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-load.php';
include_once $path . '/wp-config.php';

$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Test the connection:
if (mysqli_connect_errno()){
    // Connection Error
    exit("Couldn't connect to the database: ".mysqli_connect_error());
}

Upvotes: 4

Related Questions