If I use the following code, it works:
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
But when I do this, it doesn't:
$db_host='localhost';
$db_id='root';
$db_pass='';
$con = mysql_connect($db_host, $db_id, $db_pass);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
Trying to swap (") and (').
mysql_ functions are discouraged for new applicationa you are advised to use mysqli or PDO. The following code uses PDO to connect to database.
//dependant on your setup
$host= "localhost";
$username="XXX";
$password="YYY";
$database="ZZZ";
// connect to the database
try {
$dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);
//Remainder of code
}
catch(PDOException $e) {
echo "I'm sorry I'm afraid you can't do that.". $e->getMessage() ;// Remove or modify after testing
file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]'). $e->getMessage()."\r\n", FILE_APPEND);//Change file name to suit
}
// close the connection
$dbh = null;
try using a script like this
$db_host = 'localhost';
$db_id = 'root';
$db_pass ='';
$con = mysql_connect ($ db_host, $ db_id, $db_pass) or die ('Could not connect:'. mysql_error ());
That code is fine. Review the error log- the problem has to be external to that code.
Related
I have newly purchased server, on that server database connections are not working.
<?php
error_reporting(E_ALL);
$server = "server name";
$user = "username";
$password = "password";
$db = "test";
echo "Before";
$con = mysql_connect($server, $user, $password);
echo "After";
if (!$con){
die('Could not connect:' . mysql_error());
}
mysql_select_db($db, $con);
?>
When run this file its print Before text but not print After text.
Currently you can use the following code:
ini_set("error_reporting", E_ALL & ~E_DEPRECATED);
Using this you can get either deprecated or not.
FYI: The mysql_* functions have been removed in PHP7.x. There are two modules you can use.
The first is MySQLi, just use the code as follows:
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
You can also use PDO using code :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Hello guys,
I know this might seem to be a duplicate question but i am having an issue connecting to my database with PDO. I tried interchanging the server name from localhost to '127.0.0.1' but to no avail i have gained success. I am here testing and trying to create my own database for my own personal use and to get an understanding of how querying a database works, but my lack of knowledge brought me here. Can someone just point me in the right direction.
a snippet of my code is below
<?php
require_once('CONFIG.php');
session_start();
try {
$database_handler = new PDO('mysql:host=' . $databasehost . 'houses', 'root', '');
}
catch (PDOException $e) {
print "Error: " . $e->getMessage();
}
?>
So i have my Config.php file which has
<?php
$databasehost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'house';
$conn = mysql_connect($databasehost , $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'house';
mysql_select_db($dbname);
?>
Any help would be greatly appreciated
The format of your DSN is wrong
<?php
require_once 'CONFIG.php';
session_start();
try {
$dsn = sprintf('mysql:host=%s;dbname=%s;charset=utf8', $databasehost, $dbname);
$database_handler = new PDO($dsn, $dbuser, $dbpass, array(
PDO::ATTR_EMULATE_PREPARES=>false,
PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
}
catch (PDOException $e) {
print "Error: " . $e->getMessage();
}
and drop the lines
$conn = mysql_connect($databasehost , $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'house';
mysql_select_db($dbname);
from your Config.php
i've tried everything to make my site connect to the database but i always get his error: Could not connect to Master Database
i have 2 files
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','root');
define('DBNAME','test');
define('dbslave','test');
define('dbsiteid','1');
define('dbprefix','_blog');
and connect.php
error_reporting(0);
$connect = mysql_connect("$DBHOST", "$DBUSER", "$DBPASS");
if ( ! $connect) {
die('Could not connect to Database server');
}
$siteid = "$dbsiteid";
$prefix = "$dbprefix";
$dbmast = "$DBNAME";
$dbslave = "$dbslave";
$cmast = mysql_select_db("$DBNAME");
if ( ! $cmast) {
die('Could not connect to Master Database');
}
$cslave = mysql_select_db("$dbslave");
if ( ! $cslave) {
die('Could not connect to Slave Database');
}
how do i solve this error with connection or what i did wrong ?
You do not put constants in quotes, they do not start with $, and by convention are all uppercase.
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','root');
define('DBNAME','test');
define('DBSLAVE','test');
define('DBSITEID','1');
define('DBPREFIX','_blog');
$connect = mysql_connect(DBHOST, DBUSER, DBPASS);
if (!$connect) {die('Could not connect to Database server');}
$cmast = mysql_select_db(DBNAME);
if (!$cmast) {die('Could not connect to Master Database');}
$cslave = mysql_select_db(DBSLAVE);
if (!$cslave) {die('Could not connect to Slave Database');}
Also, defining constants only to assign them to variables is silly and a waste of resources. And don't turn off error reporting when developing as it hides your errors. You want to do the opposite and them them on.
I'm trying to learn this stuff. Please be gentle.
Something is wrong here:
$dbhost = "localhost";
$dbname = "something_dbname";
$dbuser = "something_user";
$dbpass = "pwpwpwpw";
$dberror1 = "Could not connect to the database!";
$dbconnected = "you are connected!";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ($dberror1);
$select_db = mysql_select_db($dbname . $dbconnected) or die ($dberror1);
where is my mistake? I want $dbconnected to show...
I can just as easily use
echo "hello";
it shows that I connect but I'm trying to get familiar with using multiple variables.
would this be better?
$dbhost = "localhost";
$dbname = "something_dbname";
$dbuser = "something_user";
$dbpass = "pwpwpwpw";
$dberror1 = "Could not connect to the database!";
$dbconnected = "you are connected!";
if ($mysqli = new mysqli($dbhost, $dbuser, $dbpassword, $dbname))
echo $dbconnected;
else die($dberror1);
Right now you are trying to connect to a database called something_dbnameyou are connected. The . concatenates variables into one string.
To fix your immediate problem, try this:
First, define $dbhost - I don't see it in your code.
Then change the last line to this:
$select_db = mysql_select_db($dbname) or die ($dberror1);
Then, just echo $dbconnected;
If you are not connected, the page will have called die, and will never reach the line that echos $dbconnected. If you are connected, the program will proceed to this next line and echo your success message.
Or you can do it more explicitly like this:
if ($select_db = mysql_select_db($dbname))
echo $dbconnected;
else die($dberror1);
To fix the bigger problem, DON'T use mysql_*. Read this for more information.
mysqli or pdo are far better options, and you can accomplish the same task easier, for instance, connecting to a db with mysqli is just:
$mysqli = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);
Or you can do it procedural style, which is closer to your current code. The following snippet is from the php manual, on the page I linked in the comment below.
$link = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . mysqli_get_host_info($link) . "\n";
mysqli_close($link);
I'd strongly recommend using PDO. The connection string is similar and can be done using:
// I do not see $dbhost defined in your code. Make sure you have it defined first
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo $dbconnected; // will print out the connection success message
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
To answer your question about not using mysql_* functions, you can check out this
I am unable to connect to my database residing on dotCloud. I tried:
$mysqli = new mysqli($db_host, $db_user, $db_password, $db_name);
and
$mysqli = mysqli_connect($db_host, $db_user, $db_password, $db_name);
and
$mysqli = new mysqli($remote_server, $db_user, $db_password, $db_name);
and
$mysqli = mysqli_connect($remote_server, $db_user, $db_password, $db_name);
but it fails to connect, and I get "Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data."
I retrieve variables dynamically above the mysqli script with the following:
$env = json_decode(file_get_contents("/home/dotcloud/environment.json"));
$db_user = $env->DOTCLOUD_DB_MYSQL_LOGIN;
$db_password = $env->DOTCLOUD_DB_MYSQL_PASSWORD;
$db_host = $env->DOTCLOUD_DB_MYSQL_HOST;
$db_port = $env->DOTCLOUD_DB_MYSQL_PORT;
$remote_server = '$db_host:$db_port';
//I also define $db_name here
$db_name = 'mydbname';
I also have the following code below the mysqli script:
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
$result["status"] = "failed";
$result["message"] = "Failed to connect to database.";
echo json_encode($result);
exit;
} else {
// Successfully connected!
$stmt = $mysqli->stmt_init();
echo "<p>Successfully connected!!</p>";
}
What am I doing wrong?
There are a couple of things wrong in your code.
1. Your $remote_server variable is using a single quote
$remote_server = '$db_host:$db_port';
This means that $remote_server will not expand the $db_host and $db_port variables. You should use double quotes. If you used the variable as it is, it wouldn't work for you.
$remote_server = "$db_host:$db_port";
See this page for more info:
http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single
2. You are not using the mysql port when connecting, which is required on dotCloud since it doesn't run mysql on the standard port of 3306.
Your code:
$mysqli = new mysqli($db_host, $db_user, $db_password, $db_name);
The correct code, using the variables you already declared above:
$mysqli = new mysqli($db_host, $db_user, $db_password, $db_name, $db_port);
More info can be found here: http://www.php.net/manual/en/mysqli.quickstart.connections.php
For a complete example, it will look like this.
$env = json_decode(file_get_contents("/home/dotcloud/environment.json"));
$db_user = $env->DOTCLOUD_DB_MYSQL_LOGIN;
$db_password = $env->DOTCLOUD_DB_MYSQL_PASSWORD;
$db_host = $env->DOTCLOUD_DB_MYSQL_HOST;
$db_port = $env->DOTCLOUD_DB_MYSQL_PORT;
//I also define $db_name here
$db_name = 'mydbname';
$mysqli = new mysqli($db_host, $db_user, $db_password, $db_name, $db_port);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
try like this: I think it will help you.
$connect = mysql_connect($mysql_host, $mysql_user, $mysql_password);
if (!$connect) {
die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully';
$db = mysql_select_db($mysql_database,$connect);
if (!$db) echo"'Could not select database";