0

Let me apologize in advance. I've been working on this project all day and I'm tired and probably just need sleep but I can't seem to connect to a mysql database from a function.

I have a database file which get's called through require_once() and have a function that is being called but it doesn't seem to want to connect.

Here's the connect code:

// Create connection
$con  =  mysqli_connect("$database_serverURL","$database_username","$database_password","$database_dbName");

 // Check connection
 if (mysqli_connect_errno($con))
 {
  $database_error = true;
  $database_errorInfo = mysqli_connect_errno($con);
 }

 $database_error = false;

Here's my function:

//Select from database

function selectFromDatabase($table_name){

    //Declare array
$return_array = array();

    //Make query
$result = mysqli_query($con,"SELECT * FROM $table_name");

while($row = mysqli_fetch_array($result)){

    $return_array = $row[];

}

writeJson($return_array); 

//close database connection
mysqli_close($con);
}

It says that the first parameter is null and it's supposed to be the database connect information. I know I can make a connection to the database and pull info from the table but when it's inside the function it doesn't want to work.

I tried making the connect data global but that didn't work and i have a feeling that's a bad idea.

I feel like i should learn more about class systems and functions and stuff but I just want this to work.

Sorry if it's right in front of me. I even tried putting the connection code inside the function but still squat.

Again sorry for the stupid question. Especially due to the fact that it's about connecting to a database :P

Edit:

This was my first attempt on creating an Object Oriented script. Here was my final solution.

I had a config script called class_config.php:

<?php

class declarations{

     //Define variables
     private $databaseArray;

     //Populate variables
     public function populateVariables(){

          $this->databaseArray = array('databaseServer', 'databaseUsername', 'databasePassword', 'databaseName');

     }

     //Return variable requested
     public function returnVariable($variable){

          $this->populateVariables();

          return $this->$variable;

     }

}

?>

Database class (class_database.php):

<?php

//Include config class
require_once('class_config.php');

function createInstance(){

     //Create class instance
     $obj = new declarations;

     //Return class instance
     return $obj;

}

function connectDB(){

     //Create class instance
     $obj = createInstance();

     //Get database array from 'declarations' class
     $databaseArray = $obj->getVariable('databaseArray');

     //Create strings from array values
     list ($serverURL, $username, $password, $databaseName) = $databaseArray;

     //Create database connection
     $con = mysqli_connect($serverURL, $username, $password, $databaseName);

     //Return connection
     return $con;

}

?>

Anytime I need a database connection, I just call the database connect function. I would create an instance by using $con = connectDB(); and just use $con in my query. In my projects I usually have one function that executes all queries and returns the result:

function executeQuery($payload){

     //Create database connection
     $con = connectDB();

     //Execute database query
     $result = mysqli_query($payload);

     //Return result
     return $result;

}
evan.stoddard
  • 698
  • 1
  • 5
  • 22
  • Let add I'm using mysqli if you didn't already see ;) – evan.stoddard May 12 '13 at 04:21
  • 2
    `*sigh*` It seems most popular question under the tag. http://stackoverflow.com/questions/16498855/mysqli-database-connection-error-when-using-functions-from-different-files – Your Common Sense May 12 '13 at 04:25
  • Thanks dude! Your name seems to fit perfectly! I can't believe I didn't do that! I guess I just need some sleep ;P. Put your comment as the answer so I can give you some points :) – evan.stoddard May 12 '13 at 04:28

6 Answers6

2

At least, you have to pass $con into your function to use it.

Like this:

function selectFromDatabase($table_name, $con)
{
    ...
}
Paul Denisevich
  • 2,329
  • 14
  • 19
1

Maybe the $con is outside the scope of your function. If you rewrite your function to

function selectFromDatabase($con, $table_name){
   //Declare array
   $return_array = array();

    //Make query
    $result = mysqli_query($con,"SELECT * FROM $table_name");

    while($row = mysqli_fetch_array($result)){

        $return_array = $row[];

    }

    writeJson($return_array); 

    //close database connection
    mysqli_close($con);
    }
}

then pass the $con into the function or you can keep it the same and use a global connection like another person posted.

decapo
  • 789
  • 3
  • 8
  • 25
  • Also if you are learning this is cool. But I think parameterized queries are more secure. See this question http://stackoverflow.com/questions/60174/how-to-prevent-sql-injection-in-php – decapo May 12 '13 at 04:48
0

your variable $con is local to your connection file you need to create a more global scope variable or make your connection a function to return a value or do global $con

function selectFromDatabase($con, $table_name){


     //Declare array
       $return_array = array();

        enter code here
        global $con; //include this
        //Make query
        $result = mysqli_query($con,"SELECT * FROM $table_name");

        while($row = mysqli_fetch_array($result)){

            $return_array = $row[];

        }

        writeJson($return_array); 

        //close database connection
        mysqli_close($con);
        }
    }
0

I ended up making a class and have a private string and a function to connect to the database:

class database{

private $con;

private function connectDB(){

    $this->con = new mysqli("server","username","password","dbName");
    return $this->con;

}

then just instance the object:

function createInstance(){

$obj = new database;

}

function requireDatabase{

    $obj = createInstance();

    $con = $obj->connectDB();

    mysqli_query($con, 'SELECT * FROM foo');

}
evan.stoddard
  • 698
  • 1
  • 5
  • 22
0

This was my first attempt on creating an Object Oriented script. Here was my final solution.

I had a config script called class_config.php:

<?php

class declarations{

     //Define variables
     private $databaseArray;

     //Populate variables
     public function populateVariables(){

          $this->databaseArray = array('databaseServer', 'databaseUsername', 'databasePassword', 'databaseName');

     }

     //Return variable requested
     public function returnVariable($variable){

          $this->populateVariables();

          return $this->$variable;

     }

}

?>

Database class (class_database.php):

<?php

//Include config class
require_once('class_config.php');

function createInstance(){

     //Create class instance
     $obj = new declarations;

     //Return class instance
     return $obj;

}

function connectDB(){

     //Create class instance
     $obj = createInstance();

     //Get database array from 'declarations' class
     $databaseArray = $obj->getVariable('databaseArray');

     //Create strings from array values
     list ($serverURL, $username, $password, $databaseName) = $databaseArray;

     //Create database connection
     $con = mysqli_connect($serverURL, $username, $password, $databaseName);

     //Return connection
     return $con;

}

?>

Anytime I need a database connection, I just call the database connect function. I would create an instance by using $con = connectDB(); and just use $con in my query. In my projects I usually have one function that executes all queries and returns the result:

function executeQuery($payload){

     //Create database connection
     $con = connectDB();

     //Execute database query
     $result = mysqli_query($payload);

     //Return result
     return $result;

}
evan.stoddard
  • 698
  • 1
  • 5
  • 22
-3

use inside function

global $con;
  • Especially when it's connecting to a database. You will cause too many connections and get mad at you. And it is going to be in an app so if many people are using it at one time... boom goes my script. – evan.stoddard May 12 '13 at 04:44