我是类和对象的新手。我在class.atp中为mysql数据库连接编写了一些代码。在index.php我有这段代码:
<?php
try {
require_once('./lib/testdb.php');
$login = new Login();
}
catch(Exception $error) {
print $error->getMessage();
}
/* Include the HTML for the form */
require_once('./lib/form.php');
?>
和testdb.php我有这个代码:
<?php
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "root");
class Login{
private $username;
private $password;
public function getUsername() {
return $this->username;
}
public function getPassword() {
return $this->password;
}
public function getEncryptedPassword() {
return sha1($this->password);
}
public function connectToMySQL() {
@mysql_connect(DB_HOST, DB_USER, DB_PASS) OR die("Cannot connect to MySQL server!");
mysql_select_db("dd") OR die("Cannot select database!");
}
public function verifyLogin($username, $password) {
$this->username = $username;
if(empty($username) || empty($password)) {
throw new Exception(Login::ERROR_EMPTY_LOGIN);
}
else {
$query = sprintf("SELECT * FROM 'users' WHERE username = '%s' AND
userpass = sha1('%s') ");
$this->clean($username),
$this->clean($password));
$result = mysql_query($query) OR die('Cannot perform query!');
while($info = mysql_fetch_array( $result ))
{
echo $info['username'];
}
}
?>
数据库部分是这样的:
--
-- Database: `login`
--
-- --------------------------------------------------------
--
-- Table structure for table `login`
--
CREATE TABLE IF NOT EXISTS `login` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(80) NOT NULL,
`password` varchar(80) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `login`
--
INSERT INTO `login` (`id`, `username`, `password`) VALUES
(1, 'ajay', 'password');
问题是它没有从数据库中获取任何数据,也没有显示“无法执行查询”。所以请指导我。这是我在课堂和对象中的第一个项目。
答案 0 :(得分:1)
您的sprintf
声明中有错误:
$query = sprintf("SELECT * FROM 'users' WHERE username = '%s' AND
userpass = sha1('%s') "); // here
$this->clean($username),
$this->clean($password));
应该是:
$query = sprintf("SELECT * FROM 'users' WHERE username = '%s' AND
userpass = sha1('%s') ", // corrected
$this->clean($username),
$this->clean($password));
由于该错误,您不会在查询中添加用户名和密码。
答案 1 :(得分:0)
使用mysql_error()
找出真正的问题所在。
$result = mysql_query($query) OR die('Cannot perform query: ' . mysql_error());
答案 2 :(得分:0)
必须使用括号构造类:new Login();
而不是new Login;
:
<?php
try {
require_once('./lib/testdb.php');
$login = new Login();
}
答案 3 :(得分:0)
保留一些理智和工作效率,并开始查看mysql日志文件中的最后一行,以了解这些简单错误。
或者,为了暂时识别问题是什么
echo $query;