I am trying to connect to a mysql database within a php script. So far, my code looks like
//to my knowledge, this works. I was able to echo out the correct name
$name = $_POST["name"];
$server_name = "localhost";
$user_name = //my user name
$password = //my password
$db_name = //the db name
//it passes this error check, so I am connecting properly I am assuming
$dbconn = mysql_connect($server_name, $user_name, $password)
or die ('Could not connect to database: ' . mysql_error());
mysql_select_db($db_name, $dbconn);
$query = "SELECT *
FROM brothers
WHERE name = '$name'";
//it DOES NOT make it past this one
$result = mysql_query($query)
or die('Bad Query: ' . mysql_error());
//filter through the query as a row
$row = mysql_fetch_array($result, MYSQL_ASSOC);
//echo the result back to the user
echo $row["name"];
echo $row["major"];
//close the connection
mysql_close($dbconn);
I keep getting the error "No Database Selected", even though I am sure that I spelled the database name correctly (I copy pasted). Does anyone know why my code might be throwing this error?
Could be a permissions issue(the user which logon maybe don't have read rights on the database) :
mysql_select_db() fails unless the connected user can be authenticated
as having permission to use the database.
Here's my comment in answer form:
Do the same or die ('Could not use DB: ' . mysql_error()) after the mysql_select_db() call to find out what's going on there.
Your comment ("access denied") suggests that you have permissions to connect to the database server but not to use the database. Remember that one database server can have multiple databases on it, each with their own permission scheme. Check the permissions on the database you're trying to use and make sure that $user_name can use it with $password.
Related
Just built my first database to test out learning skills using the simple query below:
<?php
mysqli_connect("xxx","yyy","zzz" , "newtone" );
if (mysqli_connect_error()){
echo ("could not connect to database");
}
?>
This is what I got
:(42000/1044): Access denied for user 'yyy'#'xxx' to database 'newtone'......
I don't get it. So When i Use this:
mysqli_connect("xxx","yyy","zzz" );
if (mysqli_connect_error()){
echo ("could not connect to database");
}
?>
I don't get an error message, just a blank page (notice how the database name is not included on the login argument). What am I doing wrong?
You want to connect with database then need three things for create connection dbhost username,dbhost password and your database name.
<?php
$dbhost = "localhost";
$dbuser = "root"; //In case of localhost (default db username)
$dbpass = ""; //In case of localhost
$dbname = "testDb";//Your database name
$con = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname );
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Your 2nd example works because you are successfully connecting to the MySql server, and defaulting to a default database other than "newtone"
If you tried a command like mysqli::select_db after connecting, you would see the same error. http://php.net/manual/en/mysqli.select-db.php
The crux of your problem seems to be permissions for your user yyy. Make sure user yyy has various permissions like read/write on the DB "newtone"
For some reason, the following code inside the query works in my MySQL command console, yet when I try to run it as a Query in PHP, something keeps going wrong and I'm not sure what. Here is the code I've done so far.
//2. Perform database query
$query = "SELECT skills.element_id, content_model_reference.element_id, element_name FROM skills, content_model_reference WHERE (skills.element_id = content_model_reference.element_id)";
$result = mysql_query($query);
//Tests if there was a query error
if(!$result){
die("Database query failed.");
}
Is there something preventing the code that worked in MySQL (The line with SELECT) from working, or is my syntax somehow wrong?
EDIT: So it's saying I didn't select a database. Yet I thought I had. Here is the code above it:
//1. Create a database connection
$dbhost = "host"; //Host: Can be either an IP address, or a domain (like google.com).
$dbuser = "user";//User: The user that is connecting to the database.
$dbpass = "pass";//Password: This is the password that the user is using.
$dbname = "db";//Name: This is the name of the database.
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);//The value, 'handle,' is the connection.
//Test if connection occurred. Die ends the program/php, and in this case, also prints a message
if(mysqli_connect_errno()){
die("Database connection failed: ".
mysqli_connect_error().
" (". mysqli_connect_errno() . ")"
);
}
Like I said, the error message I am getting is pertaining only to the query, the server is fine with my database connection.
You're using mysqli_* for the connection, but you're using mysql_* for the QUERY... don't think you can do that, has to be one or the other (MYSQLI_ preffered). Also the query should be:
$result = mysqli_query($connection,$query);
Can anyone see what the problem with my code is / where im going wrong?
I know i have the correct host,database,user and password.
This is the code in the php file, it should get all the details available on the players from my sql database, however if i go on the page it just gives me a white page. Im using go daddy as a host and my database is also on there.
Any ideas? thanks
<?php
$host = "abc12345"; //Your database host server
$db = "abc12345"; //Your database name
$user = "abc12345"; //Your database user
$pass = "abc12345"; //Your password
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if (!$connection) {
die("Database server connection failed.");
} else {
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if (!$dbconnect) {
die("Unable to connect to the specified database!");
} else {
$query = "SELECT * FROM Player";
$resultset = mysql_query($query);
$records = array();
//Loop through all our records and add them to our array
while ($r = mysql_fetch_assoc($resultset)) {
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
The script is all right, I checked it with a different query.
Assuming that the table Player is not empty, the error can be either with your raw sql query (as pointed by #Sharikov in comments), otherwise the error is with the way you have configured your godaddy server.
For debugging that, I would suggest inserting dummy print_r or echo statements before you execute the query, and going through your apache logs at /var/log/apache2/access.log.
Also make sure that you don't have any core php package missing on your server (like php5-mysql if you use mysql).
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()? :)
hi i am using mysql for my database. just i try to connect mysql db through looping but it failed , i cannot , Is there is any otherway to do this
my trial code is this
while($row = mysql_fetch_array($query)) {
$temp = "db".$row["listid"];
$temp = mysql_connect("localhost","root","", true);
mysql_select_db($row["databasename"],$temp);
}
is it any other way to do this.
Try with:
$res = mysql_query($query);
while($row = mysql_fetch_array($res)) {
$name = "db".$row["listid"];
$temp = mysql_connect("localhost","root","", true) or die('Could not connect: ' . mysql_error());
mysql_select_db($row["databasename"],$temp);
$res = mysql_query($query, $temp);
}
and tell us your error - but, as the first comment, this is highly NOT recommended
You only require ONE database connection.
Once you connect to a database it is available for the life of that page (request).
If you require to switch databases that will also use the same connection (unless different credentials are required.
If it's for cross database queries if they are on the same MySQL server and the user for the initial connection has sufficient privileges, then you can prefix database tables with the database name.