I'm new to PDO. I would like to know if there is anything similar to mysql_select_db in PDO, so that i can switch between different databases during runtime without the need for creating a new object.
I know that I am a couple of months late but you should be able to switch between databases from within your query.
examples:
$sql = "SELECT * FROM dbname.tablename";
$sql = "SELECT * FROM anotherdbname.anothertablename"
So even if your original $pdo object was used 'blahblah' as the dbname, you should still be okay based on the select examples I provided.
It looks like PDO does not have database switching because not every database engine supports it.
AFAIK PostgreSQL does not have database switching, but offer schemas and u can switch between those.
However if you're using mysql check if this works for you:
$pdo = new PDO('mysql:dbname=db1;host=127.0.0.1','user','pass');
$sql = 'select count(*) from table_name';
$res = $pdo->query($sql);
print_r($res->fetchAll());
$pdo->exec('USE db2');
$res = $pdo->query($sql);
print_r($res->fetchAll());
You actually do not need to specify the database upon connection at all. As long as you specify the database in every query, as Laz stated, this will work:
$dbh = new PDO('mysql:host=127.0.0.1','USER','PASS');
$query = "SELECT * FROM database1.table1";
$query = "SELECT * FROM database2.table1";
There is not, you will need to create two PDO objects for the separate connections if you would like to use both at runtime.
Edit: Interesting point by #laz below (which I'm guessing is the cause of negative votes on my answer). I was thinking under the assumption that the databases were on separate servers tbh, in which case my answer stands.
you don't even need to specify the database in every query, just use msyql syntax
USE db_name
and then write your requests
you can make this :
$database1 = new PDO("mysql:host=localhost;dbname=db1;charset=utf8;",$username, $password);
$database2 = new PDO("mysql:host=localhost;dbname=db2;charset=utf8;",$username, $password);
simple 😀
Related
I have a legacy php project that I need to convert from mysql to mysqli.
The conversion seems quite straight forward except for one part.
In mysql the following code seems to work well:
$query = "select c.id from contact c";
$queryResult = mysql_query($query);
$result = mysql_result($queryResult,0,"c.id");
I am translating the code to:
$connection = new mysqli(...)
$queryResult = $connection->query($query);
$queryResult->data_seek(0);
$result_row = $queryResult->fetch_assoc();
$result = $result_row["c.id"];
However it seems that in mysqli "c.id" is not valid. I need to use "id".
I been looking at mysql to mysqli conversion posts but I haven't seen any solution to this particular issue. I know I can update the query to use something like
"select c.id as cid from contacts"
However there are hundreds of queries that I need to manually convert so I was wondering if there is any easy way of getting the "c.id" part to work with mysqli.
Thanks.
hi im starting to use PDO for sqlite and I want to know how to do something similar like:
$result = **sqlite_query**($conection,$consulta);
for example something similar to $conection = sqlite_open('../db/traductor.db');
would be--->$conection = new PDO('sqlite:../db/traductor.db');
hope you can understand my question, and thanks
As you've been pointed, the PHP PDO manual page will tell you where to look for, but I'll save you a couple of minutes.
In procedural MySQL, you would connect to your database with:
$link = mysql_connect("localhost", "user", "password");
mysql_select_db("database", $link);
And fire your queries like:
$query = mysql_query("SELECT * FROM `products` ORDER BY `product_id` ASC;", $link);
In PDO, it's a bit different:
$pdo = new PDO("mysql:host=localhost;dbname=database;charset=utf8", "user", "password");
And you fire your queries (in a direct fashion) like this:
$pdo->query("SELECT * FROM `products` ORDER BY `product_id` ASC;");
But the power of PDO lies within prepared statements
$statement = $pdo->prepare("SELECT * FROM `products` WHERE `price` > ? ORDER BY `product_id` ASC;");
$statement->execute([27.75]);
Take your time and read the PDO manual page and as many tutorials on the web as you can. It's more difficult to work with PDO in the beginning but, once you learn, you won't want to work with anything less (not to mention you can link with MySQL, SQL Server, Oracle, PostgreSQL, MongoDB and many other databases using the same structure, among other advantages).
Hope that helped ;)
i am trying to connect to two databases to create a search engine for a couple of my databases. Heres a test code. can someone tell me what i am doing wrong or if it is possible. thanks.
mysql_connect("localhost","user","pass");
mysql_select_db("db1");
mysql_select_db("db2");
$search=mysql_query("SELECT * from db1.repairs, db2.order from db1,db2");
while($row=mysql_fetch_array($search)){
echo $row['first_name']." ".$row['esn']." ".$row['order_type']."<br>";
}
You can query across databases if you specify the database name before the table name like this
SELECT a.col1, b.col2
FROM db1.table1 AS a
INNER JOIN db2.table2 AS b ON a.someIdFromA = b.someIdFromB
As Korcholis mentions the problem is in your select. Also you do not want to use the mysql_* functions if you can avoid it. PDO or MySqli are preferred.
Edit
At least this works using MySQL. I would bet it works for most other RDBMSes as well, but I don't have others handy to test and I can't say if this conforms to SQL standards or not. Comments anyone?
You can use
<?php
$db1 = mysql_connect("localhost","user","pass");
$db2 = mysql_connect("remote","user","pass");
mysql_select_db("db1", $db1);
mysql_select_db("db1", $db2);
$query1 = mysql_query("USE somedatabase", $db1);
$query2 = mysql_query("USE otherdatabase", $db2);
Or try with a class that handles these connections in a different instances
http://www.joni2back.com.ar/programacion/php-class-for-mysql-databases/
mysql_connect returns a $resource. You can connect twice and select a database with each one (in fact, you can select a database from the connect itself), and then use each connection.
However, your problem is that your SELECT is incorrect. You are trying to select fields from tables from databases, which is not correct. In fact, you cannot fetch two different databases in a so fancy way, because they are considered two sets of information independent and unrelated between them. That's why tables exist, to fit that problem.
This other answer, however, may have a solution.
Otherwise, you could connect to each database using two mysql_connect and two resources, fetch the values, and cross them yourself. Not the best option, I know, but an answer that could fit your needs.
PS: If you are beginning the project right now, switch to Mysqli or PDO. Mysql is deprecated.
Try to review this, and maybe you can't query a database with querying FROM:
<?php
$con1 = mysqli_connect("$hostname", "$user1", "$password1", "$db1");
if (mysqli_connect_errno($con1)) {
echo mysqli_connect_error();
}
$con2 = mysqli_connect("$hostname", "$user2", "$password2", "$db2");
if (mysqli_connect_errno($con2)) {
echo mysqli_connect_error();
}
$search1 = mysqli_query($con1, "SELECT * from $db1table");
$search2 = mysqli_query($con2, "SELECT * from $db2table");
/* Other PHP codes here */
mysqli_close($con1);
mysqli_close($con2);
?>
You can even improve this code, nor minimized it!
Are these 2 equivalent, if not how can I make them. I'm using php/Mysql (I'll use mysqli later)
mysql_select_db("db_App", $link);
$result = mysql_query("SELECT * FROM AppOne");
OR
$result = mysql_query("SELECT * FROM db_App.AppOne"); // how can I get this to work like above?
You'll always have to select a database. From then on, specifying the database in the query is useless. It's better not to specify it there anyway, as that'd make you run into troubles if your database changes at some point.
if you skip the $link in mysql_select_db("db_App", $link);
they should do the same.
Generally I connect and retrieve data using the standard way (error checking removed for simplicity):
$db = mysql_select_db("dbname", mysql_connect("host","username","passord"));
$items = mysql_query("SELECT * FROM $db");
while($item = mysql_fetch_array($items)) {
my_function($item[rowname]);
}
Where my_function does some useful things witht that particular row.
What is the equivalent code using objects?
Since version 5.1, PHP is shipped with the PDO driver, which gives a class for prepared statements.
$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password); //connect to the database
//each :keyword represents a parameter or value to be bound later
$query= $dbh->prepare('SELECT * FROM users WHERE id = :id AND password = :pass');
# Variables are set here.
$query->bindParam(':id', $id); // this is a pass by reference
$query->bindValue(':pass', $pass); // this is a pass by value
$query->execute(); // query is run
// to get all the data at once
$res = $query->fetchall();
print_r($res);
see PDO driver at php.net
Note that this way (with prepared statements) will automatically escape all that needs to be and is one of the safest ways to execute mysql queries, as long as you use binbParam or bindValue.
There is also the mysqli extension to do a similar task, but I personally find PDO to be cleaner.
What going this whole way around and using all these steps gives you is possibly a better solution than anything else when it comes to PHP.
You can then use $query->fetchobject to retrieve your data as an object.
You can use the mysql_fetch_object()
http://is2.php.net/manual/en/function.mysql-fetch-object.php