Check whether a mysql_connect() failed or not? - php

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

Related

The function does not connect with the query to the database

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/>";
}

Mysql multiple database connection doesn't work

I just tried to connect a secondary database like this example bellow but i don't know why refuse to work. Any idea?
I mention that each database connection works properly individualy.
$db_HOST = "localhost";
$db_USER = "db_user";
$db_PASS = "db_pass";
$db_NAME1 = "db_test1";
$db_NAME2= "db_test2";
$db_LINK1 = mysql_connect($db_HOST, $db_USER, $db_PASS) or die("Technical revision. Please try again later!");
mysql_select_db($db_NAME1, $db_LINK1) or die("Couldn't select database");
$db_LINK2 = mysql_connect($db_HOST, $db_USER, $db_PASS, true) or die("Technical revision. Please try again later!");
mysql_select_db($db_NAME2, $db_LINK2) or die("Couldn't select database");
Errors i get in the log file:
PHP Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /config/global/variables.php on line 27
PHP Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in config/global/hello.php on line 3
Thank you!
Do the following (with PDO instead of mysql_connect as the latter is deprecated):
$db_HOST = "localhost";
$db_USER = "db_user";
$db_PASS = "db_pass";
$db_NAME1 = "db_test1";
$db_NAME2= "db_test2";
try {
$db_LINK1 = new PDO('mysql:host='.$db_HOST.';dbname='.$db_NAME1, $db_USER, $db_PASS);
foreach($db_LINK1->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
try {
$db_LINK2 = new PDO('mysql:host='.$db_HOST.';dbname='.$db_NAME2, $db_USER, $db_PASS);
foreach($db_LINK2->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
More info here: php.net/manual/en/pdo.connections.php
If the second connection fails check the exact error message.
You should really use PDO but your code works if you use your link in your db select. For example:
$db1 = mysql_connect($hostname, $username, $password);
$db2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $db1);
mysql_select_db('database2', $db2);
that should work. You forgot to select which database should be used on every link.
I thnk I found the problem.
I forgot to change all queries accordind to the new multiple connection.
LE: Solve confirmed! Thank you all!

How do I start a PGSQL connection in PHP?

I am trying to start a pgsql connection in php but i get pg_last_error(): No PostgreSQL link opened yet Please forgive my amateur question as i am a bit new to php.
Here is my php code:
<?php
$connect = pg_connect("host=xxx.xx.xxx.21 dbname=d106 user=b16 password=bran") or die("Could not connect: " . pg_last_error());
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bikes");
if (!$result)
{
echo "no results ";
}
while($row = pg_fetch_array($result))
{
$coor = $row['thestartgeom'];
echo $coor;
}
pg_close($connect);
?>
In your pgsql connection you have missed the port number.
Try this way.
<?php
$host = "host=xxx.xx.xxx.21";
$port = "port=5432";
$dbname = "dbname=d106";
$credentials = "user=b16 password=bran";
$connect= pg_connect( "$host $port $dbname $credentials" ) or die("Could not connect: " . pg_last_error());
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bikes");
if (!$result)
{
echo "no results ";
}
while($row = pg_fetch_array($result))
{
$coor = $row['thestartgeom'];
echo $coor;
}
pg_close($connect);
?>
You can store PgSQL connection code in one PHP file to reuse
pgsql_db_connection.php file
<?php
$host = "host=xxx.xx.xxx.21";
$port = "port=5432";
$dbname = "dbname=d106";
$credentials = "user=b16 password=bran";
$connect= pg_connect( "$host $port $dbname $credentials" );
if(!$connect){
echo "Error : Unable to open database\n";
}
?>
Call pgsql_db_connection.php file in other php files to use your database connection.
<?php
require_once('pgsql_db_connection.php');
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bikes");
if (!$result)
{
echo pg_last_error($connect);
exit;
}
while($row = pg_fetch_array($result))
{
$coor = $row[0];
echo $coor;
}
?>
When pg_connect fails, it returns FALSE and produces a PHP warning with the detailed information on why it couldn't initiate the connection. If you can see the other message:pg_last_error(): No PostgreSQL link opened yet that you're reporting, I'd expect you should be able to see the previous one too, which is the one normally telling the reason of the failure.
If the display_errors configuration setting is set to 0, the first message would not show up on the browser/screen but the second would not either.
Anyway, assuming you can't have access to pg_connect warnings for whatever reason such as custom error handler, what's wrong with your code is that pg_last_error() must have an already opened connection to work.
To access the detailed error message from a failed pg_connect, the built-in PHP function error_get_last() (returning an array) could be used.
<?
$connect= pg_connect("your-connect-string");
if (!$connect) {
print_r(error_get_last());
// for only the message:
// echo error_get_last()['message']
}
die("DB connection failed");
?>
See also how to catch pg_connect() function error? if you prefer exceptions.

php Insert Query - Why Are There Two Connections to a Database?

In my script I link to a page that connects to my database :
include "connect.php";
connect.php
<?php
error_reporting(E_ERROR);
/* Allows PHP to connect to your database */
// Database Variables
$Host = "myhost";
$User = "username";
$Password = "password";
$DBName = "database";
// Connect to Database
$connect = mysql_connect($Host, $User, $Password)
or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($DBName)
or die ("Could not connect to database ... \n" . mysql_error ());
?
Then in another script I have an insert query:
include "connect.php";
$Link = mysql_connect($Host, $User, $Password);
$Query = "INSERT INTO mytable VALUES ('0','".mysql_escape_string($forename)."','".mysql_escape_string($surname)."', '".mysql_escape_string($username)."', '".mysql_escape_string($password)."', '".mysql_escape_string($email)."')";
if(mysql_db_query ($DBName, $Query, $Link)) {
$message = "You have successfully registered";
header("Location: register.php?message=".urlencode($message));
} else {
die("Query was: $Query. Error: ".mysql_error($Link));
}
}
}
Why is this necessary :
$Link = mysql_connect($Host, $User, $Password);
Hasn't the connection already been established?
There is no point in doing this, especially as mysql_* functions will assume the last opened connection if none is given.
However, even with two calls to mysql_connect, only one connection is made. From the docs:
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.
So by default, the existing connection will be returned.

2 MySQL connections across 2 differents host

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

Categories