dongyue0263 2011-02-05 20:07
浏览 55
已采纳

mysql_connect和mysql_selectdb没有将一些变量作为参数的奇怪问题

I was working in some code in a PHP course I assisted, in a LAMP environment, and worked without problems. After the course, I took my code home and ran it on a WAMPServer, and for some reason, mysql_connect is not accepting some variables as arguments. I know this because I tried giving the parameters to mysql_connect by hand and the connection works. Also, I echoed all four variables and they print out OK.

I am new to PHP, but this doesnt make any sense to me.

The code:

functions.php

 <?php

require ("config.php");
     function conectardb () { 
     mysql_connect ($server, $login, $pass);
     mysql_select_db ($db);
 }

?>


config.php

<?php
 $login = "root" ;
 $pass = "" ;
 $server = "localhost";
 $db = "testing";
?>

I've tried replacing the plain arguments by their variables one by one, and found out the code works until this point:

 function conectardb () { 
     mysql_connect ($server, "root", $pass);
     mysql_select_db ("testing");
 }

If I use $login or $db, the connection will not work. Any ideas? This is driving me crazy.

  • 写回答

4条回答 默认 最新

  • dsnhalq37505 2011-02-05 20:09
    关注

    This is a misunderstanding of scope in PHP.

    Functions exist in their own scope. You defined $login, $pass, etc. in a different scope than the function. The function can't access them, it can't see them.

    You can do a couple things about this:

    1. Define the database connection parameters as constants instead of variables
    2. Define the variables within the function (requiring the configuration file inside the function will have the same effect)
    3. Use the global keyword to pull them from the global scope into the function scope

    i.e.

    $bar = 'hello world';
    function foo() {
        global $bar;
        echo $bar;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式