0

Can I put a function in the file config.php ?

config.php :

<?php

$dbhost="localhost";  
$dbusername="user1"; 
$dbpassword="123456";
$dbname="dbname1"; 

$table_name="table1";

$db=mysql_connect($dbhost,$dbusername,$dbpassword) or die (mysql_error());
@mysql_select_db($dbname) or die (mysql_error());


function next_auto_increment(){
    $Result_auto_increment= mysql_query("SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '$dbname' AND TABLE_NAME = '$table_name' ");
    $row_auto_increment=mysql_fetch_array($Result_auto_increment);
    $auto_increment = $row_auto_increment['AUTO_INCREMENT']; 
    return $auto_increment;
}

?>

then I call the func from other php like this :

require_once "config.php";
$the_next_auto_increment = next_auto_increment();

but the function does not work !

if i put the function in the same php file, it works but in config.php not

Drew
  • 4,215
  • 3
  • 26
  • 40
Json
  • 59
  • 3
  • 13

2 Answers2

0

The $dbname and $table_name variables are not within the scope of the next_auto_increment function block.

You can pass them in as arguments:

function next_auto_increment($dbname, $table_name){
    ...
}    

Or you can use global to pull them into the scope:

function next_auto_increment(){
    global $dbname;
    global $table_name;

    ...
}

I also need to state the obligatory, "you should be using PDO and not mysql_connect"!

Drew
  • 4,215
  • 3
  • 26
  • 40
  • I did not use PDO connection before, so i can not use it. But **how to get atleast the var $dbusername from other php file ?** I just want now to get the fatabasename from there. I can put the function in other php file, no problem, but I need the database_name – Json Jun 11 '17 at 12:49
  • @Json Take a look at: http://php.net/manual/en/language.variables.scope.php – Drew Jun 12 '17 at 12:51
0

For one thing all the mysql_* functions are deprecated. I wouldn't use the mysqli_* functions either. Just PDO -- it is much safer to use and you don't have to worry about it being deprecated for many years to come.

But, the point is, this alone can cause your script to fail and do nothing. If your php.ini is not set to show you errors it may not be obvious if this is happening.

Try changing all the mysql_* functions to mysqli_* -- they are mostly equivalent except in a few places. mysql_select_db needs ... to be mysqli_select_db($db,$dbname). So would mysqli_query.

And also, globals. There are several variables in your next_auto_increment function that are defined globally that would not be accessible from your function. Something like:

global $db;
global $dbname;
global $table_name;

See the following to get errors to show up for you while developing.