How do I select mysql database in php? - php

I have this code:
if(!mysql_connect($host,$user,$passwd)){
die("Hoops, error! ".mysql_error());
}
...no error from here.
if(!mysql_select_db($db,$connect)){
$create_db = "CREATE DATABASE {$db}";
mysql_query($create_db,$connect);
mysql_query("USE DATABASE {$db}",$connect);
}
..."no database selected" error from here.
I would like to select database if it exists and if doesn't then create it and select it.
Why is my code not right?
Thank you in advance

Where are you saving the value returned by mysql_connect()? Don't see it here. I assume $host, $user, $password and $db are properly set ahead of time. But you're passing a param to mysql_select_db that may not be properly set.
$connect = mysql_connect($host,$user,$passwd);
if (!$connect) {
die('Could not connect: ' . mysql_error());
}
if(!mysql_select_db($db,$connect)) ...
Start by checking to see if you can select without the CREATE query first. Try a simple SELECT query to start. If you can connect, select the db, and execute a SELECT query, that's one step. Then try the CREATE query. If that doesn't work, it's almost certainly a matter of permissions.

You might need database create permissions for the user attempting to create the database.
Then you need to operate on a valid connection resource. $connect never looks to be assigned to the connection resource.

Why not simply use the CREATE DATABASE IF NOT EXISTS syntax instead?
Something like this ...
$con = mysql_connect('localhost');
$sql = 'CREATE DATABASE IF NOT EXISTS {$db}';
if (mysql_query($sql, $con)) {
print("success.\n");
} else {
print("Database {$db} creation failed.\n");
}
if(!mysql_select_db($db,$connect)){
print("Database selection failed.\n");
}

You should check the return value of mysql_query() - currently if any of those calls fail you won't know about it:
if(!mysql_select_db($db,$connect)){
if (!mysql_query("CREATE DATABASE $db", $connect)) {
die(mysql_error());
}
if (!mysql_select_db($db, $connect)) {
die(mysql_error());
}
}

Change the line
mysql_query($create_db,$connect);
mysql_query("USE DATABASE {$db}",$connect);
To
mysql_query($create_db,$connect);
mysql_select_db($db);*
and it should work.

you could try w3schools website. They have a very simple and easy to learn tutorial for selecting database. The link is : http://www.w3schools.com/php/php_mysql_select.asp
Hope this help :)

I would like to thank to all of you, however I found fault on my side. This script was in class and one of variables were not defined inside this class. So I'm really sorry.
I don't know how to consider the right answer, but I noticed my mistake after reading Clayton's answer about not properly set parameters, so I guess he is the winner ;)

Related

PHP: could not find database

