Page 1 of 1

No Database Selected

Posted: Sun Jan 08, 2012 2:21 am
by jayson.ph
Hi, all i wander that, how could it be no database selected?

Code: Select all

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

mysql_select_db("mydatabase", $con);

$sql="INSERT INTO tbl_login (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[uname]','$_POST[pwd]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

mysql_close($con)
?> 

Re: No Database Selected

Posted: Sun Jan 08, 2012 2:40 am
by Christopher
Maybe the name of the database is wrong and mysql_select_db() is failing. Check its return value.

Also for security, do not insert $_POST or $_GET variables directly into SQL strings. I would recommend using PDO and prepared statements.

Re: No Database Selected

Posted: Sun Jan 08, 2012 2:43 am
by twinedev
It could be that "mydatabase" doesn't exist or that the user you are connecting with does not have permission to use it.

Code: Select all

<?php

$con = mysql_connect('localhost','user','pass')
           or die('ERROR: Could not connect to Database Server - '.mysql_error());

mysql_select_db('mydatabase',$con) 
    or die('ERROR: Could not access specified Database - '.mysql_error());

// Your SQL didn't have POST indexs that matched field... so you will want to fix!
$SQL = sprintf('INSERT INTO `tbl_login` (`FirstName`,`LastName`,`Age`) VALUES ("%s","%s","%s")',
               mysql_real_escape_string($_POST['firstname']),
               mysql_real_escape_string($_POST['uname']),
               mysql_real_escape_string($_POST['pwd'])
              );

mysql_query($SQL) 
    or die('ERROR: '.mysql_error());

echo '1 record added';

mysql_close($con);

?>

Re: No Database Selected

Posted: Sun Jan 08, 2012 3:03 am
by jayson.ph
Thsnk You all, thank for a nice advice

and from the part : $con = mysql_connect("localhost","","") : what password and user that should i put. since every time i put a password and user i got this error below and i thing its the one why i can't connect to a database.

Could not connect: Access denied for user 'root'@'localhost' (using password: YES)

Re: No Database Selected

Posted: Sun Jan 08, 2012 3:16 am
by twinedev
Well, if you are actually doing a connect to mySQL without a user and password, then you are most likely connecting as guest, and the only database you will be able to access is on called "test" (if it exists, many times it is removed). Try telling it to select "test" instead, see what happens. (if it does select it, your INSERT will fail though)

The username and password you would need we can't give, it would be given to you by either the person or system that is setting up the database for you to use.

-Greg