Petr
Petr

Reputation: 7957

PHP - database not selected. What is wrong with my code?

I am learning PHP and tried to connect to MySQL. Altough I am using select DB, is still reports "No database selected". What is wrong, please? Thanks.

<?php

$user="test";
$pass="aaa";
ConnectToDb();

function ConnectToDb()
{
$pripojeni=mysql_connect('localhost',$user,$pass);
$selectedDB=mysql_select_db('1a');
    if($query=mysql_query('select * from project')) 
  {
  while($d=mysql_fetch_array($query)) 
  {
        echo "TEST";
        }
  }
  else echo mysql_error($pripojeni);
  }
?>

Upvotes: 2

Views: 280

Answers (2)

Bjoern
Bjoern

Reputation: 16304

You should give the function at least some parameters... try this:

[...]

ConnectToDb($user,$pass);

function ConnectToDb($MyUser,$MyPass) {
  $pripojeni=mysql_connect('localhost',$MyUser,$MyPass);

[...]

...in order to tell your function which user and which password to use. Otherwise the function doesn't know that $user and $pass are related to it.

Upvotes: 0

Amy B
Amy B

Reputation: 17977

$user and $pass are in the wrong variable scope.

Pass the values as parameters:

ConnectToDb('test', 'aaa');

function ConnectToDb($user, $pass)
{
    $pripojeni = mysql_connect('localhost', $user, $pass);
    ...
}

Upvotes: 3

Related Questions