谢谢。我想让用户登录,我尝试以 oop 方式进行
这是 loginPage.php
<html>
<body>
<?php require_once("connection.php");
$instance=new connection("527442_1","chi1234a","foodil_zxq_1");
if (isset($_POST['s'])) {
$SecIns=new login($_POST['u'],$_POST['p']);
echo $SecIns->enter();
}
?>
<form name="fm" method="POST" action="show.php">
User Name :<input type="text" name="u">
<br>
Password: <input type="password" name="p">
<br>
<input type="submit" name="s">
</form>
</body>
</html>
这是我失败的 oop 代码 Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource
<?php
class connection
{var $user;
var $pass;
var $db;
function __construct($user,$pass,$db){
$this->user=$user;
$this->pass=$pass;
$this->db=$db;
}
function conn(){
$conn=mysql_connect('localhost' , $this->user , $this->pass) or die ("Can't connect server");
mysql_select_db($this->db,$conn) or die ("DB error");
}
}
class login extends connection
{
function __construct($id,$pwd)
{$this->id=$id;
$this->pwd=$pwd;
}
function enter()
{$this->query="SELECT * FROM test WHERE id='".$this->id."' AND pwd='". $this->pwd."';";
$result=mysql_query($this->query,$this->conn) or die ("Error:" . mysql_error());
if (mysql_num_rows($this->result)<1)
return "Not correct user";
else
return "Login success";
}
}
?>
问题出在function enter()
处,应该是格式问题??但我花了很长时间。谢谢。
最佳答案
虽然您希望将组织添加到代码中是值得称赞的,但将方法添加到类中并不会自动使其成为 OOP。我建议您阅读基础知识,然后重新组织您的类(class)。
至于你的问题,
$result=mysql_query('$this->query','$this->conn') or die( ..
--------------------------^
您传递的那些变量被视为文字字符串,因为您已经引用了它们。您需要向它传递一个实际的查询和一个连接对象。只需删除引号。
此外,我建议您查看参数化查询:http://php.net/manual/en/book.pdo.php
编辑
进一步查看您的代码,这些提示可能会改进您的代码
- 为您的类(class)使用大写名称。这使它们更易于阅读。
- 您将连接移至其他类别是正确的,但您的用法是错误的。
- 即使您从 Connection 类扩展了 Login 类,您也没有实例化连接对象以在 Login 类中使用,即使您在代码中引用它(例如 - $this->conn)
实例化您的连接并将其作为参数传递给您的其他类。不要从连接中扩展它们。
$conn = new Connection($username, $pass, $host, $db); $login = new Login($conn); $login->doLogin($用户名, $密码);
并且在您的连接中有一个query()
方法,因此您可以从其他类中调用该方法。
关于php - 关于 php 类和我的 sql 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6842273/