Related
I already know that if you want to connect to a database using MySQL you have to provide the correct URL, username, password that is the normal thing here is my code:
<?php
$mysql_id = mysql_connect('localhost', 'root', '');
mysql_select_db('Booklet', $mysql_id);
if(!$mysql_id)
{
echo"cannot connect to database ";
}
?>
This code runs well, however if I messed with the username which is root it still connects here is the code:
<?php
$mysql_id = mysql_connect('localhost', 'rot', '');
mysql_select_db('Booklet', $mysql_id);
if(!$mysql_id)
{
echo"cannot connect to database ";
}
?>
Can anyone explain to me why is this happening?
As of PHP 5.5.0 mysql_* functions are deprecated and you should not code with thoses. Think of thoses function as a crawling zombie, you don't go and kiss it, do you ?
You should use MySQLi or PDO for doing operations on database. Please don't bother with mysql_* anymore, you dont want that. It's like asking to code on Windows Milenium, hell, even booting this thing is a nightmare.
Anyway, to answer the question you should write :
$mysql_id = mysql_connect('localhost', 'rot', '') or die(mysql_error());
Or better, you should look at the doc of MySqli and be free of thoses shackles. Think about that, please.
You never bothered checking for failure. Your code simply assumes success and blunders onwards.
$mysql_id = mysql_connect('localhost', 'rot', '') or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
mysql_select_db('Booklet', $mysql_id) or die(mysql_error());
All of the mysql_*() function return boolean false on failure. You need to check for that false. Never ever assume a DB operation succeeded. Always assume failure, check for that failure, and treat success as a pleasant surprise.
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
try to debug your code by adding mysql_error() like this
$mysql_id = mysql_connect('localhost', 'rot', '');
mysql_select_db('Booklet', $mysql_id);
echo " debug return: " . mysql_error();
or simply update your code if you have a newest version of php > 5.5.0
$mysql_id = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));
Using the new MySQLi functions, you would get a false back on trying to connect, also you can pass you database as fourth parameter. So your code could look like this:
<?php
if($mysql_id = mysqli_connect('localhost', 'root', '', 'Booklet'))
{
/* do something like mysqli_query($mysql_id, ... */
}
else
{
echo"cannot connect to database ";
}
?>
Let's say user have two databases hosted on single host and I need to connect to both of them so that I can use any table anytime without adding connection code multiple times.
I have implemented this in CodeIgniter with adding authorization details of both databases in database.php file and to load required database with $this->load->database('dbname'); in script.
Now, for core PHP, we can do this like:
mysql_connect ('host','user','password','port','dbname'); // connection with one database.
It was connected with my first database.
Now, I want to connect with second database:
1) I have not closed above connection and connected with second one with
mysql_connect ('host','user','password','port','dbname1');.
2) Would it be bad practice to do so ? Would it consume more objects ? Should we be required to close first one anyhow?
It is not neccessary to open 2 connection just to use tables from 2 databases on the same server. You just need to use the database.table notation. Doing that means that you can even join tables from different databases in the same query
SELECT t1.col1, t1.col2, t2.col2, t2.col2
FROM db1.table1 AS t1 JOIN db2.table1 AS t2 ON t1.col1 = t2.col3
So if you have connected to db1 initially you can use db2 tables and the same if you connected to db2 you can use db1 tables.
Have you tried this?
$mysqli1 = new mysqli("example.com", "user", "password", "database1");
$mysqli2 = new mysqli("example.com", "user", "password", "database2");
Why do you need two connections? The pros/advantages of two databases are actually primarily performance issues. But if you are on the same machine actually the only advantage you have, would be a cleaner separation. So it would be better to use one DB with two different prefixes for the table.
So you seperate the diffent data by prefix and not by DB.
You can do this by following object oriented approach
First of all create connection with two databases:
$Db1 = new mysqli('localhost','root','','database1'); // this is object of database 1
$Db2 = new mysqli('localhost','root','','database2'); // this is object of database 2
$query1 = 'select * from `table_name_of_database1`'; // Query to be run on DB1
$query2 = 'select * from `table_name_of_database2`'; // Query to be run on DB2
$result1 = $Db1->query($query1); // Executing query on database1 by using $Db1
$result2 = $Db2->query($query2); // Executing query on database2 by using $Db2
echo "<pre>";
/* Print result of $query1 */
if ($result1->num_rows > 0) {
while($row = $result1->fetch_assoc()) {
print_r($row);
}
} else {
echo "0 results";
}
/*========================================================*/
/* Print result of $query2 */
if ($result2->num_rows > 0) {
while($row = $result2->fetch_assoc()) {
print_r($row);
}
} else {
echo "0 results";
}
Conclusion: When you want to use database1 use $Db1 object and if you want to use database2 then use $DB2.
I don't think how to connect to 2 DBs simultaneously is the problem, as you have successfully done it ( or know how to do it ). I can gather that from your question. So I won't show how to do this. See other answers if you need to.
But to address your issues directly:
Would it be bad practice to do so ? Generally, you should avoid 2 simultaneous DB connection handles as much as possible. If you only need to get data from one DB and use them to do something on the other, your best bet is to put the data from DB1 into appropriate PHP variables, close the connection; then make the second connection. That would be cheaper than keeping 2 DB connections open at the same time. However, if you are doing something like INSERT INTO db1.table SELECT FROM db2.table AND ALSO NEED TO COMMIT OR ROLLBACK depending on success or failure of some queries, then AFAIK, you need to keep both connections open until your processes are over. You see, there always trade-offs. So you decide based on the need of your application and bear the cost.
As a practical example of this scenario, I once worked on a project where I needed to SELECT a table1, INSERT INTO a table2, if the INSERT succeeds, I delete all the rows from table1, if the DELETE fails, I rollback the INSERT operation because the data cannot live in the two tables at the same time.
Of course, my own case involved only one DB, so no need of a second connection. But assuming the two tables were on different DBs, then that may be similar to your situation.
Would it consume more objects ? No other objects other than the ones pointed out in 1 above, namely the DB connection handles according to your question.
Should we compulsory require to close first one anyhow ? Once again, depending on your application needs.
Instead of mysql_connect use mysqli_connect.
mysqli is provide a functionality for connect multiple database at a time.
Q: What cons are there to connect with other database without closing previous database?
A: When you connect to a database server physically are assigning resources to interact with you, if two databases are on the same server you would unnecessarily using resources that could be used to address other connections or other activities. Therefore you would be right close connections that do not need to continue using.
Q: Is this a appropriate practice to do so ? What is the best way to do so without opening this connection in every script multiple times ? I want this to get done in core php only as I have already know this in codeigniter.
One way SESSIONS, but you can't store database conections in sessions. Read in PHP.net this Warning: "Some types of data can not be serialized thus stored in sessions. It includes resource variables or objects with circular references (i.e. objects which passes a reference to itself to another object)." MySQL connections are one such kind of resource.
You have to reconnect on each page run.
This is not as bad as it sounds if you can rely on connection pooling via mysql_pconnect(). When connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection. The connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mysql_close() will not close links established by mysql_pconnect()).
Reference:
http://php.net/manual/en/function.mysql-pconnect.php
http://www.php.net/manual/en/intro.session.php
Can't pass mysqli connection in session in php
1) Is it possible to connect with more than one database in one script ?
Yes we can create multiple MySQL link identifier in a same script.
2) It should be not like to close one connection with mysql_close and open new one,rather both connection should open at a time and user can use any table from any of the database ?
Use Persistent Database Connections like mysql_pconnect
3) If it is possible,what can be disadvantage of this ? Will there create two object and this will going to create issue ?
I don't think so it create any issue other than increasing some load on server.
You can use like this
$db1 = mysql_connect($hostname, $username, $password);
$db2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('abc', $db1);
mysql_select_db('def', $db2);
For Database 1
mysql_query('select * from table1', $db1);
For Database 2
mysql_query('select * from table2', $db2);
The best way to use multiple databases is to use PDO functions
EXAMPLE
// database cobfigurations
$config= array(
// first database
array(
'type'=>'mysql', // DB type
'host'=>'localhost', // DB host
'dbname'=>'database1', // DB name
'user'=>'root', // DB username
'pass'=>'12345', // DB password
),
// second database
array(
'type'=>'mysql', // DB type
'host'=>'localhost', // DB host
'dbname'=>'database2', // DB name
'user'=>'root', // DB username
'pass'=>'987654', // DB password
),
);
// database connections
$mysql=array();
foreach($config as $con)
{
$con=(object)$con;
$start= new PDO($con->type.':host='.$con->host.';dbname='.$con->dbname.'', $con->user, $con->pass, array(
// pdo setup
PDO::ATTR_PERSISTENT => FALSE,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'
));
if ($start && !empty($start) && !is_resource($start))
$mysql[]=$start; // connection is OK prepare objects
else
$mysql[]=false; // connection is NOT OK, return false
}
/**********************
**** HOW TO USE ****
**********************/
// fetch data from database 1
$data1 = $mysql[0]->query("SELECT id, title, text FROM content1")->fetchAll();
if(count($data1)>0)
{
foreach($data1 as $i=>$result)
{
echo $result->id.' '.$result->title.' '.$result->text.'<br>'
}
}
// fetch data from database 2
$data2 = $mysql[1]->query("SELECT id, title, text FROM content2")->fetchAll();
if(count($data2)>0)
{
foreach($data2 as $i=>$result)
{
echo $result->id.' '.$result->title.' '.$result->text.'<br>'
}
}
If you not use PDO before, please read this short tutorial:
http://www.mysqltutorial.org/php-querying-data-from-mysql-table/
Is practicly same like mysql and mysqli connections but is more advanced, fast and secure.
Read this documentations:
http://php.net/manual/en/book.pdo.php
And you can add more then 2 databases
Use PDO supported by php 5 version instead mysql connect
Here is a simple class that selects the required database automatically when needed.
class Database
{
private $host = 'host';
private $user = 'root';
private $pass = 'pass';
private $dbname = '';
private $mysqli = null;
function __construct()
{
// dbname is not defined in constructor
$this->mysqli = new mysqli( $this->host, $this->user, $this->pass );
}
function __get( $dbname )
{
// if dbname is different, and select_db() is succesfull, save current dbname
if ( $this->dbname !== $dbname && $this->mysqli->select_db( $dbname ) ) {
$this->dbname = $dbname;
}
// return connection
return $this->mysqli;
}
}
// examples
$db = new Database();
$result = $db->db1->query( "SELECT DATABASE()" );
print_r( $result->fetch_row() );
$result = $db->db2->query( "SELECT DATABASE()" );
print_r( $result->fetch_row() );
$result = $db->{'dbname with spaces'}->query( "SELECT DATABASE()" );
print_r( $result->fetch_row() );
$con1 = mysql_connect($hostname, $username, $password);
$con2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $con1);
mysql_select_db('database2', $con2);
Then to query database 1 pass the first link identifier:
mysql_query('select * from tablename', $con1);
and for database 2 pass the second:
mysql_query('select * from tablename', $con2);
if mysql's user have permission to two database , you can join two table from two database
etc:
SELECT database1.table.title title1,database2.table.title title2
FROM database1.table
INNER JOIN database2.table
ON (database1.table.id=database2.table.id)
I have this simple code:
<?php
//Open the mySQL connection
$conn_string = "'localhost', 'Vale', 'test'";
$dbh = mysql_connect($conn_string);
//Check that a connection with the DB has been established
if (!$dbh)
{
die("Error in MySQL connection: " . mysql_error());
}
...
And I get the error: Error in MySQL connection: php_network_getaddresses: getaddrinfo failed: The requested name is valid, but no data of the requested type was found.
I cannot figure out what the problem is, I have been google-ing but all the suggestions have failed (tried 127.0.0.1 instead of localhost, 127.0.0.1:3306, etc.)
I have code that works with postgre, but I need to use mysql, and I am trying to modify it, but I cannot pass the first line and get a connection. Any suggestion, please? Thank you!
mysql_connect doesn't take a comma seperated string. It takes 3 individual strings.
Change it to this:
$dbh = mysql_connect($server, $mysql_user, $password);
If you absolutely have a comma separated string, and can't get around this, you can split the string like this:
$config = str_replace("'", '', $conn_string); // replace the quotes.
$config = preg_split('/,/', $conn_string); // split string on ,
if($config != $conn_string) { // make sure this returned an array
count($config) === 3 OR die("Invalid database configuration string");
$dbh = mysql_connect($config[0], $config[1], $config[2]);
if(FALSE === $dbh) {
die("Coult not connect: " . mysql_error());
}
}
You might want to consider MySQLi, instead of MySQL.
<?php
$dbh=mysqli_connect("localhost","Vale","Password","test"); /* Vale is your username? And the name of your database if test, right? And your Username's Password is blank? */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
?>
As other users have pointed out mysql_connect expects the database, username, and password as separate arguments rather than a single string.
I think another highly important issue to point out is that this particular extension is deprecated.
Please see: http://uk1.php.net/function.mysql-connect
A better solution would be to use mysqli_connect: http://uk1.php.net/manual/en/function.mysqli-connect.php
$db = mysqli_connect( 'localhost', 'Vale', 'test', 'yourDatabaseName' );
mysql_connect requires three argument not single string
$dbh = mysql_connect('localhost', 'Vale', 'test');
So I have a PHP page that connects first to my database and does a bunch of stuff using the information from there. Now I want to connect to another database within the same PHP page and access data from there and insert the information into my original database.
The code:
<?php
session_start();
include ("account.php");
include ("connect.php");
....
do stuff here
....
include ("account2.php");
include ("connect2.php");
...
$thing = "SELECT abc, efg, hij FROM table ORDER BY RAND() LIMIT 1" ;
$thing = mysql_query($thing);
echo "$thing";
....
....
insert information into my database
(From account.php & connect.php files)
....
?>
Everything shows up except for $thing. It says, "Invalid query: Query was empty" but I know the query I used works because when I ran it in the account2 database, I got the results I wanted. Is there something wrong with my logic or is it something else?
You are not mentioning database connection link while executing the query. May be your second database connection is defined after the 1st one in connection.php file. So interpreter is considering 2nd connection while executing the query.
Define the connection link with query,
$thing = mysql_query($thing,$conn); //$conn is your mysql_connect
You can still use the mysql_connect or similar mysql_ functions (procedural way) But all these are now deprecated. You should use mysqli_ (mysql improved) functions or go with the object oriented way.
$conn1 = new mysqli(SERVER1,DB_USER1,DB_PASS1,DB1);
$conn2 = new mysqli(SERVER2,DB_USER2,DB_PASS2,DB2);
if($conn1 ->connect_errno > 0 || $conn2 ->connect_errno > 0){
die('Unable to connect to database server.');
}
Now while executing your query,
$query = "SELECT abc, efg, hij FROM table ORDER BY RAND() LIMIT 1";
$thing = $conn1 -> query($query); //if it's second connection query user $conn2
Many web applications benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.
For your case, i would make 2 persistent connections, store each in it's own variable and then use one whenever i need to. Check it out using the PDO class.
//Connection 1
$dbh1 = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
.
.
.
//Connection 2
$dbh2 = new PDO('mysql:host=localhost;dbname=test2', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
After you finish you first database operation, then you can close the connection using
mysql_close($c) //$c = connection
And again start for next database operation.
private static function _connectDB1()
{
//give hostname, dbusername, dbpassword
$con1 = mysql_connect("localhost", "root", "rootpass");
$db1 = mysql_select_db("dbone", $con1);
}
private static function _connectDB2()
{
//if you are using different db with different credentials
//you can give here like this
// mysql_connect("mynewhost", "mynewusername", "mynewpassword")
$con2 = mysql_connect("localhost", "root", "rootpass");
$db2 = mysql_select_db("dbtwo", $con2);
}
Got a problem! Though I found almost similar threads but none helped :(
I've written a php script to fetch the number of registered users from my MySQL database. The script is working great in my localhost; it is using the given username,pass and host name which are "root", "root", and "localhost" respectively, but the script is not using the given username/pass/host rather using root#localhost (password: NO) in Live server.
In the Live server I created a MySQL user, set an different password, and hostname there is of course not localhost. I updated the script with my newly created mysql users data. BUT, whenever I run the script, I see that the script is still using "root", "root", and "localhost"!!
take a look at the script:
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
$db = mysql_select_db ("regdb",$conn); //Oops, actually it was written this way in the script. I misstyped it previously. now edited as it is in the script.
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ");
while ($row = mysql_fetch_array($query)):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
-- Some says to change the default username and pass in the config.ini.php file located in phpMyAdmin directory. Would this help?? I didn't try this because either my hosting provider didn't give me privilege to access that directory (because I am using free hosting for testing scripts) or I simply didn't find it :(
Please help....
Foreword: The MySQL extension is marked as deprecated, better use mysqli or PDO
Though you store the connection resource in $conn you're not using it in your call to mysql_query() and you're not checking the return value of mysql_connect(), i.e. if the connection fails for some reason mysql_query() "is free" to establish a new default connection.
<?php
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
if ( !$conn ) {
die(mysql_error()); // or a more sophisticated error handling....
}
$db = mysql_select_db ("regdb", $conn);
if ( !$db ) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
while ( false!=($row=mysql_fetch_array($query)) ):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
edit: It looks like you're processing only one row.
Either move the echo line into the while-loop or (if you really only want one record) better say so in the sql statement and get rid of the loop, e.g.
// Query to fetch data
// make it "easier" for the MySQL server by limiting the result set to one record
$query = mysql_query("SELECT * FROM regd LIMIT 1", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
// fetch data and output
$row=mysql_fetch_array($query);
if ( !$row ) {
echo 'no record found';
}
else {
echo htmlspecialchars($row['total_regd']);
}
First of all:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
What is your mysql_error()? :)