mysqli_select_db() not working properly ..? - php

function db_connect($db_host, $db_user, $db_pass, $db_name) {
$db_connect = mysqli_connect($db_host, $db_user, $db_pass) or die('Could not connect: ' . mysqli_error($db_connect));
$db_select = mysqli_select_db($db_name, $db_connect) or die ('Could not select ' . $db_name . ': ' . mysqli_error($db_select));
}
Every variable is defined. All that appears is
Could not select CMS:
There isn't even an error message. What am I doing wrong? As far as I am aware, it is connecting to MySQL, but it isn't connecting to the specified database 'CMS'.

According to php.net, mysqli_select_db exepts to be first parameter MYSQLI link, seccond DB Name
bool mysqli_select_db ( mysqli $link , string $dbname )
http://php.net/manual/en/mysqli.select-db.php
You should turn on error reporting for next time, to catch that error.
error_reporting(1);

Related

Strange behaviour when connect to database in php/mysql

I'm connecting to Mysql Database With following code. I'm using mysqli. But It's not connecting to mysql database.
define("HOST", "hostname");
define("USER", "username");
define("PASS", "password");
define("DB", "dbname");
$link = mysqli_connect(HOST, USER, PASS) or die("Couldn't make database connection.");
$db = mysqli_select_db($link, DB) or die("Couldn't select database");
Strange things is that when I delete or die("Couldn't make database connection.") and or die("Couldn't select database"); then it's connect to db. Why ? Is there anything I'm doing wrong ?
This is the proposed way to handle the situation:
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}

connecting to a database using php

I am very new to PHP so this is my first attempt to connect to a mysql database through a php file and I am getting this message. I dont know how much anyone can help me with this or if at least someone can guide me to a right direction
Can not use : soum_email1:
And my php looks like this
<?php
define('DB_NAME', 'soum_email1');
define('DB_USER', 'soum_email');
define('DB_PASSWORD', 'Qe232f9');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!link){
die('could not connect:' . mysql_error());
}
$db_selct = mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('Can not use : ' . DB_NAME . ':' .mysql_error());
}
echo 'connection sucessful';
?>
You are assigning the mysql_select_db() function $db_selct, but then checking $db_selected (which with the code you've posted is always falsey.
Also, link should be $link (on line 9).
Your code should be:
define('DB_NAME', 'soum_email1');
define('DB_USER', 'soum_email');
define('DB_PASSWORD', 'Qe232f9');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link){
die('could not connect:' . mysql_error());
}
$db_selct = mysql_select_db(DB_NAME, $link);
if(!$db_selct){
die('Can not use : ' . DB_NAME . ':' .mysql_error());
}
echo 'connection sucessful';
You should note though that the mysql_* family of functions are now deprecated, and you should consider using MySQLi or PDO.
First of all:
Please use the pdo or mysqli database like Quentin wrote in the first comment.
Further you should name your variables right,
$db_selct = mysql_select_db(DB_NAME, $link);
and
if(!$db_selected){
die('Can not use : ' . DB_NAME . ':' .mysql_error());
}
have different variable names.

How to connect to remote mysql database using php (hosted on dotCloud)

