PHP Undefined variable in functions and included scripts

后端 未结 3 1060
别跟我提以往
别跟我提以往 2021-01-22 19:34

I\'ve read a LOT of things about this problem, however I still cannot fix it.

In my functions file I declare a variable with a value like so:

$px_host =          


        
3条回答
  •  被撕碎了的回忆
    2021-01-22 20:32

    In your specific case you should declare global within function all variables outside the function. So

    function dbQuery($database, $reqquery){
        global $px_host,$px_dbuser,$px_dbpass;
        // rest of function
    }
    

    But your code can be improved: You should define constants at the beginning of your script

    define('DB_HOST','localhost');
    define('DB_USER','user');
    define('DB_PASS','pass');
    

    and use constants inside the function (so no need to declare global, and it's more logic because host, user and pass aren't variable but constants).

    You should connect at database only once at the beginning of your flow so the function dbQuery execute only the query (according with the function name).

    EDIT for completeness of answer:

    As some users say you in other comments, I invite you to read the php doc for mysql_connect and see the red advise:

    Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

    I'm not here for say you what you MUST do in your project, but read the doc and follow the tipps/suggestions is essential for the success of your project. :)

提交回复
热议问题