Could not connect to MySQL in PHP - php

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();
}
?>

Related

Fatal error: Uncaught mysqli_sql_exception: Unknown database 'test_db'. I keep getting this error even though I programatically created the database

Here is the code
<?php
$servername = "localhost";
$usrname = "root";
$pwd = "";
$db = "test_db";
// connect to the database
$conn= mysqli_connect($servername, $usrname, $pwd,$db);
if (!$conn){
die('connection failed' . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE IF NOT EXISTS test_db";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully<br>";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
?>
I am not sure what is going on as I am sure i made no errors while typing. As it keeps showing me that there is an unknown database despite the fact i made a CREATE DATABASE statement.
I do not know if there is something else i need to do but by all measures the code should work.
It is supposed to echo the "Database created successfully" or the error message.
`<?php
$servername = "localhost";
$usrname = "root";
$pwd = "";
//$db = "test_db";
// connect to the database
$conn= mysqli_connect($servername, $usrname, $pwd);
if (!$conn){
die('connection failed' . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE IF NOT EXISTS test_db";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully<br>";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
?>`
Your code is fine, You just have to remove $db from mysqli_connect().
Because you are requesting to connect "test_db" to this database which already not exists.
<?php
// Connect to MySQL
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Make my_db the current database
$db_selected = mysql_select_db('my_db', $link);
if (!$db_selected) {
// If we couldn't, then it either doesn't exist, or we can't see it.
$sql = 'CREATE DATABASE my_db';
if (mysql_query($sql, $link)) {
echo "Database my_db created successfully\n";
} else {
echo 'Error creating database: ' . mysql_error() . "\n";
}
}
mysql_close($link);
?>
Reference
How do I create a database if it doesn't exist, using PHP?
$conn= mysqli_connect($servername, $usrname, $pwd,$db);
You are trying to connect to a database that did not initially exist, so you get a fatal error.
Try creating new database using try catch blocks
try{
$conn= mysqli_connect($servername, $usrname, $pwd,$db);
}cath(Exception $e){
//your code
}

PHP script cannot access database in sql

I am trying to connect to a MySQL database through a php script. It gives me this error from mysql_error(): Access denied for user '#localhost' to database 'userinfo'
userinfo is the database.
my script is this
<?php
$servername = "localhost";
$username = "root";
$password = "'mm'";
$database = "userinfo";
$conn = mysqli_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully<br>";
mysql_select_db($database) or die(mysql_error());
echo "connected successfully to db:" . $database . "<br>";
?>
you are connecting using
mysqli_
function
and selecting data with
mysql_
avoid using both at the same time. since they're incompatible.
use the mysqli_ alternative instead
mysqli_select_db($conn, $database);
and
mysqli_error($conn)
Please keep in mind this isn't the safest way. But since you have said your learning this it is a start.
<?php
$servername = "localhost";
$username = "root";
$password = "mm";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
http://www.w3schools.com/php/php_mysql_connect.asp
To select data from the database
http://www.w3schools.com/php/php_mysql_select.asp
It appeared you where combining the old mysql in php with the new mysqli

Php connection with SQL Server 2012

I'm trying to make a connection to sql server 2012 with php, but always shows
Erro: SQLSTATE[IMSSP]: An invalid keyword 'Databases' was specified in the DSN string.
Can someone help me with this?
here is the code that i use to make the connection
<?php
session_start();
$servername = 'SERVERNAME';
$username = 'sa';
$password = '12345678';
$dbname = 'DBNAME';
//connection
try {
$conn = new PDO("sqlsrv:server=$servername;database=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::SQLSRV_ATTR_DIRECT_QUERY , true);
} catch(PDOException $e) {
echo "Erro: " . $e->getMessage();
}
$conn=null;
?>
I haven't used SQL server 2012 but try changing
$conn = new PDO("sqlsrv:server=$servername;database=$dbname", $username, $password);
To
$conn = new PDO("mssql:host=$servername;dbname=$dbname", $username, $password);

php syntax database connect

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

Can't make mysql connection

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.

Categories