I have a WAMP installation with Windows Server 2012 R2 Datacenter Edition, Apache 2.4.23, PHP 7.0.10 (mysqlnd 5.0.12-dev - 20150407), MySQL 5.7.14.
I configured a connection with:
$host = 'wrong-server';
$dbase = 'db_name';
$user = 'my_user';
$pwd = 'my_pwd';
$connection='mysql: host='.$host.'; dbname='.$dbase;
$link = new PDO($connection , $user, $pwd);
where wrong-server doesn't exsist (it is for a test for catching errors).
When I execute the code the connection works using localhost as host (I know it because a query to db_name retrive datas).
I searched for some default behaviour or configuration without succes.
Some ideas?
Code update:
<?php
$host = '192.168.123.123'; //'localhost';
$dbase = 'db_name';
$user = 'my_user';
$pwd = 'my_pwd';
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_SILENT;
$connection='mysql: host='.$host.'; dbname='.$dbase;
try {
$link = new PDO($connection, $user, $pwd, $pdo_options);
$_SESSION['DB_INFO']=array( 'db'=>$link->getAttribute(PDO::ATTR_DRIVER_NAME),
'ver'=>$link->getAttribute(PDO::ATTR_SERVER_VERSION),
'cli'=>$link->getAttribute(PDO::ATTR_CLIENT_VERSION ),
'srv'=>$link->getAttribute(PDO::ATTR_SERVER_INFO ),
);
print_r($_SESSION['DB_INFO']);
}
catch(\PDOException $err) {
echo 'Error: '.$err->getMessage();
};
Server 192.168.123.123 doesn't exsist but I have these response:
Array ( [db] => mysql [ver] => 5.7.14 [cli] => mysqlnd 5.0.12-dev - 20150407 - $Id: 241ae00989d1995ffcbbf63d579943635faf9972 $ [srv] => Uptime: 20111 Threads: 1 Questions: 354 Slow queries: 0 Opens: 125 Flush tables: 1 Open tables: 118 Queries per second avg: 0.017 )
But if I set $pwd='wrong_pwd' the answer is:
Error: SQLSTATE[HY000] [1045] Access denied for user 'my_user'#'localhost' (using password: YES)
SOLUTION
As #MichaelBerkowski states, eliminating spaces in the DSN
mysql:host='.$host.';dbname='.$dbase.'
instead of
mysql: host='.$host.'; dbname='.$dbase.'
solves the problem, so an error came out.
Related
I use Xampp as server. I have mysql table that i visualize with bootstrap grid. As the table have more than 1000 rows, the visualization with bootstrap is slow. I'm trying to work server side but have a problem connecting to the data base with this code
$dbDetails = array(
'host' => 'localhost',
'user' => 'root',
'pass' => '',
'db' => 'company');
It can't contact the server or connect to the database, while with this is possible. I receive the following errors: DataTables warning: table id=memListTable - Invalid JSON response AND {"error":"An error occurred while connecting to the database. The error reported by the server was: SQLSTATE[HY000] [1045] Access denied for user 'root'#'localhost' (using password: NO)"}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "company";
I use MySQL 5.7.17 on AWS RDS.
I encountered a strange behavior and I am looking for an explanation.
In short: I try to connect over SSL, with settings that I think should cause the connection to FAIL, but it succeeds!
The following PHP code succeeds to connect to the RDS instance over SSL:
<?
$HOST = "something.amazonaws.com";
$USER = "myuser";
$PASS = "mypass";
$connectionString = "mysql:host={$HOST};charset=utf8";
$options = [ ];
$options[PDO::MYSQL_ATTR_SSL_CA] = "LITERALLY THIS TEXT. DEFINITELY NOT A CERTIFICATE!";
$options[PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT] = false;
$conn = new \PDO($connectionString, $USER, $PASS, $options);
$sql = "SHOW STATUS LIKE 'Ssl_cipher'";
$stmt = $conn->prepare($sql);
$stmt->execute([ ]);
$stmt->setFetchMode(\PDO::FETCH_ASSOC);
$rows = $stmt->fetchAll();
print_r($rows);
The result I get:
Array
(
[0] => Array
(
[Variable_name] => Ssl_cipher
[Value] => AES256-SHA
)
)
Also, I found three pem files in /etc/ca-certificates/rds-mysql. I thought that PHP might be going there for some reason, so I deleted them, but the SSL connection still succeeds.
Note: if I delete the line that says $options[PDO::MYSQL_ATTR_SSL_CA] = "LITERALLY THIS TEXT. DEFINITELY NOT A CERTIFICATE!"; - it does NOT connect over SSL. So it appears that this option does have some impact.
My question is: how come it succeeds?
I need help with problem that appear on my website while I tried to connect to mysql.
so, this is the error:
Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp\www\sites\mysite\core\connection.php on line 9
Call Stack
Time Memory Function Location
1 0.0007 163008 {main}( ) ..\index.php:0
2 0.0012 165376 include( 'C:\wamp\www\sites\mysite\core\connection.php') ..\index.php:1
3 0.0015 166400 mysql_connect ( ) ..\connection.php:9
( ! ) Warning: mysql_connect(): in C:\wamp\www\sites\mysite\core\connection.php on line 9
Call Stack
Time Memory Function Location
1 0.0007 163008 {main}( ) ..\index.php:0
2 0.0012 165376 include( 'C:\wamp\www\sites\mysite\core\connection.php') ..\index.php:1
3 0.0015 166400 mysql_connect ( ) ..\connection.php:9
MySQL Error: Accטs refusי pour l'utilisateur: 'root'#'#localhost' (mot de passe: OUI)
the php code to connect that I wrote, is:
<?php
session_start();
$dbhost = "localhost";
$dbname = "users";
$dbuser = "root";
$dbpass = "root";
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
?>
cause you are using deprecated extension so
Use mysqli or PDO (The mysql extension is deprecated)
try
mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
By default, your MySQL credentials for WAMP are:
username: root
and no password.
$dbhost = "localhost";
$dbname = "users";
$dbuser = "root";
$dbpass = "";
And as other users mentioned, try to use mysqli or pdo as mysql is deprecated, but it's not your issue here.
Good luck!
If your using the default user of phpmyadmin and didn't set a new password than the password would be an empty string (no password), unless you set your password to root.
Your code is correct, although you should look into mysqli when you feel like you can handle it.
mysql_connect — Open a connection to a MySQL Server.
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_connect()
PDO::__construct()
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 4 years ago.
Attempting to connect to localhost sql db using the following code (Not doing anything with query at this point just want the query to execute):
<?php
$host = "localhost";
$port = 3306;
$socket = "";
$user = "root";
$password = "Password1";
$dbname = "CIIP_WIKI";
$con = new mysqli($host, $user, $password, $dbname, $port);
if(!$con)
{
echo ("db connection failed!");
die ('Could not connect to the database server' . mysqli_connect_error());
}
else {
echo ("db connection established.");
echo ("<br/>");
}
$query = sprintf("SELECT first_name FROM actor WHERE actor_id='1'");
$result = mysql_query($query);
$con->close();
?>
I keep getting the following...
Welcome
db connection established.
Warning: mysql_query(): Access denied for user ''#'localhost' (using password: NO) in C:\Program Files (x86)\EasyPHP-12.1\www\Cisco Wiki\index.php on line 31
Warning: mysql_query(): A link to the server could not be established in C:\Program Files (x86)\EasyPHP-12.1\www\Cisco Wiki\index.php on line 31
Why does this not work?
This is because you create a connection using mysqli_ and then use mysql_ to try to fetch your result. They are different API's.
<?php
/* You should enable error reporting for mysqli before attempting to make a connection */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
/* Set the desired charset after establishing a connection */
mysqli_set_charset($mysqli, 'utf8mb4');
printf("Success... %s\n", mysqli_get_host_info($mysqli));
Example taken from the PHP manual
This warning will be logged anytime you try to execute a query without a valid connection object being available.
In your case you thought you had a valid connection object available, but you created it using mysqli while your query is being executed using mysql. Those are two different APIs and so the mysql_query function was looking for a mysql connection object and didn't find it.
I am using this code for mysql connection
$con = mysql_connect("localhost", "username" , "password");
if (!$con)
{
die('Could not connect: ');
}
else
{ echo "connection failed....";}
mysql_select_db("ManagersDatabase", $con);
mysql database are to be found in /var/lib/mysql/ManagersDatabase.
and my php pages are to be found in /var/www/html/.
It dosen't print anything. What is the wrong in my code?
This is how you should be connecting, by using PDO: and utilizing prepared query's when querying.
<?php
try{
$con = new PDO('mysql:host=127.0.0.1;dbname=your_database','root','password');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$con->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}catch (Exception $e){
die('Cannot connect to database. Details:'.$e->getMessage());
}
?>
Or mysqli and utilizing prepared query's when querying.
<?php
$con = new mysqli("127.0.0.1", "user", "password", "your_database");
if ($con->connect_errno) {
die("Failed to connect to MySQL: (".$con->connect_errno.") ".$con->connect_error);
}
print_r($con);
?>
Edit (Reply to comment):
If you add print_r($con); you should see the mysqli connection object like:
/*
mysqli Object
(
[affected_rows] => 0
[client_info] => mysqlnd 5.0.10 - 20111026 - $Id: b0b3b15c693b7f6aeb3aa66b646fee339f175e39 $
[client_version] => 50010
[connect_errno] => 0
[connect_error] =>
[errno] => 0
[error] =>
[error_list] => Array
(
)
[field_count] => 0
[host_info] => 127.0.0.1 via TCP/IP
[info] =>
[insert_id] => 0
[server_info] => 5.5.25a
[server_version] => 50525
[stat] => Uptime: 10 Threads: 1 Questions: 1 Slow queries: 0 Opens: 33 Flush tables: 1 Open tables: 26 Queries per second avg: 0.100
[sqlstate] => 00000
[protocol_version] => 10
[thread_id] => 1
[warning_count] => 0
)
*/
Other methods are outdated and soon tobe (thankfully) deprecated.
you should connect to your database in else block;
$con = mysql_connect("localhost", "username" , "password");
if (!$con)
{
die('Could not connect: ');
}
else // if connection is made, then select the DB
{
mysql_select_db("ManagersDatabase", $con);
}
Quote from your question:
if (!$con)
{
die('Could not connect: ');
}
else
{ echo "connection failed....";}
... you do notice it doesn't make much sense? it is saying if (something) { //could not connect } else { //connection failed } so your code thinks it is always failing.
What you should have is something like
$con = mysql_connect("localhost", "username" , "password");
if ($con === false)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ManagersDatabase", $con);
So it would actually print out anything.
Also, you should have either display_errors enabled to get the errors on screen or error_log in use so you would get the errors logged to somewhere.
In addition, please check you actually have the mysql extension enabled and in use, and mysql_connect() function available. phpinfo(); will tell what extensions you have, and function_exists() can tell you have the function available.
So, things to do:
Fix your code logic like listed above
Enable error printing or logging
Check that you have the mysql extension enabled
Check that mysql_connect() function actually is callable
Edit. as the missing mysql extension seems to be the problem ('call to undefined function mysql_connect'):
First of all, you need to have access to your PHP configuration. If this is your local installation or server, you should have that - if you are using someone elses hosting, they are the people who should change these things.
Given some assumptions, such as
you are using your local apache server
you are not using XAMPP or any other *AMP products, but vanilla installations
this is what you should do:
Find your php.ini configuration file or create one based on example files in the PHP folder if you don't have one
Find the lines below (.dll for windows, .so for linux, don't know about others)
;extension=php_mysql.dll
;extension=php_mysqli.dll
;extension=php_pdo_mysql.dll
Strip out the comment (the first ';') from the one you want to use. You are using the first one in your example, the others are for using other abstractions described in some of the other postings here, so if you want to go with the code you have, you'd uncomment the first one.
Enable "display_startup_errors" also if you want to see any configuration problems immediately
Check that "extension_dir" setting is correct, and is pointing to the folder where you have the above .dll extensions
Restart your apache server
This is Template file for your project connect.php. You can use it.
<?php
// Connecting, selecting database
$link = mysql_connect('localhost', 'root', '') or die('Could not connect: ' . mysql_error());
//echo 'Connected successfully';
mysql_select_db('procost') or die('Could not select database');
?>