I have my 'dbinterface' class with a connect function. When i run this i get a statement saying "Query didn't work. No database selected"
class dbinterface {
private $_dbLink;
private $dbHost = 'host';
private $dbUser = 'user';
private $dbName = 'name';
private $dbPass = 'pass';
private $dbUserTable = 'table';
public function connect ()
{
$this->_dbLink = mysql_connect($this->_dbHost, $this->_dbUser, $this->_dbPass);
if(!$this->_dbLink)
throw new Exception ("Could not connect to database. " . mysql_error());
}
I made a change to the public connect function.
public function connect ()
{
$this->dbLink = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass);
mysql_select_db($this->dbUserTable);
if(!$this->dbLink)
throw new Exception ("Could not connect to database. " . mysql_error());
}
Unfortunately it output the same result. I am new to PHP and still learning, i have tried everything i know so ANY help is very much appreciated.
Unless you use an absolute schema.table type reference in your queries, you HAVE to specify a default database with mysql_select_db(). Without that,
SELECT somefield FROM sometable
fails with "no database selected" because MySQL doesn't know WHICH database it should look in for that table.
This would work, however:
SELECT somefield FROM name_of_db.name_of_table
without a default database, as you've explicitly stated you're using the "name_of_db" database.
Related
I'm a learning programmer and I'm trying to learn PHP.
Now the point is that I use alot of db connections in my new project. This are alot of different DB's an require different connection.
Does anybody a way where I can create a function what makes me use my code like this? Getdata($User, $beerbrand, $sales); and use these variables in my code? I use the same way to get the data out of the database everytime. But it's alot of code, where I think it should be possible to make that a little easier.
The way I use now:
mysql_connect($host, $user, $password) or die ("cannot connect");
mysql_select_db("$db_name");
$stuff = mysql_query("SELECT * FROM beers ORDER BY ID");
while($frontstuff = mysql_fetch_array($stuff)){
$us = $frontstuff['Beer'];
}
If you think this is a stupid question, please be gentle and explain it to me in a easy way.
Best regards
<?php
class Database {
private $connection; //Database Connection Link
private $userName; //Database server User Name
private $password; //Database server Password
private $database; //Database Name
private $hostname; //Name of database server
public function __construct() {
$this->hostname=your servername
$this->userName=yourusername
$this->password=yourpasswrod
$this->database=your bb name
try {
$this->connectlink = mysql_connect($this->hostname,$this->userName,$this->password);
if(!($this->connectlink)) {
throw new Exception("Error Connecting to the Database".mysql_error(),"101");
}
if(!mysql_select_db($this->database, $this->connectlink)) {
throw new Exception("Error Connecting to the Database1".mysql_error(),"101");
}
}catch(Exception $e){
//print_r($dbConfig);
echo $e->getMessage();
}
}
public function __destruct() {
#mysql_close($this->connectlink);
}
}
you can crete a database file like this for specifying connnection
and you can use this file in processing your query in another pages.Eg
<?php
include_once("database.php");
function __construct(){
$this->db = new Database;
}
public function getstuf($parameter){
$stuff = mysql_query("SELECT * FROM beers ORDER BY ID");
while($frontstuff = mysql_fetch_array($stuff)){
$us = $frontstuff['Beer'];
}
return stuff;
}
}
I am receiving the following error when loading my index page:
Fatal error: Call to a member function prepare() on a non-object in /Applications/MAMP/htdocs/parse/helloworld/helloworld/libraries/Database.php on line 32
I will place all of the relevant code below, sorry for the length but it should be fairly straight forward to read. The short version is I am practicing PDO and PHP classes so I am remaking an existing project I had on a different machine. (which is why a there is a lot of calls in the index file which acts more like a controller).
I am pulling my hair out here because it works on my other machine and from what i can tell the two projects are identical... I am just getting this error. I had this in my previous project, but that was because I had misspelled the database in the config file... I am 100% positive I did not do that again but I don't know what else I missed -- clearly the PDO class is not being made if I var_dump it returns null... Any and all help would be greatly appreciated (especially if it is in regards to my PDO class style I am just following a blog which seemed to make sense when it worked).
EDIT:
After some debugging it was clear that the try block in the database class was failing because a connection could not be established. This was clear after running $this->error = $e->getMessage() which returned:
string(119) "SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/Applications/MAMP/tmp/mysql/mysql.sock' (2)"
As the accepted answer below states the error indicates localhost trying to connect via a unix socket and mysqld not being able to able to accept unix socket connections.
So the original error leads to the ultimate question of: how do you connect to a unix socket when mysqld is not accepting unix socket connections and/or why does mysqld not accept unix socket connections?
End EDIT.
This is my (relevant) PDO class:
<?php
class Database {
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
private $dbh;
private $error;
private $stmt;
public function __construct() {
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array (
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try {
$this->dbh = new PDO ($dsn, $this->user, $this->pass, $options);
} // Catch any errors
catch ( PDOException $e ) {
var_dump($dsn);
$this->error = $e->getMessage();
}
}
public function query($query) {
$this->stmt = $this->dbh->prepare($query);
}
This is the index file that gets called
<?php
require('core/init.php');
//Create objects...
$type = new Type;
$post = new Post;
$group = new Group;
$follower = new Follower;
//Create template object
$template = new Template('templates/front.php');
$template->types = $type->getAllTypes();
$template->groups = $group->getAllGroups();
$template->posts = $post->getAllPosts();
$template->replies = $post->getReplies();
$template->followers = $follower->getAllFollowers();
echo $template;
and these are the other relevant files:
config --
<?php
//DB Params
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "root");
define("DB_NAME", "dobbletwo");
define("SITE_TITLE", "Welcome To Dooble!");
init --
//include configuration
require_once('config/config.php');
//helper functions
require_once('helpers/photo_helper.php');
require_once('helpers/system_helper.php');
//Autoload Classes
function __autoload($class_name){
require_once('libraries/'.$class_name . '.php');
}
for the sake of brevity (which may be far gone at this point I will only show one of the classes i load to prove that I am constructing the db(type, post, group, follower, template...)
<?php
class Type {
//Initialize DB variable
public $db;
/*
* Constructor
*/
public function __construct(){
$this->db = new Database;
}
the mysql libraries seem to interpret localhost as meaning you want to connect via a unix socket. your error indicates your mysqld isn't setup to accept unix socket connections.
to connect via tcp/ip instead, change define("DB_HOST", "localhost"); to define("DB_HOST", "127.0.0.1");
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?
Sorry if the title of this question does not explain the actual question. I couldn't find appropriate word to name the title of this question.
I have a database class like so:
class Database
{
private $link;
private $host, $username, $password, $database;
public function __construct($setup)
{
if ($setup == 'default') {
$this->host = 'localhost';
$this->username = 'root';
$this->password = 'root';
$this->database = 'infobox_sierraleone';
}
if ($setup == 'promo') {
$this->host = 'localhost';
$this->username = 'root';
$this->password = 'root';
$this->database = 'infobox';
}
$this->link = mysql_connect($this->host, $this->username, $this->password)
OR die("There was a problem connecting to the database.");
mysql_select_db($this->database, $this->link)
OR die("There was a problem selecting the database.");
}
public function __destruct()
{
mysql_close($this->link)
OR die("There was a problem disconnecting from the database.");
}
}
I have created to different objects of the class above in a separate file:
include 'conn/database.php';
$db = new Database('default');
$db_promo = new Database('promo');
When i run the above script, i get this message:
There was a problem disconnecting from the database.
I realise that this message if from the __destruct() function.
I have researched for some time and i am still not clear why this message is showing and how to get rid of it.
Any sort of help will be much appreciated.
Thank You.
Edit:
removed the return statement that was in the constructor.
Since you're not destroying your own objects, they get destroyed by PHP when the script is finished. PHP then just destroys anything it's got, but not necessarily in the right order.
In this case, apparently PHP kills the MySQL connection first and then continues destroying other objects, including yours. Your object then tries to disconnect the already disconnected database connection, which would go unnoticed, if you wouldn't let the script die on failure.
I have an application in which I want to authenticate a user from a first database & manage other activities from another database.
I have created two classes. An object of the classes is defined in a file:
$objdb1=new db1(),$objdb2=new db2();
But when I try to call $objdb1->fn(). It searches from the $objdb2 & is showing table1 doesnot exists?
My first file database.php
class database
{
private $hostname;
private $database;
private $username;
private $password;
private $dblinkid;
function __construct()
{
if($_SERVER['SERVER_NAME'] == 'localhost')
{
$this->hostname = "localhost";
$this->database = "aaaa";
$this->username = "xxx";
$this->password = "";
}
else
{
$this->hostname = "localhost";
$this->database = "xxx";
$this->username = "xxx";
$this->password = "xxx";
}
$this->dblinkid = $this->connect();
}
protected function connect()
{
$linkid = mysql_connect($this->hostname, $this->username, $this->password) or die("Could not Connect ".mysql_errno($linkid));
mysql_select_db($this->database, $linkid) or die("Could not select database ".mysql_errno($linkid)) ;
return $linkid;
}
Similarly second file
class database2
{
private $vhostname;
private $vdatabase;
private $vusername;
private $vpassword;
private $vdblinkid;
function __construct()
{
if($_SERVER['SERVER_NAME'] == 'localhost')
{
$this->vhostname = "xxx";
$this->vdatabase = "bbbb";
$this->vusername = "xxx";
$this->vpassword = "";
}
else
{
$this->vhostname = "localhost";
$this->vdatabase = "xxxx";
$this->vusername = "xxxx";
$this->vpassword = "xxxx";
}
$this->vdblinkid = $this->vconnect();
}
protected function vconnect()
{
$vlinkid = mysql_connect($this->vhostname, $this->vusername, $this->vpassword) or die("Could not Connect ".mysql_errno($vlinkid));
mysql_select_db($this->vdatabase, $vlinkid) or die("Could not select database ".mysql_errno($vlinkid)) ;
return $vlinkid;
}
Third file
$objdb1 = new database();
$objdb2 = new database2();
Can you help me on this?
Regards,
Pankaj
Without knowing your classes, it is difficult to help. If you are using PDO, I can guarantee you that you can create multiple instances connected to different databases without any problem. If you are using the mysql_ family of functions you probably just forgot to set the link_identifier parameter (see here).
However, having a class db1 and a class db2 sounds like a code smell to me. You probably want to have two instances of the same class with different attributes.
Each time you call mysql_connect() or the equivalent mysqli functions, if a connection already exists using those same credentials it gets reused - so anything you do to modify the state of the connection, including changing database, charsets, or other mysql session variables affects "both" connections.
Since you are using the mysql_connect() function you have the option to force a new connection each time but this is not supported on all the extensions (IIRC mysqli and PDO don't alow for this).
However IMHO this is the wrong way to solve the problem. It just becomes messy trying to keep track of what's connected where.
The right way would be to specify the database in every query:
SELECT stuff FROM aaaa.first f, aaaa.second s
WHERE f.something=s.something;
Most likely your class does not pass the appropriate connection resource to the database functions. The second argument to e.g. mysql_query() is the connection resource. Simply store this resource in an instance variable on connection, and use it every time you do something with the database.
Your problem may be in checking if the SERVER_NAME is "localhost". Seems like you may be using the same connection strings in both classes. What is $_SERVER['SERVER_NAME'] resolving to?
You're looking for the fourth parameter of mysql_connect(), which states that it shouldn't reuse existing connections:
$dbLink1 = mysql_connect($server, $user, $pass, true);
mysql_select_db($db1, $dbLink1);
$dbLink2 = mysql_connect($server, $user, $pass, true);
mysql_select_db($db2, $dbLink2);
mysql_query("SELECT * FROM table1", $dbLink1); // <-- Will work
mysql_query("SELECT * FROM table1", $dbLink2); // <-- Will fail, because table1 doesn't exists in $db2
Passing the fourth parameter as true to mysql_connect resolves the issue.
$linkid = mysql_connect($this->hostname, $this->username, $this->password,true) or die("Could not Connect ".mysql_errno($linkid));