I have 2 connection database (MySQL) in different host like this:
//database 1
$dbhost='localhost';
$dbuser='user1';
$dbpass='pass1';
$dbname='dbname1';
//database 2
$dbhostams='192.168.16.3';
$dbuserams='user2';
$dbpassams='pass2';
$dbnameams='dbname2';
function dbconnection($dbhost,$dbuser,$dbpass,$dbname){
if(!mysql_connect($dbhost,$dbuser,$dbpass)){
echo "Error occure on opening connection or database. Period.";
}else{
if(!mysql_select_db($dbname)){
echo "Error occure on select databases !";
}
}
}
function dbconnectionams($dbhostams,$dbuserams,$dbpassams,$dbnameams){
$cxn = mysql_connect($dbhostams,$dbuserams,$dbpassams,$dbnameams);
if( $cxn === FALSE ) {
die('mysql connection error: '.mysql_error());
}else{
if( !mysql_select_db($dbnameams) ){
echo "Error occure on select databases !";
}
}
}
when i use:
dbconnection($dbhost,$dbuser,$dbpass,$dbname);
at my page code, and use:
dbconnectionams($dbhostams,$dbuserams,$dbpassams,$dbnameams);
at another line of code in same page, error occured, like this:
Warning: Access denied for user: 'apache#localhost' (Using password: NO) in
/home/firman/html/fdrsimpeg/sdm-aam/include/dbclass.php on line 17
Warning: MySQL Connection Failed: Access denied for user: 'apache#localhost'
(Using password: NO) in /home/firman/html/fdrsimpeg/sdm-aam/include/dbclass.php
on line 17
mysql connection error:
what must i do to solve this problem?
Your global variables ($dbhost, $dbuser, etc.) are not within the scope of your function calls; for example, if those function calls take place within another function, you will need to declare the variables within the function with the global keyword in order to access them (otherwise PHP thinks you're referring to different variables of the same name that are local to the function):
function foo() {
global $dbhost, $dbuser, $dbpass, $dbname;
dbconnection($dbhost,$dbuser,$dbpass,$dbname);
}
Read more on PHP variable scope.
First of all, change the variable names, it will be easier for you to read the code ... Second, the problem seems to be with the connection, as it is detecting that the username is "apache". Check the variables names in the functions ... change them and try again.
//database 1
$dbhost='localhost';
$dbuser='user1';
$dbpass='pass1';
$dbname='dbname1';
//database 2
$dbhostams='192.168.16.3';
$dbuserams='user2';
$dbpassams='pass2';
$dbnameams='dbname2';
function dbconnection($_dbhost,$_dbuser,$_dbpass,$_dbname){
if(!mysql_connect($_dbhost,$_dbuser,$_dbpass)){
echo "Error occure on opening connection or database. Period.";
}else{
if(!mysql_select_db($_dbname)){
echo "Error occure on select databases !";
}
}
}
function dbconnectionams($_dbhostams,$_dbuserams,$_dbpassams,$_dbnameams){
$cxn = mysql_connect($_dbhostams,$_dbuserams,$_dbpassams,$_dbnameams);
if( $cxn === FALSE ) {
die('mysql connection error: '.mysql_error());
}else{
if( !mysql_select_db($dbnameams) ){
echo "Error occure on select databases !";
}
}
}
You need to pass true as fourth parameter to the mysql_connect function.
$database1 = mysql_connect($host1, $user1, $pass1);
$database2 = mysql_connect($host2, $user2, $pass2, true);
mysql_select_db('database1', $database1);
mysql_select_db('database2', $database2);
And to query your database use this:
mysql_query('SELECT * FROM table', $database1);
mysql_query('SELECT * FROM table', $database2);
Check this answer here on Stackoverflow....link
I didn't see anything obviously wrong, I tested your code as provided and both connections worked.
Check to see if mysql.default_user, mysql.default_host etc. is set within your php.ini
Related
I am using a function that is supposed to get the result row as an associative array but it does not get me because it changes from mysql to mysqli according to the moderator's instructions.
What am I doing wrong
function dbquery($link,$query) {
$result = mysqli_query($link, $query );
if (!$result) {
echo mysqli_connect_error();
return false;
} else {
return($result);
}
mysqli_close($link);
}
Function to connect to the database
function dbconnect($db_host, $db_user, $db_pass, $db_name) {
global $db_connect;
$db_connect = mysqli_connect($db_host, $db_user, $db_pass);
$db_select = mysqli_select_db($db_connect, $db_name);
if (!$db_connect) {
die("<div style='font-family:Verdana;font-size:11px;text-align:center;'><b>Unable to establish connection to MySQL</b><br />".mysqli_connect_error()." : ".mysqli_connect_error()."</div>");
} elseif (!$db_select) {
die("<div style='font-family:Verdana;font-size:11px;text-align:center;'><b>Unable to select MySQL database</b><br />".mysqli_connect_error($db_name)." : ".mysqli_connect_error()."</div>");
}
}
$link = dbconnect($db_host, $db_user, $db_pass, $db_name);
What is wrong ??
Notice: Undefined index: siteurl in
/home/sfera/public_html/locale/Polish-utf8/global.php on line
132 Notice: Undefined index: siteurl in
/home/sfera/public_html/locale/Polish-utf8/global.php on line
140 Notice: Undefined index: siteurl in
/home/sfera/public_html/locale/Polish-utf8/global.php on line
147
You know how to remove this error the error is from the locale. I will show you that you know what's going on
$locale['global_441'] = "Your account on ".$settings['sitename']."has been banned";
$locale['global_442'] = "Hello [USER_NAME],\n
Your account on ".$settings['sitename']." was caught posting too many items to the system in very short time from the IP ".USER_IP.", and have therefor been banned. This is done to prevent bots from submitting spam messages in rapid succession.\n
Please contact the site administrator at ".$settings['siteemail']." to have your account restored or report if this was not you causing this security ban.\n
".$settings['siteusername'];
// Lifting of suspension
$locale['global_450'] = "Suspension automatically lifted by system";
$locale['global_451'] = "Suspension lifted at ".$settings['sitename'];
$locale['global_452'] = "Hello USER_NAME,\n
The suspension of your account at ".$settings['siteurl']." has been lifted. Here are your login details:\n
Username: USER_NAME
Password: Hidden for security reasons\n
If you have forgot your password you can reset it via the following link: LOST_PASSWORD\n\n
Regards,\n
".$settings['siteusername'];
$locale['global_453'] = "Hello USER_NAME,\n
The suspension of your account at ".$settings['siteurl']." has been lifted.\n\n
Regards,\n
".$settings['siteusername'];
$locale['global_454'] = "Account reactivated at ".$settings['sitename'];
$locale['global_455'] = "Hello USER_NAME,\n
Last time you logged in your account was reactivated at ".$settings['siteurl']." and your account is no longer marked as inactive.\n\n
Regards,\n
It makes me an argument from the base though I have it in function
// Fetch the Site Settings from the database and store them in the $settings variable
$settings = dbarray(dbquery($link,"SELECT * FROM ".$db_prefix."setting"));
So this is but the locale do not want to read them
mysqli_connect_error() should only be used to report errors that happen during mysqli_connect(). If you get an error while performing a query, you should use mysqli_error() to get that error.
Also, you're calling mysqli_close($link);. This was never executed because both branches of the if statement returned from the function. But you shouldn't close the link in this function, you're very likely to want to use the same link for other queries.
So the function should be:
function dbquery($link,$query) {
$result = mysqli_query($link, $query );
if (!$result) {
echo mysqli_error($link);
return false;
} else {
return($result);
}
}
Similarly, dbconnect() should use mysqli_error() when reporting a failure of mysqli_select_db(). It also needs to return the connection instead of setting a global variable.
function dbconnect($db_host, $db_user, $db_pass, $db_name) {
$db_connect = mysqli_connect($db_host, $db_user, $db_pass);
$db_select = mysqli_select_db($db_connect, $db_name);
if (!$db_connect) {
die("<div style='font-family:Verdana;font-size:11px;text-align:center;'><b>Unable to establish connection to MySQL</b><br />".mysqli_connect_error()." : ".mysqli_connect_error()."</div>");
} elseif (!$db_select) {
die("<div style='font-family:Verdana;font-size:11px;text-align:center;'><b>Unable to select MySQL database $db_name</b><br />".mysqli_error($db_connect)." : ".mysqli_error($db_connect)."</div>");
}
return $db_connect;
}
You can also combine mysqli_connect() and mysqli_select_db(), as the database name can be specified as an additional argument to mysqli_connect():
mysqli_connect($db_host, $db_user, $db_pass, $db_name);
Based on what I've gathered here, your code needs to be changed to:
$result = dbquery($link, "SELECT * FROM ".$db_prefix."product ");
Notice the $link variable is missing from your code posted above.
Not use MySQL or MySQLi. Use PDO:
ob_start();
session_start();
$db_hostname = "localhost";
$db_username = "root";
$db_password = "";
$db_name = "XXXXXX";
#error_reporting(0);
#error_reporting(E_ALL);
#ini_set('display_errors', 1);
try {
$dbh = new PDO("mysql:host=$db_hostname;dbname=$db_name", $db_username, $db_password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage()."<br/>";
}
Whenever I try to connect to my database with my credentials, it doesn't connect with the username, for example when I try to connect to my local database with
mysqli_connect("localhost","dbuser","","database")
It returns
Warning: mysqli_connect(): (HY000/1044): Access denied for user ''#'localhost' to database 'database'
You can't connect using all four parameters on mysqli_connect()
From the above code i can tell your
host : "localhost"
user: "dbuser"
password: ""
database name: "database"
Do this,
$conn = mysqli_connect("localhost", "dbuser", "");
mysqli_select_db($conn, "database");
// to check if you're connected, after tested and see you can take off the code below...
if ($conn) {
echo "Connected";
} else {
echo "Connection failed";
}
if you seriously want to connect using all four parameter above?
$conn = new mysqli("localhost","dbuser","","database");
// to check if you're connected, after tested and see you can take off the code below...
if ($conn) {
echo "Connected";
} else {
echo "Failed";
}
Hope this was helpful?
Just put a space between the quotes like this " " instead of "" to show as blank in the password value in your query because in programming a value either 0(false) or 1(true) has to be there you cannot have nothing and expect something
This is when you have not set password for the user in your local phpmyadmin like root user and also check for spelling mistakes
I would love to check if i can connect to database using given username, password, and database host.
So far i was trying:
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$conndatabase = mysql_select_db($dbname);
if(!mysql_ping($conn) || !$conndatabase){
//do something when cant connect
} else {
//do something when you connected
}
It works when i give bad $dbname, cuz it cant select this database. But when i give wrong host, username or password, it will give me white page with errors. For example:
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'rootx'#'localhost' (using password: YES) in C:\xampp\htdocs\strony\planer\config\opendb.php on line 6
Warning: mysql_ping() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\strony\planer\grupy.php on line 3
Question:
Is there a way to check if i can connect using given data without errors? It just gives errors before getting to mysql_ping()
EDIT
After trying Mike Brant solution, i think i could have explained it wrong. I am trying to connect to database, and if it lets me, it shows user page he wanted to access, but when it's impossible, it redirects him to the other page, to modify database information.
if(!$conndatabase){
header('Location: index.php');
}
I am using that for checking if database exists. But if i try if(!$conn) or something similar, its too late, because i got errors displayed on $conn = mysql_connect($dbhost, $dbuser, $dbpass). So i cant redirect, as it gives me
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'root'#'localhost'~~
Warning: Cannot modify header information - headers already sent by~~
Yes. Just test the value of $conn. If it is false then the connection failed, and you shouldn't even try to proceed to the db selection step.
Your code might look like this:
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (false === $conn) {
throw new Exception('Could not connect to database: ' . mysql_error());
}
$db_select = mysql_select_db($dbname. $conn);
if (false === $db_select) {
throw new Exception('Could not select database: ' . mysql_error($conn));
}
The PHP documentation is very clear on this: http://php.net/manual/en/function.mysql-connect.php
By the way, you should look at using mysqli or PDO as mysql_* functions are deprecated.
Try to debug your connection with something like
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link){
die('Could not connect: ' . mysql_error());
}
In this way you can easilly check if connection is estabilished otherwise you will print an error.
Then I would like to remember you that mysql_ functions are deprecated so i would advise you to switch to mysqli or PDO
When you look on my edit in question, you can see those answers didn't solve my problem completely. I still lacked some way to avoid errors. That's where i used error_reporting(0);.
I am not sure if that's best solution, but it works like a charm for me.
So the code for everything i tried to achieve looks like that:
opendb.php file
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password123';
$dbname = 'databasename';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$conndatabase = mysql_select_db($dbname);
?>
And there on the site i am checking connection:
<?php
error_reporting(0);
include 'opendb.php';
if(!mysql_ping($conn) || !$conndatabase){
header('Location: index.php'); //or any other site where you can config your database connection information.
}
So yeah, thats complete solution to my problem. I guess i could use !$conn instead of !mysql_ping($conn) with same result.
As has already been said, it’s the first example on the PHP manual page for the mysql_connect function.
Secondly, you should be either using the mysqli_ functions or PDO, as the mysql_ functions are deprecated and currently being phased out.
To check a connection with PDO:
try {
$db = new PDO('mysql:host=127.0.0.1;dbname=dbname', 'user', 'pass');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
header('HTTP/1.1 500 Internal Server Error');
die($e->getMessage());
}
I am attempting to connect to a mySQL database running on my local computer using a local test server set up using XAMPP. I am just using the root account which has no password assigned. I tried it as below and everything appears to work fine. I got my message echoed out to say I had successfully connected. I then tried to force an error by entering anything else in as the host, username or password and it still echoes "connection successful".
This is the code I am using to connect:
<?php
$db_host = "localhost";
$db_username = "root";
$db_password = "";
$myConn = mysql_connect($db_host, $db_username, $db_password) or die('Connection error: '.mysql_error());
echo 'connection successful';
?>
I was wondering whether it is me or maybe the install of apache/mySQL that I am using that is causing such an absurdity.
Something must be screwed up with your install:
marc#panic:~$ php -a
php > $x = mysql_connect('bleargh', 'foo', 'bar') or die(mysql_error());
PHP Warning: mysql_connect(): Unknown MySQL server host 'bleargh' (2) in php shell code on line 1
Unknown MySQL server host 'bleargh' (2)marc#panic:~$
About all I can think of is you've got a DNS server that returns a valid address for ALL lookups, causing all hostnames to resolve.
try this one
$db_host = "localhost";
$db_username = "root";
$db_password = "";
$con = mysql_connect($db_host,$db_username,$db_passwd);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
echo 'connection successful';
mysql_close($con);
?>
It will always echo 'connection successful' because you aren't checking the status of the connection.
if (!$myConn) {
echo 'Sorry, there was an error '.mysql_error();
} else {
echo 'connection successful';
}
Depending on how you executed the code, you might be running into this:
If a second call is made to mysql_connect() with the same arguments,
no new link will be established, but instead, the link identifier of
the already opened link will be returned. The new_link parameter
modifies this behavior and makes mysql_connect() always open a new
link, even if mysql_connect() was called before with the same
parameters. In SQL safe mode, this parameter is ignored.
So, either do an explicit check or:
$myConn = mysql_connect($db_host, $db_username, $db_password, true) or die('Connection error: '.mysql_error());
Hey i'm trying to find out whether my sql query failed or not. I want it so if it does fail redirect to form page using the code below:
$checkconnection = mysql_connect('localhost', $dbuser, $dbpass)
or die();
if(!$checkconnection)
{
$_SESSION['errormsg'] = "<div style='padding-left: 50px;color:#FF0000'>Cannot connect to specfied database!</div>";
header("Location: install.php");
}else{
echo('Connection Successful!');
}
using that all it says is this:
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'nzcraftn_admin'#'localhost' (using password: YES) in /home/nzcraftn/public_html/phishnet/install/install_submit.php on line 17
Try this one
$checkconnection = #mysql_connect('localhost', $dbuser, $dbpass)
it will hide default error and trigger your own
The return value of mysql_connect being false only indicates failure. If it returns FALSE, the or die() expression will exit the php script. That's the reason why you don't sea any of it's output.
Remove the or die() command, and display the actual error in your if( !$checkconnection ) clause. The reported error can be retrieved using mysql_error().
It's only displaying the warning because your or die() isn't outputting anything (empty parameter list). Try this instead:
<?php
//Start the session
session_start();
//Do the conntection
$checkconnection = #mysql_connect('localhost', $dbuser, $dbpass);
//Check if it's valid
if(!$checkconnection) {
//Add it up to the session, and redirect
$_SESSION['errormsg'] = "<div style='padding-left: 50px;color:#FF0000'>Cannot connect to specfied database!</div>";
session_write_close();
header("Location: install.php");
exit();
} else{
//Yay
echo('Connection Successful!');
}
?>
The answer by genesis just supresses the warning, but still might work
If you want it 'clean' you can try/catch the error:
(directly from the comments on php.net/mysql_connect:
// Assign variables
global $db_connection, $db_server, $db_database, $db_username, $db_password;
$db_server = $server;
$db_database = $database;
$db_username = $username;
$db_password = $password;
// Attempt connection
try
{
// Create connection to MYSQL database
// Fourth true parameter will allow for multiple connections to be made
$db_connection = mysql_connect ($server, $username, $password, true);
mysql_select_db ($database);
if (!$db_connection)
{
throw new Exception('MySQL Connection Database Error: ' . mysql_error());
}
else
{
$CONNECTED = true;
}
}
catch (Exception $e)
{
echo $e->getMessage();
}