2

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);
  }
?>

2 Answers 2

3

$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);
    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks..I thought its the same as other languages.
0

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.

Comments

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.