I am Developing the simple application,the application related to database operations.
My doubt is how can i connect to multiple databases same time.
how can php knows which databases the data will store.
If the user enter the data which database it will enter,both databases or one database.
Please answer my question.i have struggling a lot for this question.
If you use PHP5 (And you should, given that PHP4 has been deprecated), you should use PDO, since this is slowly becoming the new standard. One (very) important benefit of PDO, is that it supports bound parameters, which makes for much more secure code.
You would connect through PDO, like this:
try {
$db = new PDO('mysql:dbname=databasename;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
(Of course replace databasename, username and password above)
You can then query the database like this:
$result = $db->query("select * from tablename");
foreach ($result as $row) {
echo $row['foo'] . "\n";
}
Or, if you have variables:
$stmt = $db->prepare("select * from tablename where id = :id");
$stmt->execute(array(':id' => 42));
$row = $stmt->fetch();
If you need multiple connections open at once, you can simply create multiple instances of PDO:
try {
$db1 = new PDO('mysql:dbname=databas1;host=127.0.0.1', 'username', 'password');
$db2 = new PDO('mysql:dbname=databas2;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
Yes you can.. by using two connection strings..
$mysqli1 = new mysqli('HOST1', 'USER1', 'PASSWORD1', 'DB_NAME1');
$mysqli2 = new mysqli('HOST2', 'USER2', 'PASSWORD2', 'DB_NAME2');
and your queries should be like
$result1 = $mysqli1->query('query ......');
and
$result2 = $mysqli2->query('query ......');
Of course you can given example below add more connections if you want:
Class database
{
private oracleDatabase;
private mysqlDatabase;
public function connOracle() {
$db = "";
$user = "";
$password = "";
try {
$this->oracleDatabase = new PDO("oci:dbname=".$db,$user,$password);
} catch(PDOException $e){
echo "Can't connect to database (Oracle). ". $e->getMessage();
}
}
public function connMysql() {
$db = "";
$user = "";
$password = "";
try {
$this->mysqlDatabase = new PDO("mysql:dbname=".$db,$user,$password);
} catch(PDOException $e){
echo "Can't connect to database (Mysql). ". $e->getMessage();
}
}
}
Be carefull if you are using two databases on the same server at the same time. By default mysql_connect returns the same connection ID for multiple calls with the same server parameters, which means if you do
<?php
$db1 = mysql_connect(...stuff...);
$db2 = mysql_connect(...stuff...);
mysql_select_db('db1', $db1);
mysql_select_db('db2', $db2);
?>
then $db1 will actually have selected the database 'db2', because the second call to mysql_connect just returned the already opened connection ID !
You have two options here, eiher you have to call mysql_select_db before each query you do, or if you're using php4.2+ there is a parameter to mysql_connect to force the creation of a new link.
Use this below link to refer.What you have asked here.
PHP Documentation
Yes, you may use multiple database in one application, but the main thing is when you are communicating with the dbname, you have to specify that dbname also so than script will communicate with only that db in which you had defined. Ex.
$db1 = mysql_connect(...stuff...);
$db2 = mysql_connect(...stuff...);
mysql_select_db('db1', $db1);
mysql_select_db('db2', $db2);
$resultsa = mysql_query('SELECT * FROM table_a', $dbname) or die('Could not query database_a');
Yes you can connect multiple databases.
open your php.ini file and give me your database details like
port number,username,password.
And after that you can give the queries like this in your applications
$db1 = mysql_connect($hostname, $username, $password);
$db2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $db1);
mysql_select_db('database2', $db2);
Then to query database 1, do this:
mysql_query('select * from tablename', $dbh1);
and for database 2:
mysql_query('select * from tablename', $dbh2);
i think this is work fine for your question.
Yes you can, in very basic terms, you do it like this:
http://au1.php.net/function.mysql-connect
$conn = mysql_open($host, $username, $password, true);
To connect to multiple databases on the same server:
$dblink1 = mysql_select_db('database_a', $conn);
$dblink2 = mysql_select_db('database_b', $conn);
To get results from two databases:
$resultsa = mysql_query('SELECT * FROM table_a', $dblink1) or die('Could not query database_a');
$resultsb = mysql_query('SELECT * FROM table_b', $dblink2) or die('Could not query database_b');
edit - keep in mind that the mysql_ functions aren't available in recent PHP releases because they've been removed.
Warning
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.
See also MySQL: choosing an API guide and related FAQ for more
information.
Related
I am trying to connect to an existing SQL Server database using PDO with the drivers provided by Microsoft.
I have seen examples using odbc, dblib, mssql, etc., however I believe the connection string with these drivers should use 'sqlsrv'?
Are there any good examples of how to properly do this? If I should be doing this via some other method please let me know. Thanks!
Well that's the best part about PDOs is that it's pretty easy to access any database. Provided you have installed those drivers, you should be able to just do:
$db = new PDO("sqlsrv:Server=YouAddress;Database=YourDatabase", "Username", "Password");
Mind you that in my experience and also of other (PHP - Why is new SQLSRV driver slower than the old mssql driver?) that using PDO_SQLSRV is way slower than through PDO_ODBC.
If you want to use the faster PDO_ODBC you can use:
//use any of these or check exact MSSQL ODBC drivername in "ODBC Data Source Administrator"
$mssqldriver = '{SQL Server}';
$mssqldriver = '{SQL Server Native Client 11.0}';
$mssqldriver = '{ODBC Driver 11 for SQL Server}';
$hostname='127.0.0.1';
$dbname='test';
$username='user';
$password='pw';
$dbDB = new PDO("odbc:Driver=$mssqldriver;Server=$hostname;Database=$dbname", $username, $password);
This works for me, and in this case was a remote connection:
Note: The port was IMPORTANT for me
$dsn = "sqlsrv:Server=server.dyndns.biz,1433;Database=DBNAME";
$conn = new PDO($dsn, "root", "P4sw0rd");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM Table";
foreach ($conn->query($sql) as $row) {
print_r($row);
}
Figured this out. Pretty simple:
new PDO("sqlsrv:server=[sqlservername];Database=[sqlserverdbname]", "[username]", "[password]");
try
{
$conn = new PDO("sqlsrv:Server=$server_name;Database=$db_name;ConnectionPooling=0", "", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
$e->getMessage();
}
$servername = "";
$username = "";
$password = "";
$database = "";
$port = "1433";
try {
$conn = new PDO("sqlsrv:server=$servername,$port;Database=$database;ConnectionPooling=0", $username, $password,
array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
} catch (PDOException $e) {
echo ("Error connecting to SQL Server: " . $e->getMessage());
}
I am trying to connect to an existing SQL Server database using PDO with the drivers provided by Microsoft.
I have seen examples using odbc, dblib, mssql, etc., however I believe the connection string with these drivers should use 'sqlsrv'?
Are there any good examples of how to properly do this? If I should be doing this via some other method please let me know. Thanks!
Well that's the best part about PDOs is that it's pretty easy to access any database. Provided you have installed those drivers, you should be able to just do:
$db = new PDO("sqlsrv:Server=YouAddress;Database=YourDatabase", "Username", "Password");
Mind you that in my experience and also of other (PHP - Why is new SQLSRV driver slower than the old mssql driver?) that using PDO_SQLSRV is way slower than through PDO_ODBC.
If you want to use the faster PDO_ODBC you can use:
//use any of these or check exact MSSQL ODBC drivername in "ODBC Data Source Administrator"
$mssqldriver = '{SQL Server}';
$mssqldriver = '{SQL Server Native Client 11.0}';
$mssqldriver = '{ODBC Driver 11 for SQL Server}';
$hostname='127.0.0.1';
$dbname='test';
$username='user';
$password='pw';
$dbDB = new PDO("odbc:Driver=$mssqldriver;Server=$hostname;Database=$dbname", $username, $password);
This works for me, and in this case was a remote connection:
Note: The port was IMPORTANT for me
$dsn = "sqlsrv:Server=server.dyndns.biz,1433;Database=DBNAME";
$conn = new PDO($dsn, "root", "P4sw0rd");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM Table";
foreach ($conn->query($sql) as $row) {
print_r($row);
}
Figured this out. Pretty simple:
new PDO("sqlsrv:server=[sqlservername];Database=[sqlserverdbname]", "[username]", "[password]");
try
{
$conn = new PDO("sqlsrv:Server=$server_name;Database=$db_name;ConnectionPooling=0", "", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
$e->getMessage();
}
$servername = "";
$username = "";
$password = "";
$database = "";
$port = "1433";
try {
$conn = new PDO("sqlsrv:server=$servername,$port;Database=$database;ConnectionPooling=0", $username, $password,
array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
} catch (PDOException $e) {
echo ("Error connecting to SQL Server: " . $e->getMessage());
}
I'm coding a web service for iOS in Php. I'm trying to retrieve data from server through php but the response is null.The server is MSSql Server 2014.
<?php
define ('DB_HOST', '****.net');
define ('DB_USER', '****');
define ('DB_PASS', '******');
define ('DB_NAME', '*******');
$dbc = mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_NAME, $dbc);
if (mysql_select_db){
echo "Done";
}else{
echo "Die";
}
$sql_select = "SELECT * from ClientChk";
$records = mysql_query($sql_select);
$count= 1;
while($result = mysql_fetch_array($records))
{
if ($result == nil){
echo "Nil!";
}
}
echo json_encode($result['Id']);
?>
This is a bad example of doing this.
1) You have to check if the connection was successful.
2) If use MSSQL, then you can't use mysql_ commands.
3) nill doesn't exist in php, should be 'null'
$SERVER = '127.0.0.1';
$DB = 'test';
$USER = 'username';
$PASSWORD = 'password';
$db = new PDO("sqlsrv:server=$SERVER;database=$DB;", $USER, $PASSWORD);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$query = "SELECT * FROM ClientChk";
$result = $db->query($query)->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $ex) {
$ex->getMessage();
echo $ex;
}
echo json_encode($result);
So, the problem is, that you try to connect to a MSSQL database, with a MySQL database connector.
To connect to a MSSQL database, you can use the following methods:
mssql_connect(): It uses a quite similar syntax to mysql, but it is removed as of php 7.0, so I advice against it's usage even if you using an earlier version of php.
PDO class: It's differs a lot from the older function style sql connectors, but it is the preferred way by many.
sqlsvr_connect(), obdc_connect(): If you prefer a function based connector instead of the PDO class, and you don't want to use the deprecated mssql_connect, I recommend choosing one of these.
I hope, I could be of any help.
The script below is used for updating schema of 100 databases.
I am making one call to mysql_connect, does mysql_select_db cause another connection to be made or am I ok? (I run this script to update the schema of 100 or so database)
$conn = mysql_connect("localhost", "root", "PASSWORD");
$show_db_query = mysql_query('SHOW databases');
$databases = array();
while ($row = mysql_fetch_assoc($show_db_query))
{
if (!in_array($row['Database'], $exclude_dbs))
{
$databases[] = $row['Database'];
}
}
foreach($databases as $database)
{
mysql_select_db($database, $conn);
echo "Running queries on $database\n***********************************\n";
foreach($sql_queries as $query)
{
if (!empty($query))
{
echo "$query;";
if (!mysql_query($query))
{
echo "\n\nERROR: ".mysql_error()."\n\n";
}
}
}
echo "\n\n";
}
As long as mysql_select_db found a last connection or a connection identifer is supplied with the calling statment, it does not create a new connection.
Since you are passing a connection identifer so it does not create a new connection to mysql. you are safe to go in this case of multiple connection but be aware that mysql extension is no longer maintained, you could try mysqli or PDO.
Hi I have been learning php from this book PHP Solutions Dynamic Web Design Made Easy and gotten to the part where I have to work with mysqli api for databases.After writing a connection function and running the script I get this error:
This is my code:
function dbConnect($usertype , $connectionType = 'mysqli'){
$host = 'localhost';
$db = 'phpsols';
if($usertype == 'read'){
$user = 'psread';
$pwd = 'Aleczandru1989';
}elseif($usertype == 'write'){
$user = 'aleczandru';
$pwd = 'Aleczandru1989';
}else{
exit('Unrecognized type');
}
if($connectionType == 'mysqli'){
return new mysqli($host , $user , $pwd , $db) or die ('Cannot open database');
}else{
try{
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
} catch (PDOException $e){
echo 'Cannot connect to database';
exit;
}
}
}
$conn = dbConnect('read');
$sql = 'SELECT * FROM images';
$result = $conn->query($sql) or die(mysqli_error()); //Line 5
$numRows = $result->num_rows;
Line 5 in this case refers to $result = $conn->query($sql) or die(mysqli_error());.
What Am I doing wrong here?
The $conn object you are attempting to create with dbConnect('read'); fails. If you would do a var_dump($conn); it probably shows it is not what you aspect it to be. The error is actually describing what is wrong. You try to access the query function with '->query(..' on $conn. But $conn has to be an object reference that actually has the query function. The points where this object will be created are:
return new mysqli($host , $user , $pwd , $db)
and
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
Since you are showing a different error then
or die ('Cannot open database');
My guess it is actually gong wrong at
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
And you will catch the exception. But the echo statement is not visible anymore due to the fatal error. You will have to do some debugging there!
I have no experience with PDO, but construction of the object seems ok. (but can this help you out: http://nl1.php.net/manual/en/class.pdo.php#84751) If the construction is ok, than check if your database engine is actually running :) ?