我有mysql和php的问题

时间:2010-05-06 17:48:26

标签: php mysql mysqli

我遇到了问题,这是我的代码:

   $db = new mysqli("localhost", "root", "", "blah");

$result1 = $db->query("select * from c_register where email = '$eml' and password = '$pass'");

if($result1->fetch_array())

  {

        $auth->createSession();

        $_SESSION['user'] = 'client';

        promptUser("You have successfully logged in!!!","index.php");
  }

$db = new mysqli("localhost", "root", "", "blah");

$result2 = $db->query("select * from b_register where email = '$eml' and password = '$pass'");
  if($result2->fetch_array())

  {

         $auth->createSession();

         $_SESSION['user'] = 'business';

         promptUser("You have successfully logged in!!!","index.php");
  }
$db = new mysqli("localhost", "root", "", "blah");

$result3 = $db->query("select * from g_register where email = '$eml' and password = '$pass'");
  if($result3->fetch_array())

  {

        $auth->createSession();

        $_SESSION['user'] = 'employee';

        promptUser("You have successfully logged in!!!","index.php");
  }

$db = new mysqli("localhost", "root", "", "blah");

$result4 = $db->query("select * from k_register where email = '$eml' and password = '$pass'");
  if($result4->fetch_array())

  {

        $auth->createSession();

        $_SESSION['user'] = 'super';

        promptUser("You have successfully logged in!!!","index.php");
  }
  else

  {

        promptUser("Username/Password do not match.  Please try again!!!","");
  }

这个代码很有趣,但我并不是说我错了。我是php和mysql的新手,所以请帮忙。我还为保存数据的所有变量尝试了例如result4->free();,我得到了这个错误:致命错误:在...中的非对象上调用成员函数free() >

3 个答案:

答案 0 :(得分:1)

不要重复自己。你已经创建了你的mysqli对象,所以重用它。例如:

$db = new mysqli("localhost", "root", "", "blah");
$result1 = $db->query("select * from c_register...");
$result2 = $db->query("select * from d_register...");
$result3 = $db->query("select * from e_register...");

这将使您的代码更易读,以后更容易修改。

答案 1 :(得分:0)

mysqli::query()仅在成功查询后返回结果对象。

你需要建立一个支票:

if(($result1 != false) and ($result1->fetch_array()))  // The same for 2,3,4...

您应该使用

获取错误消息
echo $db->error;

答案 2 :(得分:0)

来自PHP手册: mysqli :: query在成功时返回TRUE,在失败时返回FALSE。对于SELECT,SHOW,DESCRIBE或EXPLAIN,mysqli_query()将返回一个结果对象。

所以你应该测试一下:


if ($result != false) {
  ...
} else {
  // print error or whatever
}

顺便说一下。它是非常危险转义变量,如$eml$pass - 如果用户输入$pass类似于: bleh' OR 1 = 1 OR password = 'bleh,然后整个查询将如下所示:

select * from b_register where email = 'some@email.com' and password = 'bleh' OR 1 = 1 OR password = 'bleh'

用户将在不知道密码的情况下登录!

因此,您应该使用:

mysql_real_escape_string($eml)
$pass相同。

甚至更好:使用语句准备和参数绑定 - 请参阅:http://pl2.php.net/manual/en/mysqli.prepare.php