"No database selected" error from mysql db and myphp site - php

I keep getting 'No database selected' everytime I login to my php website. The backend is MySQL database. The following code is in my database.php file. I appreciate any help on the issue. Thank you.
{
public $conn;
function __construct($server, $user_name, $pass, $db) {
$this->conn = mysql_connect($server, $user_name, $pass);
mysql_select_db($db, $this->conn);
}
function __destruct() {
mysql_close($this->conn);
}
}

What do you get if you do this?
mysql_select_db($db, $this->conn)
|| die ("select_db failed: " . mysql_error($this->conn));
It may halp you understand what's going wrong.
Also please stop using the mysql_ apis.

Related

Issue with MySQL connection inside class

I have a MySQL class that I use to connect to MySQL. But after doing the upgrade of PHP to 5.4.16, it doesn't work any more. Can anyone help with it?
Below is the code that I use. Whenever I try to connect it gets into the error part.
final class MySQL {
private $connection;
public function __construct($hostname, $username, $password, $database) {
if (!$this->connection = mysql_connect($hostname, $username, $password)) {
exit('Error: Could not make a database connection using ' . $username . '#' . $hostname);
}
}
SOLVED : Did the following on command prompt and
setsebool -P httpd_can_network_connect=1
More details here :
https://maanasroyy.wordpress.com/2015/06/04/php-cant-connect-to-mysql-with-error-13-but-command-line-can/

PHP. How can I create a functions' library?

I've got not too much experience programing but I've done a little application with a few PHP files and I'd like to optimize it.
I want to extract all the repeated code and place it inside a folder as a PHP file, that I will call later, when I need the code.
For example this lines are repeated in all my files:
$servername = "ejemplo.es";
$username = "ramon";
$dbname = "bbdd";
$password = "loquesea";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
first of all, you should read a php tutorial about functions and object orientated programming.
In your case, you could have a class for your database things called Database, which would look something like this:
<?php
class Database
{
private $_connection = null;
public function __construct($host, $username, $password, $database)
{
// connect to database and store the connection for further use
}
public function doThisAndThat()
{
// do some fancy database stuff
}
public function __destruct()
{
// important for databases is to disconnect from them
}
}
Then all you have to do is include your Database class file and call it like that:
$db = new Database($host, $username, $password, $database);
$db->doThisAndThat();

Including php file with database connection error

I want a generic php file with all the database info (dbname,host,username,password)
But when I include the page, in like index.php I get this error:
Access denied for user 'apache'#'localhost' (using password: NO)
connect.php
<?php
class dbconnect{
private $host = '**';
private $user = '**';
private $pass = '**';
public $con;
function Connect($db = '**') {
if($db=='**'){
$this->host="localhost";
$this->user="**";
$this->pass="**";
$db="**";
}else{
$this->host="**";
$this->user="**";
$this->pass="**";
}
$this->con = mysql_connect($this->host,$this->user,$this->pass);
if (!$this->con)
{
die('Could not connect: ' . mysql_error());
}
$blaa = mysql_select_db($db, $this->con);
mysql_query("SET NAMES UTF8");
return $blaa;
}
function Disconnect() {
//$this->con = mysql_connect($this->host,$this->user,$this->pass);
mysql_close();
}
}
?>
I am sure the ** information is correct because when I specify it as:
$con=mysqli_connect("example.com","example","password","my_db");
In index.php it works
It's important to note, your test case doesn't actually prove it works.
What does this output:
$conn = mysql_connect("example.com", "user", "password");
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
As you won't necessarily get the information that's failing it without that.
To top that off, let's simplify your class a little bit for debugging purposes:
class dbconnect
{
private $host = '**';
private $user = '**';
private $pass = '**';
public $con;
public function Connect($host = "localhost", $user = "root", $pass = "")
{
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->con = mysql_connect($this->host, $this->user, $this->pass);
if (!$this->con) {
die('Could not connect: ' . mysql_error());
}
$blaa = mysql_select_db($db, $this->con);
mysql_query("SET NAMES UTF8");
return $blaa;
}
public function Disconnect()
{
mysql_close($this->con);
}
}
Now what do you get when you do
$db = new dbconnect("example.com", "user", "password");
Be sure you're using credentials that work, and that you're not running into issues such as default values or incorrect variable assignment through these methods.
Now, if you don't want to provide the values, you can simply:
$db = new dbconnect();
Public Service Announcement
Check out PHP's PDO or at minimum (but really, just use PDO) the mysqli alternative. PHP's mysql extension is NOT secure, and you should not be using it in any environment, ever.
If the connection information are correct, check your MySQL User's host access permission:
SELECT user, host FROM mysql.user
If "localhost" is set, then the user can only access the database locally, otherwise "%" will open access.
Usually it is an issue with the connection credentials.
Check that you can log into your mysql using the details you have set for that website.
mysql -u apache -p
It will then ask you for the password.
If that login does not work, then you have a problem with that user's mysql account.
You use incorrect parameters for accessing. Just dump variables which at the line $this->con = mysql_connect($this->host,$this->user,$this->pass);. You can use debugger or echo, print instructions.
Furthermore use PDO extension for accessing to databases. It's better!
Why shouldn't I use mysql_* functions in PHP?

mysqli doesn't return instance with die()

I have function :
function dbConnect($usertype, $connectionType = 'mysqli') {
// some code hare
return new mysqli($host, $user, $pwd, $db) or die ('Cannot open database');
}
but when I try this:
$conn = dbConnect('read');
$result = $conn->query('SELECT * FROM images');
function dosn't return anything and it say :
Fatal error: Call to a member function query() on a non-object in
C:\xampp\htdocs\phpsols\mysql\mysqli.php on line 10
but it works this way(without die())
return new mysqli($host, $user, $pwd, $db);
The [..] or die() construct leads to funny behaviour in conjunction with the return statement: The whole thing is interpreted as a boolean expression.
And because new mysqli will never be false, the "die" is never processed, and thus, your function returns true instead of a newly created instance of mysqli.
If you still would like to use or die(), do this:
$result = new mysqli($host, $user, $pwd, $db) ;
if (!$result) die ("Can't open database.");
return $result;
You can try this:
function dbConnect($usertype, $connectionType = 'mysqli') {
// some code hare
try {
return new mysqli($host, $user, $pwd, $db);
} catch(Exception $e) {
die ('Cannot open database');
}
}
aside from this funny one-liner problem, your idea of error handling is all wrong. Sadly, it was copy-pasted to other answer as well.
Here is the right code
$mysqli = new mysqli($host, $user, $pwd, $db);
if ( mysqli_connect_errno() )
{
throw new Exception(mysqli_connect_errno()." ".mysqli_connect_error());
}
return $mysqli;
Honestly, this die ('something'); thing is a childhood disease of PHP. Time to grow up a little.

Opening DB connection in class method

To open a DB connection, I currently use this class method :
function openDB() {
// 1. Create a database connection
$conn = mysqli_connect("x" , "x", "x","x");
if (!$conn)
{
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
However, I want to instead use my config file
require("assets/configs/db_config.php");
Obviously this file contains the DB connection information.
How can I do away with
$conn = mysqli_connect("x" , "x", "x","x");
And simply make $conn and make it use DB_Config.php instead?
For you config file return an array of the values you need
return array("host"=>"example.com", "dbname"=>"mydb", "username"=>"dbuser", "password"=>"secret");
Then in your openDb function do this.
function openDB() {
// 1. Create a database connection
$config = include("/path/to/config.php");
$conn = mysqli_connect($config["host"] , $config["username"], $config["password"],$config["dbname"]);
if (!$conn)
{
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
Change
function openDB()
to
function openDB($server, $user, $pass, $dbName)
and pass those variables to mysqli_connect
and pass data from included file.I suppose, you have them in some sort of constants or defines.
Also, it would be good idea to haveDB connection somewhere globally.

Categories