i am having difficulty with connecting my database to mysql, i have tried many different ways of trying to get it to connect to my database, but none these methods seem to work. I am only new to php and i could be missing something, but i dont know what it is.
This is for a search engine, i have the form created.
I would think that my problem is coming from this line of code, mysql_connect("localhost", "root", "") or die("could not connect");?!
I was wondering if i could be told what is the problem and how to fix it, thank you so much.
here is my code below.
<?php
//connect
mysql_connect("localhost", "root", "") or die("could not connect");
mysql_select_db("search") or die("could not find database");
$output = '';
if (isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","", $searchq);
$query = mysql_query("SELECT * FROM gp management system WHERE Title LIKE '%$searchq%' OR Description LIKE '%$searchq%' OR Keyword LIKE '%$searchq%'") or die("could not search");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'There was no search results!';
}
else{
while($row = mysql_fetch_array($query)) {
$Title = $row['Title'];
$Description = $row['Description'];
$Keyword = $row['Keyword'];
$output .= '<div> ' .$Keyword. ' </div> ';
}
}
}
?>
SQL errors:
SELECT * FROM gp management system WHERE Title...
^^-- table name
^^^^^^^^^^ aliasing 'gp' as 'management'
^^^^^^-- extra unknown garbage
Table names shouldn't have spaces to begin with, but if you insist on having them, then you need proper quoting:
SELECT * FROM `gp management system` etc...
^--------------------^
Never output a fixed/useless "could not search" error. Have the DB tell you what went wrong:
$result = mysql_query($sql) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^^
As your only new, you really should stop using mysql_ and change to mysqli_ or (my preference) PDO(). Your message in your title seems to be coming from your selectdb line, so you're actually connecting to the database fine, it's just not able to locate the schema that you are trying to use (i.e. "search" does not exist as a schema name in your DB environment). Unless that's not the error that you are getting, in which case it's a flaw in your actual SQL query. Without an accurate statement of what you are getting back on the screen when you try to run the script then not much can be done to help.
I would rather do somehow like I did ages ago, see below:
function db_connect($host, $username, $passwd, $db_name) {
$db = mysql_connect($host, $username, $passwd);
if (!$db) {
echo "Login to database failed: ";
echo mysql_error();
return false;
}
$result=mysql_select_db($db_name); //Select the database
if (!$result) {
echo "Cannot find the database: ".$db_name;
echo mysql_error();
return false;
}
return $db; //Database descriptor
}
However you shouldnt rely on the old MYSQL extension, but use MYSQLi.
EDIT: as #tadman pointed out there were a # sign infront the mysql_connect call, however there is an if statement for checking and a call to error output.
As others have said, your code is something of a mess - you seem to be new to programming, not just in PHP. But everyone has to start somewhere, so....
You might want to start by learning a bit about how to ask questions - specifically you have included a lot of code which is not relevant to the problem you are asking about - which is about connecting to MySQL. OTOH you have omitted lots of important information like the operating system this is running on and what diagnostics you have attempted. See here for a better (though far from exemplary example).
Do read your question carefully - the title implies an issue with mysql_select_db() while in the body of the content you say you think the problerm is with mysql_connect(). If you had provided the actual output of the script we would have been able to tell for ourselves.
You should be checking that MySQL is actually running - how you do that depends on your OS. You should try connecting using a different client (the mysql command line client, sqldeveloper, Tora, PHPMyAdmin....there are lots to choose from).
You should also check (again this is operating system specific) that your MySQL instance is running on the same port as is configured in your php.ini (or overridden in your mysql_connect() call).
MySQL treats 'localhost' as something different from 127.0.0.1 on Unix/Linux systems. If this applies to you try 127.0.0.1 in place of localhost.
or die("could not connect");
Does not help in diagnosing the problem. If instead you...
or die(mysql_error());
You will get a more meaningful response.
BTW: while writing code using the mysql extension rather than mysqli or PDO is forgivable, I am somewhat alarmed to see what appears to be medical information managed with no real security.

php mysql Insert into not working

So what I am trying to do is a very basic and straight way of inserting a record into mysql db.
It is just something I have done few times before, however for some reason it is not working with me this time.
So in the following couple of lines of code I will show my code, which basically do the following
1- Check if the user exists in the DB (An existing user is a user with the same email)
2- If the user exists in the DB then it sends an http response with a status code of 409 which means duplication.
(Anyway note that this works perfectly, which implies the connection was made successfully to the DB, and it was able to retrieve any exact user, if any)
3- If the user does not exist it should be inserted in the DB (Here is the problem)
My Code
//Checking if the user exist
$result = mysql_query("SELECT * FROM $table_name WHERE email='".$post_email."'",$con) or die ('Error: '.mysql_error ());
$num_rows = mysql_num_rows($result);
if($num_rows > 0){
// Close Connection
mysql_close($con);
echo "409";
}
else{
mysql_query("INSERT INTO samam_users (username,password,email) VALUES ('ALI','AHMED','amsh-1992#hotmail.com')",$con);
// Select the record
$user_id = mysql_insert_id();
$result = mysql_query("SELECT * FROM $table_name WHERE email='".$post_email."'",$con) or die ('Error: '.mysql_error ());
// Close Connection
mysql_close($con);
echo "200 " . $result['username'];
}
I googled the possible solutions for this issue, however all similar issues I went through were because of syntax errors.
Any suggestions? Thanks in advance :)
What is the exact error message you are getting? Copy/paste that here, please.
Also, the only odd thing I see is that you are doing the SELECT commands with a variable $table_name, and in the INSERT command you are hard-coding a table name..? Maybe that's it?
INSERT INTO samam_users ...
just put the same table name variable there?
INSERT INTO $table_name ...
Let me know if this helps. :)
$sql = "INSERT INTO samam_users (username,password,email) VALUES ('ALI','AHMED','amsh-1992#hotmail.com')";
if(!mysql_query($sql,$con)) {
die(mysql_error());
}else {
echo 'inserted succesfully';
}
mysql_error() will give you information about why your query isn't working - allowing you to debug it.
Also don't use mysql_*, it's going to be deprecated and there are much better more secure options like MySQLi or preferably PDO
I think you have to put all the values in INSERT command in double quotes instead of single quote

