2

new here, only starting basic PHP. Trying to understand the specifics of the two MySQL commands. Please see this code

<?php   
$hostname = "localhost";
$username = "";
$password= "";
$databaseName = "alphacrm";

$dbConnected = mysql_connect($hostname, $username, $password);

$dbSelected = mysql_select_db($databaseName, $dbConnected);   ?>

If I run the code:

mysql_connect - successful

mysql_select_db - failed.

Question: why won't both fail if the $username is empty/wrong?

Note: I know I just need to input the value for $username and it will work. I am not trying to make it work, I am trying to understand why BOTH functions are not failing when $username has no value

Thanks.

Edit: @Jason: Thank you, I now know I am using outdated learning material

Andrejs
  • 10,803
  • 4
  • 43
  • 48

2 Answers2

3

Try to get more information with

if ($dbSelected){
 ...
} else {
    die ('Can\'t use foo : ' . mysql_error());
}

it might tell you what the problem is!

Put it in both of your else statements so you will know what mysql is doing!

mahatmanich
  • 10,791
  • 5
  • 63
  • 82
  • Only 2nd day with PHP, not pretending to know better, but a lot of sources are against "die" method, e.g.:http://www.phpfreaks.com/blog/or-die-must-die – Andrejs Sep 18 '13 at 12:48
  • Tried. Says:`DB connection FAILEDCan't use foo : Access denied for user ''@'localhost' to database 'alphacrm'` Understandable, I left `$username` undefined. BUT it still connects to MySql with that `$username` as a parameter. So does `mysql_connect` ignore invalid parameters by default/nature? – Andrejs Sep 18 '13 at 13:00
  • $username is '' so it is an empty String actually in your case a single space " ", it is not undefined! Take out $username entirely! – mahatmanich Sep 18 '13 at 13:19
  • It tries to connect do the db with a username of " " but the authentication fails! – mahatmanich Sep 18 '13 at 13:22
  • Andrey the die method is taken directly from the documentation example of mysql_connect! – mahatmanich Sep 18 '13 at 13:27
0

mysql_connect is enclosed in a variable $dbConnected, it is nothing to do until unless it has been put in mysql_connect.

when PHP reads the mysql_connect it finds the incorrect credentials so that's wht mysql_connect fails.

Moeed Farooqui
  • 3,604
  • 1
  • 18
  • 23
  • `mysql_connect` is actually successful, it is `mysql_select_db` that fails. the `credential`, in this case the `$username` is wrong (I made it intentionally), so I expected both functions to fail. But only `mysql_select_db` failed. And I wondered why? – Andrejs Sep 18 '13 at 12:54
  • I just tested just these functions. For me, already connect fails when credentials are wrong. So that it doesn't fail for you, I find indeed strange. – Ralf Nov 06 '15 at 09:45