alternate between mysql connections - php

I've been trying to figure this out for a few days now. I have 4 databases that I need to connect to. I am trying to alternate between the connections but it wont let me. It always takes the last connection.
$link = mysql_connect("localhost","root","");
mysql_select_db("front",$link);
$link2 = mysql_connect("mysite.com","user","2012");
mysql_select_db("db1",$link2);
$link3 = mysql_connect("mysite.com","user","2012");
mysql_select_db("appsdb",$link3);
$link4 = mysql_connect("mysite.com","user","2012", TRUE);
mysql_select_db("storagedb",$link4);
what do I need to do?
This works but takes too long
$link = mysql_connect("localhost","root","");
mysql_select_db("front",$link);
$link2 = mysql_connect("mysite.com","user","2012",true);
mysql_select_db("db1",$link2);
$link3 = mysql_connect("mysite.com","user","2012",true);
mysql_select_db("appsdb",$link3);
$link4 = mysql_connect("mysite.com","user","2012", true);
mysql_select_db("storagedb",$link4);
Is it possible to separate the connections altogether but still use $link, $link2, $link3, $link4 inside the queries? I dont think its efficient to keep all connections open.

I won't comment on using mysqli like others did, I guess from all these comments, you are already aware that you should switch, so I will just reply with the answer and maybe it can help other people who just can't upgrade php for some reason.
The function mysql_connect creates OR reuse a connection, so if you create multiple connections to the same server with the same credentials, you will get just a single connection.
If you NEED to force mysql_connect to create a new connection, you need to specify the new_link parameter as true as follow:
$link = mysql_connect("localhost","root","",true);
mysql_select_db("front",$link);
$link2 = mysql_connect("mysite.com","user","2012",true);
mysql_select_db("db1",$link2);
$link3 = mysql_connect("mysite.com","user","2012",true);
mysql_select_db("appsdb",$link3);
$link4 = mysql_connect("mysite.com","user","2012", true);
mysql_select_db("storagedb",$link4);
You can find more information here: http://php.net/manual/es/function.mysql-connect.php

Questions like these are rampant in this site, I suppose your search for one like this for more help.
$db_conn = connect_db(host, user, pwd);
mysql_select_db('existing_db', $db_conn);
-- do selects and scrub data --
mysql_select_db('new_db', $db_conn);
-- insert the required data --
Full link Here

just add the ",$link" to the end of your query statement...
mysql_query("SELECT * FROM table", $link);

why not using persistent connections mysql_pconnect, but consider to switch to pdo or mysqlnd
(counterparts of persistent connections 1 2)

Related

PHP MySQL Get Connection From Require() File

I usually am immersed in the Microsoft Stack but dabble in PHP from time to time. A long standing question I've had with PHP that I've never seem to be able to find the answer to is how do you apply your already declared require("dbConnect.php") database connection to your mysql_query()? For clarification please see my code example below:
require("dbConnect.php");
$db_host = 'localhost';
$db_user = 'UserName';
$db_pwd = 'Password';
$database = 'DbName';
$table = 'tblQuote';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// sending query
$result = mysql_query("SELECT QuoteID, FirstName, LastName, PhoneNumber, Email, QuoteDate FROM tblQuote ORDER BY QuoteDate DESC");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
So in looking at this you can see the standard require() declaration at the top... which already holds my connection info. But every single MySQL Query example I've ever found always creates it's own connection... which I get for demonstration purposes... but I've never been able to figure out how I can use my already existing connection thereby bypassing rewriting the exact same connection info over and over again when it comes to writing queries. I know for you PHP developers this question is like 101 but I've not been able to find an answer to this seemingly basic question... admittedly I may be asking the question wrong so any help would be appreciated!
From the PHP documentation: http://php.net/manual/en/function.mysql-query.php
mixed mysql_query ( string $query [, resource $link_identifier = NULL ] )
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments.
So since you've already created one in your dbConnect.php, the one you just made will be used (It won't create a new one for every query). To pass it explicitly into your mysql_query function call, you can return the MySQL resource that was returned from your mysql_connect call like so:
dbConnect.php
return mysql_connect(....);
Then in the code you pasted above:
$mysql_conn = require('dbConnect.php');
...
$result = mysql_query('...', $mysql_conn);
Then you will explicitly have the connection and pass it to your query - there will be no mistaking it, regardless of how large your codebase becomes. When you require the file, you'll have access to the connection variable, but in the above example, how you get the connection is more semantically clear.
Also, notice that this function has been deprecated in PHP>=5.5, so you'll want to use PDOs or MySQLi which have future support.
Hope this helps!

PHP: could not find database

