2

I have the following PHP code:

$con = mysql_connect("localhost","name","pass") or die(mysql_error());

$db = "db";

mysql_select_db($db,$con);

Now in my experience, $con should be true or false. When I echo $con I get:

Resource id #25

If I do the following code, the echo never fires (as to be expected after the above statement):

if($con) { echo "it worked"; }

When I run a query against this connection, everything works as expected. Is there a reason why this $con will not be true or false?

What am I doing wrong?

Thanks

1

3 Answers 3

5

Check mysql_connect Return Values :

Returns a MySQL link identifier on success or FALSE on failure.

So to check the connection:

if($con !== false) { echo "it worked"; }

or to quit in case of an error:

if (!$con) {
    die('Could not connect: ' . mysql_error());
}

A word of advice though, better to use the MySQLi or PDO_MySQL instead of mysql_connectsince it will soon be deprecated:

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

mysqli_connect()

PDO::__construct()

Sign up to request clarification or add additional context in comments.

Comments

0

Its simply b/c of the or or die(mysql_error()); at the end.

Give this a shot:

<?php
$con = mysql_connect("localhost","name","pass");
$db = "db";
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db($db,$con);
?> 

Comments

-1

I think it is because of the or die(mysql_error()); part. I should be the $con = mysql_connect("localhost","name","pass") only. Then you can check like this: if (!$con).

1 Comment

@tereško, why the -1 for linking to w3schools, if I may ask?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.