The function does not connect with the query to the database - php

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

Related

MySQL error message, mysql_connect(), any way to fix it?

So this is the error message:
PHP Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
This is the affected piece of code:
class wdClient {
var $dbLink; // The database link
var $prefix; // Table prefix
var $script; // The script running
/**
* Construct a new directory object.
*/
function wdClient() {
error_reporting(E_ALL ^ E_NOTICE);
$this->prefix = WDDBPREFIX;
// Connect to the database
$this->dbLink = mysql_connect(WDDBHOST, WDDBUSER, WDDBPASSWD);
// Select the database
mysql_select_db(WDDBNAME, $this->dbLink) or die('Sorry, The site is currently unavailable!');
}
where WDDBPREFIX, WDDBHOST, WDDBUSER, WDDBPASSWD, WDDBNAME are already defined in a config file.
I have tried simply using mysqli_connect instead of mysql_connect but it's not working.
Note: Never use MySQL, use this method!
//MySQLi information
$db_host = "localhost";
$db_username = "username";
$db_password = "password";
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error());
//select MySQLi dabatase table
$db = mysqli_select_db($connection, "table") or die("Error " . mysqli_error());
Good luck!
well, as pointed in here http://php.net/manual/en/function.mysqli-connect.php , you should make something like this:
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
Apparently, in your case it will look like this:
$link = mysqli_connect(WDDBHOST, WDDBUSER, WDDBPASSWD, WDDBNAME);
And then you can continue with your code...
if (!link){
die('Sorry, The site is currently unavailable!');
} else{
// write your SQL here and fetch it
}

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!

Can't induce error on $db_connect->select_db($name); ? PHP

I am a student.
I'm trying to deliberately induce an error in
$db_connect->select_db($db_name);
to check the error handling, but it won't give out an error?
The actual database name is 'cart', but i am using 'cartxx' to try and induce an error, but nothing happens, it runs as if there is no error. I don't have a database named 'cartxx'.
<?php
session_start();
$host = 'localhost'; // connects to the host server
$db_name = 'cartxx'; // name of the database we are connecting to
$db_username = 'root'; // username for database
$db_password = ''; // password for database
$db_connect = new mysqli($host, $db_username, $db_password); // connect to mysql
// If error
if (mysqli_connect_errno()) {
echo('Connection to database failed: ' . mysqli_connect_error());
exit();
}
// Select database
$db_connect->select_db($db_name);
// If error
if (mysqli_connect_errno()) {
echo 'Connection to database {$db_name} has failed: ' . mysqli_connect_error();
exit();
}
Thanks.
you need to pass default db name in connection string directly. if you need connect to one more database you can use select statment
$db_connect = new mysqli($host, $db_username, $db_password, $db_name);
for more :- http://php.net/manual/en/function.mysqli-connect.php
mysqli::selectdb will NOT return false if you give him an incorrect database name.
This function suits better a "i want to switch from database X to database Y" scenario, and will stay connected to database X if database Y is not found.
You can check the manual for this function.
A better way to select the database at connection is to use the mysqli constructor.

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.

Check whether a mysql_connect() failed or not?

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

Categories