PHP - Selecting the currently used database - php

I am having a problem in getting the string name of the currently selected database.
this is what i did.. i am trying to echo the name of the database but it produces an error "Warning: mysql_fetch_array() expects parameter 1 to be resource"
<?php
$dbcon = mysql_connect("localhost", "root", "")
or die(mysql_error()."Not Connected");
$sql = mysql_query("select database()");
$row = mysql_fetch_array($sql);
echo "db ".$row[0];
?>
i need to get the selected database name because i will use it for
mysql_select_db()

You should either select a database right after connecting using your login credentials. Or, if you want to see what databases the root user has access to, use:
SHOW DATABASES;

select Database() shows the name of the name of the slected database.
It will work only after you have already selected the database using mysql_select_db().
If you want to get the name of the databases available to you then use SHOW DATABASES

You yourself need to select a database after connecting to MySQL, it's not selected by default, like this:
$dbcon = mysql_connect("localhost", "root", "")
or die(mysql_error()."Not Connected");
mysql_select_db("databasename"); # add this line
$sql = mysql_query("select database()");
$row = mysql_fetch_array($sql);
echo "db ".$row[0];
Please don't use mysql_* function as they're deprecated, instead use mysqli_*.

first, I would suggest you use mysqli functions instead of mysql as they are being deprecated.
Then, you just select the database by adding the database name in the parameter to mysql_select_db():
mysql_select_db('dbname');
note that another advantage of mysqli is you can specify the database in the connect string

Related

How to fetch a query with SHOW DATABASE LIKE statement?

I want to fetch some databases according to a specific name.
I have:
$sql="SHOW DATABASES LIKE `'%backup%'`";
$query=mysql_query($sql,$connect);
$row=mysql_fetch_assoc($query);
I need to fetch the databases in an array according to a specific name,but it gives me an error:
mysql_fetch_assoc() expects parameter 1 to be resource, boolean
Any idea how to do this?(And yes i know mysql is deprecated but i have to use it)
I have tested it
use:
SHOW DATABASES LIKE '%backup%'
here we go, its tested and working, but i will suggest you to use PDO, since mysql_* api is deprecated.
$sql="SHOW DATABASES LIKE '%backup%'";
$connect = mysql_connect("localhost", "root", "");
$query=mysql_query($sql,$connect) or die(mysql_error());
while($row = mysql_fetch_array($query)) {
echo $row[0]."<br/>";
}
Have you considered just listing all databases, then iterating through all results, matching them via regex/stripos and appending them into an array?
$sql="SHOW DATABASES";
$query=mysql_query($sql,$connect);
while ($row=mysql_fetch_assoc($query)) {
$var = preg_match("/backup/", $row['database'])
# Do whatever - append to array, echo, etc
}
EDITED
use mysql_select_db to select databases.see here http://php.net/manual/en/function.mysql-select-db.php
or you can use mysql_list_dbs but the problem is it will give all database. so using some loop you have to use your like operator to get what you want. see this:http://php.net/manual/en/function.mysql-list-dbs.php

Get data from all tables in database using php and mysql

I have a series of websites, all of which must share the same information. Any updates to text must be made across all websites. Instead of editing each site individually and uploading the updates files one at a time, I figured it'd be far better to have a central source using MySQL - update the database, and all websites will be changed at once.
I have limited knowledge of PHP and MySQL - everything below is what I've been able to put together for myself so far, using various online sources:
<?php
//DB INFO///////////////////////////////////////////////////////////////////////////////////////
$host="localhost"; // Host name
$username="####"; // Mysql username
$password="####"; // Mysql password
$db_name="####"; // Database name
// Connect to server and select database
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get all the data from the "example" table
$pge_logbookabout = "SELECT * FROM pge_logbookabout";
$pge_logbookabout = mysql_query($pge_logbookabout) or die(mysql_error());
$row_pge_logbookabout = mysql_fetch_assoc($pge_logbookabout);
?>
So far, I can use the above to select a table and echo in the HTML using:
<?php echo $row_pge_logbookabout['rep_lbapr'];?>
That's cool, but I'm only able to select one single table using this - I'd like to be able to select ALL tables, and simply enter variables in where I need them.
Will I need to repeat the third section of the above code for each table, or is there a simpler way for me to do this?
To display all records in a table, you need to do:
while($row_pge_logbookabout = mysql_fetch_assoc($pge_logbookabout)){
echo $row_page_logbookabout['COLUMN'];
}
However if you mean that you want to display all records in each table, therefore you need separate queries to do so.
$query = mysql_query("select * from table1");
while($row_table1 = mysql_fetch_assoc($query)){
// code here
}
$query = mysql_query("select * from table2");
while($row_table2 = mysql_fetch_assoc($query)){
// code here
}
Please note this way of connecting to database, quering and fetching data will be deprecated starting PHP 5.5.0. Alternatively you can use PDO prepared statements
If you want to process over a series of tables you can use something like:
$query_tables = mysql_query('SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_name LIKE "%table%" ');
while($table = mysql_fetch_assoc($query_tables)){
$query = mysql_query("select * from ".$table['table_name'] );
// code here
}
You will have to make sure you choose the proper table names in the first query so you are processing the proper tables.
Then you can use php to loop over the tables updating a particular column/field. Not sure if that is what you are looking for...
More information at http://dev.mysql.com/doc/refman/5.0/en/information-schema.html
I agree with the above poster... switch to PDO_MYSQL.
Select multiple tables using mysql
Update mutiple tables using mysql
How are you hosting your websites? Are they on the same hosting? If that is the case, you can use localhost. Otherwise you will need to enter the external hosting mysql database credentials.(multisite single database setup).
First you select all tables, then you get the data from each one.
You could do this if you are using mysql_*, but I strongly recommend to use mysqli_* or PDO.
$result = mysql_query("show tables"); // Select all tables
while($table = mysql_fetch_array($result)) {
$queryT = mysql_query("select * from '".$table[0]."'");
while($rtable = mysql_fetch_array($queryT)){
// data of the table
}
}