i am having difficulty with connecting my database to mysql, i have tried many different ways of trying to get it to connect to my database, but none these methods seem to work. I am only new to php and i could be missing something, but i dont know what it is.
This is for a search engine, i have the form created.
I would think that my problem is coming from this line of code, mysql_connect("localhost", "root", "") or die("could not connect");?!
I was wondering if i could be told what is the problem and how to fix it, thank you so much.
here is my code below.
<?php
//connect
mysql_connect("localhost", "root", "") or die("could not connect");
mysql_select_db("search") or die("could not find database");
$output = '';
if (isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","", $searchq);
$query = mysql_query("SELECT * FROM gp management system WHERE Title LIKE '%$searchq%' OR Description LIKE '%$searchq%' OR Keyword LIKE '%$searchq%'") or die("could not search");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'There was no search results!';
}
else{
while($row = mysql_fetch_array($query)) {
$Title = $row['Title'];
$Description = $row['Description'];
$Keyword = $row['Keyword'];
$output .= '<div> ' .$Keyword. ' </div> ';
}
}
}
?>
SQL errors:
SELECT * FROM gp management system WHERE Title...
^^-- table name
^^^^^^^^^^ aliasing 'gp' as 'management'
^^^^^^-- extra unknown garbage
Table names shouldn't have spaces to begin with, but if you insist on having them, then you need proper quoting:
SELECT * FROM `gp management system` etc...
^--------------------^
Never output a fixed/useless "could not search" error. Have the DB tell you what went wrong:
$result = mysql_query($sql) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^^
As your only new, you really should stop using mysql_ and change to mysqli_ or (my preference) PDO(). Your message in your title seems to be coming from your selectdb line, so you're actually connecting to the database fine, it's just not able to locate the schema that you are trying to use (i.e. "search" does not exist as a schema name in your DB environment). Unless that's not the error that you are getting, in which case it's a flaw in your actual SQL query. Without an accurate statement of what you are getting back on the screen when you try to run the script then not much can be done to help.
I would rather do somehow like I did ages ago, see below:
function db_connect($host, $username, $passwd, $db_name) {
$db = mysql_connect($host, $username, $passwd);
if (!$db) {
echo "Login to database failed: ";
echo mysql_error();
return false;
}
$result=mysql_select_db($db_name); //Select the database
if (!$result) {
echo "Cannot find the database: ".$db_name;
echo mysql_error();
return false;
}
return $db; //Database descriptor
}
However you shouldnt rely on the old MYSQL extension, but use MYSQLi.
EDIT: as #tadman pointed out there were a # sign infront the mysql_connect call, however there is an if statement for checking and a call to error output.
As others have said, your code is something of a mess - you seem to be new to programming, not just in PHP. But everyone has to start somewhere, so....
You might want to start by learning a bit about how to ask questions - specifically you have included a lot of code which is not relevant to the problem you are asking about - which is about connecting to MySQL. OTOH you have omitted lots of important information like the operating system this is running on and what diagnostics you have attempted. See here for a better (though far from exemplary example).
Do read your question carefully - the title implies an issue with mysql_select_db() while in the body of the content you say you think the problerm is with mysql_connect(). If you had provided the actual output of the script we would have been able to tell for ourselves.
You should be checking that MySQL is actually running - how you do that depends on your OS. You should try connecting using a different client (the mysql command line client, sqldeveloper, Tora, PHPMyAdmin....there are lots to choose from).
You should also check (again this is operating system specific) that your MySQL instance is running on the same port as is configured in your php.ini (or overridden in your mysql_connect() call).
MySQL treats 'localhost' as something different from 127.0.0.1 on Unix/Linux systems. If this applies to you try 127.0.0.1 in place of localhost.
or die("could not connect");
Does not help in diagnosing the problem. If instead you...
or die(mysql_error());
You will get a more meaningful response.
BTW: while writing code using the mysql extension rather than mysqli or PDO is forgivable, I am somewhat alarmed to see what appears to be medical information managed with no real security.

Connecting to a mysql database without keeping details in the script