I am unable to connect to my database residing on dotCloud. I tried:
$mysqli = new mysqli($db_host, $db_user, $db_password, $db_name);
and
$mysqli = mysqli_connect($db_host, $db_user, $db_password, $db_name);
and
$mysqli = new mysqli($remote_server, $db_user, $db_password, $db_name);
and
$mysqli = mysqli_connect($remote_server, $db_user, $db_password, $db_name);
but it fails to connect, and I get "Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data."
I retrieve variables dynamically above the mysqli script with the following:
$env = json_decode(file_get_contents("/home/dotcloud/environment.json"));
$db_user = $env->DOTCLOUD_DB_MYSQL_LOGIN;
$db_password = $env->DOTCLOUD_DB_MYSQL_PASSWORD;
$db_host = $env->DOTCLOUD_DB_MYSQL_HOST;
$db_port = $env->DOTCLOUD_DB_MYSQL_PORT;
$remote_server = '$db_host:$db_port';
//I also define $db_name here
$db_name = 'mydbname';
I also have the following code below the mysqli script:
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
$result["status"] = "failed";
$result["message"] = "Failed to connect to database.";
echo json_encode($result);
exit;
} else {
// Successfully connected!
$stmt = $mysqli->stmt_init();
echo "<p>Successfully connected!!</p>";
}
What am I doing wrong?
There are a couple of things wrong in your code.
1. Your $remote_server variable is using a single quote
$remote_server = '$db_host:$db_port';
This means that $remote_server will not expand the $db_host and $db_port variables. You should use double quotes. If you used the variable as it is, it wouldn't work for you.
$remote_server = "$db_host:$db_port";
See this page for more info:
http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single
2. You are not using the mysql port when connecting, which is required on dotCloud since it doesn't run mysql on the standard port of 3306.
Your code:
$mysqli = new mysqli($db_host, $db_user, $db_password, $db_name);
The correct code, using the variables you already declared above:
$mysqli = new mysqli($db_host, $db_user, $db_password, $db_name, $db_port);
More info can be found here: http://www.php.net/manual/en/mysqli.quickstart.connections.php
For a complete example, it will look like this.
$env = json_decode(file_get_contents("/home/dotcloud/environment.json"));
$db_user = $env->DOTCLOUD_DB_MYSQL_LOGIN;
$db_password = $env->DOTCLOUD_DB_MYSQL_PASSWORD;
$db_host = $env->DOTCLOUD_DB_MYSQL_HOST;
$db_port = $env->DOTCLOUD_DB_MYSQL_PORT;
//I also define $db_name here
$db_name = 'mydbname';
$mysqli = new mysqli($db_host, $db_user, $db_password, $db_name, $db_port);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
try like this: I think it will help you.
$connect = mysql_connect($mysql_host, $mysql_user, $mysql_password);
if (!$connect) {
die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully';
$db = mysql_select_db($mysql_database,$connect);
if (!$db) echo"'Could not select database";

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.

"No database selected"... but only in a function

Okay, so I have the weirdest problem right now. My code is fine! It works PERFECTLY as I want and expect it to, which is a major shock to me, because every time I go to do MySQL I get endless problems that I can never find a solution to.
But today, everything works perfectly. So what's the problem? The problem is that when I try to wrap my code in a function, it just... stops working! I have error checking after every step and it works fine when in it's own file and lines. But I need to put it in a function so I can add parameters (hence the "extraQuery" variable), and "return" it so that I can access it from a separate file.
Here is my base code:
$link = mysql_connect($db_host, $db_user, $db_pass) or die ("Unable to connect: " . mysql_error());
mysql_select_db($db_name, $link) or die("Couldn't connect to database: " . mysql_error());
$extraQuery = "";
$result = mysql_query("SELECT * FROM things " . $extraQuery . " ORDER BY RAND() LIMIT 1", $link);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
mysql_close($link);
echo($row['content']);
As I said, it works completely fine as that is. But when I do this....
function getResult(){
$link = mysql_connect($db_host, $db_user, $db_pass) or die ("Unable to connect: " . mysql_error());
mysql_select_db($db_name, $link) or die("Couldn't connect to database: " . mysql_error());
$extraQuery = "";
$result = mysql_query("SELECT * FROM things " . $extraQuery . " ORDER BY RAND() LIMIT 1", $link);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
mysql_close($link);
echo($row['content']);
}
getResult();
..It stops working at the second line, telling me "No database selected". But as you can see, I am explicitly selecting a database that DOES exist and otherwise works when it's not in a function.
And just to stress this, it is NOT my user permissions, nor is it the name of the database; because it works perfectly when outside of the function.
Any possible aid would be greatly appreciated.
Due to variable scope your database variables are not available inside of the function. You need to pass it as an argument for getResult() to have access to it:
function getResult($db_host, $db_user, $db_pass, $db_name, $extraQuery){
$link = mysql_connect($db_host, $db_user, $db_pass) or die ("Unable to connect: " . mysql_error());
mysql_select_db($db_name, $link) or die("Couldn't connect to database: " . mysql_error());
$extraQuery = "";
$result = mysql_query("SELECT * FROM things " . $extraQuery . " ORDER BY RAND() LIMIT 1", $link);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
mysql_close($link);
echo($row['content']);
}
getResult();
variables $db_host,..., $db_name are there because you wanted to hide your access, or the function is exactly as it is written here?
If it is exactly you may need to declare these variables global (first row of the function: global $db_host,..., $db_name;), else their value inside a function is uninitialized.
NOTE: It is not good to use this. Just think your code to avoid this and as advised use at least MySQLi or PDO
It looks like the variables to access the database are not in the scope of the function.
You'd need to do something like:
function getResult( $db_host, $db_user, $db_pass, $db_name)
Then call the function with:
getResult( $db_host, $db_user, $db_pass, $db_name);
Or declare all of those variables as global variables, like so:
global $db_host, $db_user, $db_pass, $db_name;
This makes sure they are in the scope of the function. Otherwise, they are all undefined.
You need to declare $db_host, $db_name,etc as global, or pass them to the function, like this.
function getResult($db_host, $db_user, $db_pass){
//
}
getResult('localhost', 'user', 'pass');

Categories