试图将代码从MySQL转换为MySQLi

时间:2015-04-25 18:08:11

标签: php mysql mysqli

最近我开始使用这里的旧脚本: http://tutorial.ninja/tutorials/Web+Development/PHP+-+User+System/58/User+System+%28Part+1%29/page-2.html

我一直在尝试将配置编辑为MySQLi而不是MySQL,但我正在努力。我改变了这一切:

$conn = mysql_connect("localhost","USER","PASSWORD");  // Connect to local MySQL database with username and password
mysql_select_db("DBNAME") or die(mysql_error()); //Select which database to use

// Query database for account details if they exist and store them in the $logged variable
$logged = mysql_fetch_array(mysql_query("SELECT * FROM `members` WHERE `id` = '".$_SESSION['id']."' AND `password` = '".$_SESSION['password']."'")); 

到此:

$conn = mysqli_connect("localhost","root","root", "viozaki");  // Connect to local MySQL database with username and password



// Query database for account details if they exist and store them in the $logged variable


 $logged = mysqli_query("SELECT * FROM users WHERE username='".$_SESSION['username']."' AND password = '".$_SESSION['password']."'");
$logged = mysqli_fetch_array($logged);

我搜索的大部分内容。我了解到MySQL连接现在都可以通过包含数据库名称而不必执行select_db来完成。我对此没有任何问题,但下一行是最令人困惑的。无论我改变什么,我总是会遇到这些错误:

Warning: mysqli_query() expects at least 2 parameters, 1 given in config.php

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in config.php

这是为什么?我认为我改变它的调整将适用它,但似乎我无法摆脱这些错误。非常奇怪。

1 个答案:

答案 0 :(得分:4)

简单:您需要将数据库连接传递给查询

$logged = mysqli_query($conn, "SELECT ...

阅读手册:

我也注意到你也在使用会话,所以请确保你已经开始使用。

session_start();必须驻留在使用会话的所有文件中,如果它尚未包含在内。

我注意到您可能以纯文本格式存储密码。如果是这种情况,则非常气馁。

我建议您使用CRYPT_BLOWFISH或PHP 5.5的password_hash()功能。对于PHP< 5.5使用password_hash() compatibility pack

  • 另外,在会话中存储密码是一个好主意,可能成为会话劫持的牺牲品。

阅读有关主题的内容: