Can't connect to local hosted mysql using PHP script - php

I am trying to build a self-hosted PHP site, but I am having trouble connecting to the database from my PHP script.
Please note the following
1). This code allows me to connect to MAMP from my terminus without problem so I know MySQL is working etc
mysql --host=127.0.0.1 --port=8889 --user=root -p
2) When I tried to build a site on a remote hosted platform, this code allowed me to connect from my php script to MySQL on the remove server, so I know there is nothing wrong with this code per se, but it didn't work on my computer.
defined('DB_SERVER') ? null : define("DB_SERVER","host");
defined('DB_USER') ? null : define("DB_USER","username");
defined('DB_PASS') ? null : define("DB_PASS","password");
defined('DB_NAME') ? null : define("DB_NAME","photo_gallery");
3 I have been able to run a self-hosted wordpress site on my computer, but I didn't establish the database connection for that (it's somewhere in the code) so I don't what I'm doing wrong. That site is accessible at the following path. http://localhost:8888/wordpress/ even though it is connected at port 8889 (according to mysql)
4 MAMP tells me that I can connect to the database from my own scripts using this format
Host localhost
Port 8889
User root
Password root
Therefore, I added this line
defined('DB_PORT') ? null : define("DB_PORT","8889");
to this group, like so
defined('DB_SERVER') ? null : define("DB_SERVER","host");
**defined('DB_PORT') ? null : define("DB_PORT","8889");**
defined('DB_USER') ? null : define("DB_USER","username");
defined('DB_PASS') ? null : define("DB_PASS","password");
defined('DB_NAME') ? null : define("DB_NAME","photo_gallery");
but it still didn't work. I'm being told database connection fails when I try to test it.
Any ideas?
EDIT. I tried to put the port next to the localhost but it's not working.
defined('DB_SERVER') ? null : define("DB_SERVER","localhost:8889");
defined('DB_USER') ? null : define("DB_USER","root");
defined('DB_PASS') ? null : define("DB_PASS","root");
defined('DB_NAME') ? null : define("DB_NAME","photo_gallery");
EDIT. The above code was in the config.php which was included into the database.php which is this
<?php
require_once("config.php");
class MySQLDatabase {
private $connection;
function __construct(){
$this->open_connection();
}
public function open_connection(){
$this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if(!$connection){
die("Database connection failed:" . mysql_error());
} else {
$db_select = mysql_select_db(DB_NAME, $this->connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
}
}
public function close_connection(){
if(isset($this->connection)){
mysql_close($this->connection);
unset($this->connection);
}
}
public function query($sql) {
$result = mysql_query($sql, $this->connection);
$this->confirm_query($result);
return $result;
}
public function mysql_prep( $value ) {
$magic_quotes_active = get_magic_quotes_gpc();
$new_enough_php = function_exists( "mysql_real_escape_string" ); // i.e. PHP >= v4.3.0
if( $new_enough_php ) { // PHP v4.3.0 or higher
// undo any magic quote effects so mysql_real_escape_string can do the work
if( $magic_quotes_active ) { $value = stripslashes( $value ); }
$value = mysql_real_escape_string( $value );
} else { // before PHP v4.3.0
// if magic quotes aren't already on then add slashes manually
if( !$magic_quotes_active ) { $value = addslashes( $value ); }
// if magic quotes are active, then the slashes already exist
}
return $value;
}
private function confirm_query($result){
if(!$result){
die("Database query failed:" . mysql_error());
}
}
}
$database = new MySQLDatabase();
?>

What is the output of the following snippet?
<?php
// test.php
$host = 'localhost:8889';
$username = 'root';
$password = 'root';
$database = 'your_database';
if(!$connection = mysql_connect($host, $username, $password))
die('Error connecting to '.$host.'. '.mysql_error());
if(!mysql_select_db($database))
die('Error selecting '.$database.'. '.mysql_error());
echo 'Connection successful.';
?>
If this executes without an error, then you're probably just setting your constants incorrectly. Note that mysql_connect takes the port as part of the host parameter, not as a separate argument.

try 127.0.0.1:3307
it worked for me

Can you try to use:
define("DB_SERVER","127.0.0.1");

important:
checking defined or not is done by defined() but not by comparing it to null so sample:
http://www.php.net/defined
defined('DBSERVER') or define('DBSERVER', 'localhost:8889');
providing port information while making connection is just to add it along with server name i.e if your mysql server is localhost then while connecting just make it
localhost:8889
so your sample script may look like:
$strServer = "localhost:8889";
$strUser = "root";
$strPassword = "root";
$strDB = "test_db";
$conn = #mysql_connect($strServer, $strUser, $strPassword);
if(!$conn) {
die('Unable to connect to database: ' . mysql_error());
}else{
$db=mysql_select_db($strDB);
if(!$db){die('Error Selecting Database: '.$strDB.' [Error : '.mysql_error().']');}
}

Example with the default port 3306 of MySQL:
mysql_connect('localhost:3306', 'root', 'password');
This really makes things easier when copying scripts between the distant server and the local web server.

Related

How to know if MySQL is using SSL to connect to a remote database?

Here is my code to connect to my remote DB:
$con = mysqli_init();
mysqli_ssl_set($con, "/etc/letsencrypt/keys/...certbot.pem", "/etc/letsencrypt/live/.../cert.pem", "/etc/letsencrypt/live/.../fullchain.pem", NULL, NULL);
$connection = mysqli_real_connect($con, self::$host, self::$user, self::$password);
self::$lastConnection = $connection;
$db = "db_prod";
Unfortunately, I cannot tell if it's actually working because if I intentionally mispell any of the characters for my certificates in mysqli_ssl_set, the connection is still successful. So how can I know for sure that this is working as intended?
Any help appreciated.
Since you have used mysqli_ssl_set to try establishing SSL connection to MySQL. The system will proceed to use it for subsequent connection request.
Hence, You may check the $connection which is the return value of mysqli_real_connect
So please amend to:
<?php
$con = mysqli_init();
mysqli_ssl_set($con, "/etc/letsencrypt/keys/...certbot.pem", "/etc/letsencrypt/live/.../cert.pem", "/etc/letsencrypt/live/.../fullchain.pem", NULL, NULL);
$connection = mysqli_real_connect($con, self::$host, self::$user, self::$password);
/////////////////
if (!$connection)
{
die("Connect Error: " . mysqli_connect_error());
}
/////////////////
self::$lastConnection = $connection;
$db = "db_prod";
?>

Connection Issue - Unable to connect to database server?

I am getting this message in my site all of a sudden without making any changes in the config file. I will post my config code to see if there are any issues with it.
define('DB_SERVER', 'www.victorexoticagoa.com');
define('DB_SERVER_USERNAME', '******');
define('DB_SERVER_PASSWORD', '********');
define('DB_DATABASE', 'victor');
define('USE_PCONNECT', 'false');
define('STORE_SESSIONS', 'mysql');
define('CFG_TIME_ZONE', 'Asia/Kolkata');
The above code is from the configure.php file.
The below code is the connection:
tep_db_connect() or die('Unable to connect to database server!');
And the code below is the function which does the connection:
function tep_db_connect($server = DB_SERVER, $username = DB_SERVER_USERNAME, $password = DB_SERVER_PASSWORD, $database = DB_DATABASE, $link = 'db_link') {
global $$link;
if (USE_PCONNECT == 'true') {
$server = 'p:' . $server;
}
$link = mysqli_connect($server, $username, $password, $database);
if ( !mysqli_connect_errno() ) {
mysqli_set_charset($$link, 'utf8');
}
return $$link;
}
Any help will be gladly appreciated. Thanks
Check if your database is up by using the following command in a command shell:
mysql --host=www.victorexoticagoa.com --port=yourport --user=youruser --pass=yourpass
If it cannot connect, the problem is the server, not your code.
Have you checked if that is the way you need to connect or the port to connect? I dont see the port (thats not supposed to be port 80 most times). Please check docs of the host and ask for details. It should be documented.

Unknown MySQL server host 'DB_HOST' (0)

I am trying to sent data to the server database, i implement it using wamp server it was working fine but when i installed the db on my domain and switched it to my domain its giving the following error.
I have kept my files inside a folder in root directory
Unknown MySQL server host 'DB_HOST' (0)
Below is my config file i am using to connect to the db
<?php
// Database configuration
define('DB_USERNAME', 'user');
define('DB_PASSWORD', 'xxxx');
define('DB_HOST', '192.210.195.245');
define('DB_NAME', 'tabanico_userlogin');
?>
here my code connecting db, config.php file contains the code pasted above
<?php
class DbConnect {
private $conn;
function __construct() {
// connecting to database
$this->connect();
}
function __destruct() {
$this->close();
}
function connect() {
include_once dirname(__FILE__) . './Config.php';
$this->conn = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
mysql_select_db(DB_NAME) or die(mysql_error());
// returing connection resource
return $this->conn;
}
// Close function
function close() {
// close db connection
mysql_close($this->conn);
}
}
?>
and my file receiving data
<?php
include_once './DbConnect.php';
function createNewPrediction() {
$response = array();
$id = $_POST["id"];
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$db = new DbConnect();
// mysql query
$query = "INSERT INTO login(id,name,email,password) VALUES('$id','$name','$email','$password')";
$result = mysql_query($query) or die(mysql_error());
if ($result) {
$response["error"] = false;
$response["message"] = "Prediction added successfully!";
} else {
$response["error"] = true;
$response["message"] = "Failed to add prediction!";
}
// echo json response
echo json_encode($response);
}
createNewPrediction();
?>
I have seen related post but didn't find useful answers. Can anyone help me in getting out of this. Thanks in advance.
Please post the code where you try to connect to the server. I guess you tried to connect using the following function:
mysql_connect('DB_HOST', 'DB_USERNAME', 'DB_PASSWORD');
Since you defined the host using define('DB_HOST', 'localhost');, you do not have to use apostrophes. DB_HOST is a constant here. So try to use to
mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD);
instead. If you use apostrophes like in 'DB_HOST', it is interpreted as a string instead of the value of the constant DB_HOST containing localhost. That's a possible reason why you get the error that DB_HOST is an unknown host.
But please post the connection part of your code to see if that's really the mistake.