resource in mysql_connect in php

I am trying to connect to database through php.I did it lots of time. But I want to know how many rows exist in my table.
I've tried to use php manual, however, I was confused.
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
The above code worked on :
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
But when I decided to use
$link = mysql_connect("localhost", "mysql_user", "mysql_password","database");
It occurred an error like this:
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in ...
What is difference between codes? And how can I solve it?
Thanks in advance
The 4th parameter to mysql_connect is supposed to be a boolean type indicating whether you always want a new connection (even if mysql_connect was called earlier), not a string. As a result, $link is false because mysql_connect failed.
PHP documentation on mysql_connect
selecting DB as 4th parameter in mysql_connect is wrong - the functions returns false and no mysql_num_rows() following is possible
The mysql_connect function accept 5 arguments. In that in 4th argument this should be either true or false. But you have passed the string. This is not correct. you cann't pass the database name here.
For more tutorial see here and also this link.
You can not select database by mysql_connect() function. This function is used to connect to the database, not to query the database. To query the database use mysql_select() instead.
this parameters are allowed in mysql_connect
mysql_connect(server,user,pwd,newlink,clientflag)
please check http://www.w3schools.com/php/func_mysql_connect.asp

mysqli escape string additional parameter

Why mysqli_real_escape_string is asking additional parameter? In procedural method we must include connection establishment also. Whats logic behind that?
You're providing database connection link. This is so that you could have multiple MySQL connections at once.
In certain scenarios, you may want to open several connections and connect to multiple MySQL databases. Explicitly stating the connection link identifier that you want to use allows you to query multiple MySQL databases without worrying about conflicts.
//Open connections to two separate databases. For example: DatabaseOne and DatabaseTwo
$databaseOne = mysqli_connect("example.com", "user", "password", "DatabaseOne");
$databaseTwo = mysqli_connect("example.com", "user", "password", "DatabaseTwo");
//Make variable clean for first connection to DatabaseOne
$var= mysqli_real_escape_string($databaseOne, $var);
//QUERY TABLE FROM DATABASE ONE
$res1 = mysqli_query($databaseOne, "SELECT col FROM tableInDatabaseOne WHERE col = '$var'");
//do something with $res1
//QUERY TABLE FROM DATABASE TWO
$res2 = mysqli_query($databaseTwo, "SELECT col FROM tableInDatabaseTwo");
//do something with $res2

How to connect to multiple databases in a single PHP page? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
How do you connect to multiple MySQL databases on a single webpage?
If I want to connect to one db do some query, and then later do another query from another DB. How do I do it? Do I just
mysql_pconnect("host:3306", "user", "password") or die(mysql_error());
mysql_select_db("Test") or die(mysql_error());
//do some query
mysql_pconnect("host2:3306", "user", "password") or die(mysql_error());
mysql_select_db("Test") or die(mysql_error());
//do another query
Is that how you do it? A couple of questions. Notice I used pconnect, does that affect calling it twice on the same page? Also, do I have to close the connection for the first one before calling the second one?
You need to store database connection link in separate variable. For example
$connection_1 = mysql_connect("host:3306", "user", "password") or die(mysql_error());
mysql_select_db("Test", $connection_1) or die(mysql_error());
$connection_2 = mysql_pconnect("host2:3306", "user", "password") or die(mysql_error());
mysql_select_db("Test", $connection_2) or die(mysql_error());
mysql_query("your query", $connection_1); // run query for first connection
mysql_query("your query", $connection_2); // run query for second connection
You need to store the resource returned from mysql_connect and use it when doing mysql_select_db.
$res1 = mysql_pconnect(...);
mysql_select_db("Test", $res1);
$res2 = mysql_pconnect(...);
mysql_select_db("Test", $res2);
Then use $res1 or $res2 when querying the corresponding db.
mysql_query("select * from test_table", $res1);
mysql_query("select * from test_table", $res2);
Is that how you do it?
This will leave your script with two open connections to different hosts until it ends.
You may reuse either of these connections by calling mysql_pconnect again.
Notice I used pconnect, does that affect calling it twice on the same page?
From the docs:
The function would first try to find a (persistent) link that's already open with the same host, username and password
Since your hosts are different, there will be two different connections
Also, do I have to close the connection for the first one before calling the second one?
You cannot explicitly close a connection open with mysql_pconnect.
You did RTM, right, because you're not using the $link_identifier?
http://us.php.net/mysql_select_db :
bool mysql_select_db ( string $database_name [, resource $link_identifier ] )
Sets the current active database on the server that's associated with the specified link identifier. Every subsequent call to mysql_query() will be made on the active database.
Parameters
database_name
The name of the database that is to be selected.
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. If no connection is found or established, an E_WARNING level error is generated.
Whenever you have use the pconnect, you're sharing the connection (not only within the page, but possibly with other pages) -- in your case here, don't do that. You want isolated links, therefore isolated transactions. You should probably consider mysql_connect instead, and explicitly using the new_link parameter. Lastly, use the $link_identifier explicitly, so you are clear what you are connecting to.

Categories