-2

I use this code for connecting to sql in PHP:

public function ffff(){
    $connection = new mysql();
    $connection->connect('127.0.0.1','root','','miscfb');
}

but I want to use a variable instead of 'miscfb'.

for example: $db='miscfb';

and the code will be:

$connection->connect('127.0.0.1','root','',$db);   

but it cannot connect to database!

How should I use variables?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
  • THe new keyword is mis typed `$connection()=ne mysql();` it should be `$connection()=new mysql();` – Nouphal.M Feb 15 '14 at 07:30
  • Have you read documentation, examples, googled something? – sybear Feb 15 '14 at 07:30
  • Not a good idea to log in as root – Ed Heal Feb 15 '14 at 07:30
  • @EdHeal if it is a local development server then there wouldn't be a problem – Cjmarkham Feb 15 '14 at 07:31
  • Your code isn't throwing a syntax error? Looks like bad code to me before the line in question. – jimp Feb 15 '14 at 07:32
  • @CarlMarkham - I have seen it all too often that people log in as root for development and then it gets overlooked when moving it into production. Also during development people do make mistakes. Not being root can minimize that risk. – Ed Heal Feb 15 '14 at 07:33
  • It appears that you're using the variable in question correctly. I would suspect some other part of your code. The following is correct assuming the class implementation is correct. $db = "miscfb"; $connection->connect('localhost','username','password?',$db); – CreationTribe Feb 15 '14 at 07:33

2 Answers2

0

If $db is declared inside ffff(), then that should work. If it's declared above the function, try $this->db. However if this is a connection error, instead of a variable usage question (hard to tell) then maybe you can explain an error that's being returned?

Side note: please start to move away from mysql_* and start implementing PDO or mysqli.

Quick edit! Thanks :)

Alex L
  • 470
  • 6
  • 15
0
<?php
   //setting CONSTANTS for host, user, password (good practies in development step)
   DEFINE('DB_HOST', 'localhost'); 
   DEFINE('DB_USER', 'root'); 
   DEFINE('DB_PASS', 'root_pwd');  

  //storing the result of the connection (mysqli $link) in a variable 
  $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASS) or 
                    die('could not connect: '. mysqli_connect_error() );

   //storing the name of the database you want to work with
   $DB_NAME="miscfb";

  //selecting the database
  mysqli_select_db($dbc, DB_NAME) or die('could not select db');

?>

I suggest you to use Mysqli o PDO connection. Mysql "classic" connection will be deprecated on future version of PHP, that will began completely Object Oriented.