I have read a lot about this but it still doesn't work.
I'm just trying to select a database to create a new table in, I try:
$db = mysqli_select_db("test");
if(!$db) {
echo "error: " . mysqli_error($db);
}
But I still get an error (and mysqli_error($db) doesn't seem to work).
Of course I have already connected to it:
$con=mysqli_connect("localhost", "administrator", "****");
On phpMyAdmin I have these databases:
Why can't I select "test" ?
And creating a database doesn't work because I don't have the rights, as you can see.
The procedular signature of this function is:
bool mysqli_select_db ( mysqli $link , string $dbname )
So you will have to provide the resource you got back from the mysqli_connect() to make it work. Something like this:
$con = mysqli_connect("localhost", "administrator", "****");
$success = mysqli_select_db($con, "test");
Alternatively you could specify the database on the connect call with a 4th argument:
$con = mysqli_connect("localhost", "administrator", "***", "test");
See the examples on mysqli_connect().
mysqli_select_db function requires two parameters link and dbname. Please refer to the documentation:
http://php.net/manual/en/mysqli.select-db.php
You are only passing link and no database name in your call:
$db = mysqli_select_db("test");
Related
I'm running this code on GoDaddy webhosting and I'm getting 'The database could not be found' echoed.
Obviously the database in question can't be selected, even though I've privileged the user and checked the db name.
I don't get anything out of here mysqli_error()
$db= 'test2' ;
$con = mysqli_connect('whatever','whatever','whatever') or die ('The connection to the database could not be established.');
mysqli_select_db($db , $con) or die ('The database could not be found' . mysqli_error());
As per the mysqli_select_db documentation, it expects the parameters this way:
mysqli_select_db ( mysqli $link , string $dbname ) : bool
So your parameters are put in backwards, change it to this:
mysqli_select_db($con, $db) ...
Or, alternatively, just select the database inside mysqli_connect().
$con = mysqli_connect('whatever','whatever','whatever', $db) ...
Side note, your die() isn't really doing anything, you won't get an actual error code out of that. To use mysqli_error(), you need to pass your database handle:
die('There was an error: ' . mysqli_error($con));
For the die() that is attached to mysqli_connect(), you should do this:
die('There was an error: ' . mysqli_connect_error());
I have the following code for test, and I just found the 2nd parameter is not actually working.
$conn1 = mysql_connect("127.0.0.1", "xxxx", "xxxx");
$conn2 = mysql_connect("127.0.0.1", "xxxx", "xxxx");
mysql_select_db("test", $conn1);
mysql_select_db("yangshengfun", $conn2);
if (!$res = mysql_query("select * from proxy_ips limit 1", $conn1)) {
echo mysql_error($conn1);
}
if (!$res = mysql_query("select * from wp_posts limit 1", $conn2)) {
echo mysql_error($conn2);
The tables in database 'test' and 'yangshengfun' are complately different.
An error occured while I run this code:
Table 'yangshengfun.proxy_ips' doesn't exist
Seems when I call mysql_select_db for $conn2, it changes the current db of $conn1 too, any ideas?
try this
$conn1= mysql_connect("host_name", "user_name", "pass_word") or die('not connected');
mysql_select_db("database_name", $conn1);
Here the "die($message)" function prints a message if mysql_connect() function can't connect with db.
try this
$conn1 = mysql_connect("127.0.0.1", "xxxx", "xxxx", true);
$conn2 = mysql_connect("127.0.0.1", "xxxx", "xxxx", true);
Note : mysql_* is deprecated. use mysqli_* or pdo
Use mysqli instead:
<?php
$conn1 = new mysqli(host, user, password, db);
$conn2 = new mysqli(host2, user2, password2, db2);
?>
From the documentation of mysql_connect() of the PHP Manual
If a second call is made to mysql_connect() with the same arguments,
no new link will be established, but instead, the link identifier of
the already opened link will be returned. The new_link parameter
modifies this behavior and makes mysql_connect() always open a new
link, even if mysql_connect() was called before with the same
parameters. In SQL safe mode, this parameter is ignored.
This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, Prepared Statements of MySQLi or PDO_MySQL extension should be used to ward off SQL Injection attacks !
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()? :)