IIS to Apache connection issue

I am moving what looks like a pretty simple php/MSQL app from a Windows IIS server to a Cpanel/ Apache server. The app works fine on existing IIS/MySQL server using this format to connect:
<?php
class Connection {
var $conn;
var $user = 'XX0000XX_XXadmXX';
var $pass = 'XXXpasswordXXXX';
var $dbname = 'XXckbXXX_XXX13XX';
var $host = '74.0.0.0';
function Connection() {
$this->conn = mysql_connect($this->host, $this->user, $this->pass);
mysql_select_db($this->dbname,$this->conn) or die( "db-connect". mysql_error());
}
function closedb() {
//mysql_close(($this->host, $this->user, $this->pass ) or die( "db-close". mysql_error() );
mysql_close($this->conn)or die( "db-close". mysql_error() );
}
}
?>
I imported the DB into CPANEL/MySQL using PhpMyAdmin. 1st test failed due to $host not accepting IP address value. After changing IP to localhost - tested the connection with a DB connection script and that passed. The error is that at I can connect with the same username and PW as Windows server. But after logging in any link I click in the admin kicks me out.
Any clues would be helpful - let me know if I can provide any information that would help. I am thinking that there may be a windows specific change that needs to happen or something to do with the the DB host.
Here are some values in a settings file - before the Ip addresses were set with domain name - set with IP to test:
define('ADMIN_MANAGEMENT', "sitename");
define('FROM_NAME', "Admin");
define('SITE', "sitename");
define('SITE_NAME', "http://74.0.0.0/");
define('ADMIN_ID', "dwayne#fair.com");
define('KEYWORD', "sitename");
define('SITE_URL',"http://74.0.0.0/");
define('SITEIMGPATH', "http://74.0.0.0/public/images/");
define('ITEMS_PER_PAGE', "15");
define('PRODUCTS_PER_PAGE', "5");
define('UPLOAD_FILES', "uploads/files/");
define('UPLOAD_IMAGES', "uploads/images/");
define('SMALL_IMAGE_WIDTH',190);
define('SMALL_IMAGE_HEIGHT',77);
define('PROFILENAME', "Welcome to domain.com");
define('CARID',1000);
define('RESIZE_IMAGE_WIDTH',400);
define('RESIZE_IMAGE_HEIGHT',300);
/*Live path*/
define("ROOT", "http://" . $_SERVER["SERVER_NAME"] . "/admin/");
define("ROOTS", "http://" . $_SERVER["SERVER_NAME"] . "/admin/");

Database code is not connecting in chat program using php

<?php
// MySQL database connection file
$SERVER = "127.0.0.1"; // MySQL SERVER
$USER = "root"; // MySQL USER
$PASSWORD = "admin"; // MySQL PASSWORD
$link = #mysql_connect($SERVER,$USER,$PASSWORD);
$db = mysql_select_db("website");
?>
This is a database connecting code for chat program but it not connecting,Can any one pls help me to correct this code?
Drop the # infront of mysql_connect, it's used to suppress error which you don't want.
Also you need to check the return value of mysql_connect which is there in $link and make sure that it is not false before you proceed and to a DB select. Calling the function mysql_error when an error occurs gives you the reason for the error.
$link = mysql_connect($SERVER,$USER,$PASSWORD);
if (!$link) {
die('Could not connect: ' . mysql_error());
}

Categories