“没有数据库选择”错误与mysql_query

时间:2014-12-16 12:32:28

标签: php mysql

这是我的PHP代码

<?php
error_reporting(E_ALL);

class ll{
          function ll(){
            include "sql.php";
          }

         function getUser($ID) {
            $sql="select * FROM users where ID=$ID";
            $res = mysql_query($sql) or die (mysql_error());
            $obj = mysql_fetch_object($res);
            return $obj;
    }

        function setOfflineALL() {
            $sql="update users set online=0";
            mysql_query($sql);
        }

 }
        $services = new ll();
        $services->setOfflineALL(); // THIS WORKS !
        $services->getUser(1); // THIS GIVES error: No database selected 


        ?>

和sql.php是:

<?php   $hostname_con1 = "localhost";
        $database_con1 = "db1";
        $username_con1 = "root";
        $password_con1 = "mypass";
        $con1 = mysql_connect($hostname_con1, $username_con1, $password_con1) or trigger_error(mysql_error(),E_USER_ERROR);
        mysql_select_db($database_con1);
        mysql_set_charset('utf8',$con1);

?>
  • sql.php是正确的(没有错误)
  • setOfflineALL工作正常(无错误)
  • getUser引发&#34;没有数据库选择错误!&#34;但是我选择了一个mysql_select_db

我确实使用php5.4

有任何线索吗?

我也尝试过:

function getUser($ID) {
            $hostname_con1 = "localhost";
            $database_con1 = "db1";
            $username_con1 = "root";
            $password_con1 = "mypass";
            $con1 = mysql_connect($hostname_con1, $username_con1, $password_con1) or trigger_error(mysql_error(),E_USER_ERROR);
            mysql_select_db($database_con1);
            mysql_set_charset('utf8',$con1);

                $sql="select * FROM users where ID=$ID";
                $res = mysql_query($sql) or die (mysql_error());
                $obj = mysql_fetch_object($res);
                return $obj;
        }

仍有错误: 未选择数据库

1 个答案:

答案 0 :(得分:1)

你应该试试这个:

mysql_select_db($database_con1, $con1);

您也应该将数据库变量提供给您的查询:

mysql_query("query", $con1);

我强烈建议你不要使用mysql,而是使用PDO或mysqli PDO Mysqli