tags:

views:

44

answers:

2

Hi, 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);
  }
?>
A: 

$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);
    ...
}
Coronatus
Thanks..I thought its the same as other languages.
Petr
A: 

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.

Björn