I am attempting to create a separate login file for database connections as I am not too fond of having all the access details on each page that requires database access.
I have created a separate file on my server that contains the variables required for a successful login and then use the;
include_once('path_to_file/filename.php');
to get the variables and then use;
$dbconnection = mysqli_connect("$hostname","$username","$password","$database") or die ("Could not connect to the server");
but the connection fails every time. I tried including the connection script in the file I am attempting to include but then I get this message:
Can't connect to local MySQL server through socket '/tmp/mysqld.sock' (2)
I'm not really sure how to fix this, but every page in my server more or less access the database and I think it has to be a security risk having login details replicated everywhere!
Anyone have any suggestions or alternatives?
databaseloging format is:
<?php
# parameters for connection to MySQL database
$hostname="hostname";
$database="databasename";
$username="username";
$password="password";
?>
P.S. I have also tried require and got the same result.
Also when using multiple MySQL connections in PHP, you have to supply a fourth argument telling PHP to actually create new connections like this (this is very important, if you are using two connections to the same host):
$db1 = mysql_connect($host1, $user1, $passwd1, true);
$db2 = mysql_connect($host2, $user2, $passwd2, true);
If the fourth argument is not used, and the parameters are the same, then PHP will return the same link and no new connection will be made.
After this you should use "mysql_query" with an extra parameter than defines which connection to use:
$res1 = mysql_query($sql1, $db1) or die(mysql_error($res1));
$res2 = mysql_query($sql2, $db2) or die(mysql_error($res2));
http://www.php.net/manual/en/function.mysql-connect.php

Having Problems With PHP Connection

This is the code that connects to my SQL database. I'm new with this stuff and it seems to be semi-working but certain features on my website still don't work.
<?php
$con = mysql_connect("localhost","username","password");
$select_db = mysql_select_db('database1',$con);
/*$con = mysql_connect("localhost","username2","password2");
$select_db = mysql_select_db('database2',$con);*/
?>
This is the site in question: http://tmatube.com keep in mind the credentials above are filled in with what the programmer used for testing on his own server... ;) unfortunately I don't have access to him for support anymore.
Anyway, here's my thoughts on how this code needs to be edited maybe someone can chime in and let me know if I'm correct in my assumptions:
<?php
$con = mysql_connect("localhost","username1","password1"); -------------<<< leave this line
$select_db = mysql_select_db('DATABASE_NAME_HERE',$con);
/*$con = mysql_connect("localhost","DB_USERNAME_HERE","DB_PASSWORD_HERE");
$select_db = mysql_select_db('DATABASE_NAME_HERE',$con);*/
?>
Ok - now on to a few problems I noticed...
What does this do? /* code here */? It doesn't work at all if I leave that bit in.
Why is it connecting to database twice? and is it two separate databases?
$select_db = mysql_select_db('DATABASE_NAME_HERE',$con); <<<---- single '
When I tried to see if that line was correct the examples I saw had quotes like this
$select_db = mysql_select_db("DATABASE_NAME_HERE",$con); <<<---- double "
Which one is right?
He didn't leave it out. What he did was leave the database to be connected using the root, which has no password. The other connection (which is commented out) is using another user, rajvivya_video, with a password defined.
In testing it MIGHT be okay to connect to root and leave it without password, but even that is not recommended, since its so easy to work with a user and password defined (besides root).
Here is php mysql connect with mysqli:
<?php
$link = mysqli_connect("myhost","myuser","mypassw","mybd");
?>
No difference here with ' or ". (Anyway use mysqli and you can the wanted db as 4th parameter.) php quotes
/* comment */ is a commented out so the php does not care what is inside so only 2 first rows of are affecting (they are same mysql database on the local machine and 2 different user + password combinations). Comment in general are used to explain the code or removing part of the code with out erasing it. php commenting

How can I re-use an existing database connection in phpBB3?

I am using my own db for phpbb3 forum, and I wish to insert some data from the forum into my own tables. Now, I can make my own connection and it runs my query but in trying to use the $db variable(which I think is what you're meant to use??) it gives me an error.
I would like someone to show me the bare bones which i insert my query into to be able to run it.
Well.. You haven't given us very much information, but there are two things you need to do to connect and query to a database.
For phpbb, you may want to read the documentation they have presented:
http://wiki.phpbb.com/Database_Abstraction_Layer
Here is a general overview of how you'd execute a query:
include($phpbb_root_path . 'includes/db/mysql.' . $phpEx);
$db = new dbal_mysql();
// we're using bertie and bertiezilla as our example user credentials. You need to fill in your own ;D
$db->sql_connect('localhost', 'bertie', 'bertiezilla', 'phpbb', '', false, false);
$sql = "INSERT INTO (rest of sql statement)";
$result = $db->sql_query($sql);
I presumed that phpBB already had a connection to my database. Thus I wasnt going to use a new one? Can i make a new one and call it something else and not get an error?
And $resultid = mysql_query($sql,$db345);
Where $db345 is the name of my database connection
$db = new dbal_mysql();
// we're using bertie and bertiezilla as our example user credentials. You need to fill in your own ;D
$db->sql_connect('localhost', 'bertie', 'bertiezilla', 'phpbb', '', false, false);
$sql = "INSERT INTO (rest of sql statement)";
$result = $db->sql_query($sql);

Categories