Mysql fails in php but works in phpmyadmin

I've made this a lot of times but now I can't :(
The insert allways return false but if I execute the same SQL script (taked from the output) it inserts in the database without any problem. I'm connected to the database because some values are fetched from another table.
This is my code:
$query = "INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx,equipo_compania,paciente,sexo,edad,id_compania,otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('$fecha','$macropera','$pozo','$equipo_pmx','$equipo_compania','$paciente','$sexo',$edad,$id_compania,'$otra_compania','$puesto','$ta','$tum','$ove','$coordinador')";
if (mysql_query($query,$connection)){
//OK
} else {
$errno = mysql_errno();
$error = mysql_error();
mysql_close($connection);
die("<br />$errno - $error<br /><br />$query");
exit;
}
The output is:
0 -
INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx, equipo_compania,paciente,sexo,edad,id_compania, otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('20111001','P. ALEMAN 1739','P. ALEMAN 1715','726', 'WDI 838','SERGIO AYALA','M',33,21, '','','110/70','ROBERTO ELIEL CAMARILLO','VICTOR HUGO RAMIREZ','LIC. PABLO GARCES')
Looks like there are no error, but allways execute the code in the else part of the if instruction. Any idea? Thanks in advance.
I think the issue might be you are missing the mysql_select_db line after the connection.
After the connection with the database is established you need to select a DB. Please make sure you have selected the Database that your desired table resides in.
And you can even use the following snippets to get some useful informated through mysql_errors.
$connection = mysql_connect('localhost', 'root', 'password');
if (!$connection) {
die('<br>Could not connect: ' . mysql_error());
}
if (!mysql_select_db('db_name')) {
die('Could not select database: ' . mysql_error());
}
And try you insert query after these lines of code. All the best.
I agree with the others concerning the column types. INT is one of the only data types that do not require single quotes.
There are two blank strings. There is a possibility that the variables are not defined, and therefore giving you a PHP exception (not even in the MySql yet) but that requires stricter-than-normal exception settings. I would personally look into the $connection variable. Before the SQL query statement, put this and send us the cleaned results:
echo '<pre>'.var_dump($connection, true).'</pre>';
Additionally, on your mysql_connect function call, put
OR die('No connection')
afterwords. Do the same thing with the mysql_select_db function, changing it to 'No DB Select' obviously.
Ultimately, we will need more information. But changing to mysqli is very desirable.
Oh! And make sure the permissions for the user you are connecting as are not changed. Sometimes I find people who connect to PhpMyAdmin using one user account but a different account in their PHP code. This is problematic, and will lead to problems eventually, as you forget the different accounts, at times.

Update query in MySQL and PHP not working

PHP usually works pretty much straight out of the box, but I cannot get this query to work. I am attempting to update a simple record. My code is as follows.
<?php
$customername=mysql_real_escape_string($_POST['customername']);
$contact=mysql_real_escape_string($_POST['contact']);
$customerorder=mysql_real_escape_string($_POST['customerorder']);
$orderplaced=mysql_real_escape_string($_POST['orderplaced']);
$staffmember=mysql_real_escape_string($_POST['staffmember']);
$daterequired=mysql_real_escape_string($_POST['daterequired']);
$status=mysql_real_escape_string($_POST['status']);
$paid=mysql_real_escape_string($_POST['paid']);
$delivery=mysql_real_escape_string($_POST['delivery']);
$ordercontent=mysql_real_escape_string($_POST['ordercontent']);
$orderid=mysql_real_escape_string($_GET['orderid']);
mysql_connect("localhost", "xxxx", "xxxxxxx") or die("Connection Failed");
mysql_select_db("xxxxxx")or die("Connection Failed");
$query = "UPDATE ordermanager_orders SET customername='$customername', contact='$contact', ordernumber='$customerorder', placedby='$orderplaced', requiredby='$daterequired', status=$status', staffmember='$staffmember', paid='paid', delivery='$delivery', ordercontent='$ordercontent' WHERE order='$orderid'";
if(mysql_query($query)){
echo "updated";}
else{
echo "fail";}
?>
The values are being posted or "Getted" from another page. They are definitely coming through as otherwise it comes up with errors. At the moment it simply comes up with 'failed' as per the code.
I have tried numerous variants of code found on the internet, to check if my coding was correct, however I still cannot get it to work.
I wonder if u have tried to print_r your $query to check.
1st. Shift your connection string to the top most.
2nd. status=$status' <<=== less 1 quote
I thought you had to connect to the database before you were able to use mysql_real_escape_string()? Try connecting above all other code.
The status section of the query is also missing a quote mark.
Try changing by adding a comma
status=$status' to status='$status'
And FYI change paid='paid' to paid='$paid' to ensure the correct value is passed
Your error is because of not handling your status update correctly: status=$status' must be status='$status'.
You would have figured this if you'd put a mysql_error() in your 'fail' section.

mysqli never returns anything

As part of a PHP web application, I'm querying a MySQL database using mysqli and prepared statements.
I've used exactly the same code on a few queries and it works, but on one particular query, it always returns an empty record set. I've run exactly the same query from the MySQL command line, and it correctly returns the result. I've checked the parameters being passed in, and they're fine.
I've spent the best part of a day trying to figure out why I'm always getting an empty record set with no errors or warnings. I've got PHP's errors set to display on the page, and I've got them set to E_ALL|E_STRICT. I still don't get any warnings or errors.
I've tried all the obvious things, like making sure I can actually connect to the database, checking the parameters that are being passed in, and making sure the row I'm trying to return actually exists in the database. I've had var_dump()s and die()s all over the page to check what's coming back, and it's always a legitimate, but empty, recordset.
function salt() {
return("I've removed my salt from this sample code");
}
function openDatabase() {
$conn = new mysqli("127.0.0.1", "username", "password", "database")
or die("Error: Could not connect to database.");
return($conn);
}
function checkUserCredentials($username, $password) {
$goodPassword = md5(salt().$username.$password);
$conn = openDatabase();
$query = $conn->stmt_init();
$query->prepare("SELECT id FROM users WHERE email = ? AND passwordHash = ?")
or die('Problem with query');
$query->bind_param("ss", $username, $goodPassword)
or die('Error binding parameters');
$query->execute() or die("Could not execute");
$query->bind_result($col1) or die ("Could not bind result");
if ($col1 !== 0) {
die("Authentication Complete");
} else {
die("Authentication Failure! Number of Rows: ".$query->num_rows." Username: " . $username . " Password Hash: " . $goodPassword);
}
}
Any feedback is appreciated. I'm sure I'm missing something simple, but if I didn't shave my head I'd be tearing my hair out right now.
Thanks
I'm not familiar with the mysqli library (I usually use PDO which provides a very similar cross platform API) so I can't immediately see any problem. However, you might try watching the mysqld log. See here for info:
http://dev.mysql.com/doc/refman/5.1/en/query-log.html
By tailing the log, you should be able to see the exact query that was submitted.
One final note, I notice you're using a fixed salt value. Wouldn't it be better to generate this value randomly each time you need it and then store it in the users table? Generally, a salt is not intended to be secret, it's just there to prevent people precomputing tables of passwords using the hash algorithm that you use.
In case anyone else runs into similar issues, it really helps if you run fetch() on your mysqli_stmt object.
In my code above, the solution looks like this:
$query->bind_result($col1) or die ("Could not bind result");
$query->fetch(); // <--- How could I forget to do this?
if ($col1 !== 0) {
return true;
} else {
return false;
}
Added on behalf of OP

Categories