关于php类和我的sql问题

时间:2011-07-27 09:42:41

标签: php mysql

感谢。我想让用户登录,我尝试以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()。应该是格式问题吗?但我花了很长时间。感谢。

5 个答案:

答案 0 :(得分:3)

虽然您希望在代码中添加组织是值得称道的,但将方法添加到类中并不会自动使其成为OOP。我建议您阅读基础知识,然后重新组织课程。

至于你的问题,

$result=mysql_query('$this->query','$this->conn') or die( ..
--------------------------^

您传递的那些变量被视为文字字符串,因为您已经引用它们。你需要传递一个实际的查询和一个连接对象。只需删除引号即可。

另外,我建议您研究参数化查询:http://php.net/manual/en/book.pdo.php

修改

进一步查看代码,这些提示可能会改进您的代码

  • 为您的班级使用大写名称。这使它们更容易阅读。
  • 将您的连接移动到其他班级是正确的,但您的使用是错误的。
  • 即使你已经从Connection类扩展了Login类,你也不会在Login类中实例化一个连接对象,即使你在代码中引用它(例如 - $ this-&gt; conn)
  • 实例化您的连接并将其作为其他类的参数传递。不要将它们从连接中伸出。

    $ conn = new Connection($ username,$ pass,$ host,$ db); $ login = new登录($ conn); $ login-&gt; doLogin($ username,$ password);

在您的连接中使用query()方法,因此您可以从其他类中调用该方法。

答案 1 :(得分:0)

$result=mysql_query('$this->query','$this->conn') or die ("Error:" . mysql_error());

这段代码不会评估PHP存储的变量。如果你单引号,PHP将不会尝试解析它,就好像它是一个变量。删除引号。

执行此操作后,您的代码将在connection::conn()失败,因为没有函数mysql_conn。有mysql_connect。它以不同的顺序接受参数(例如,服务器是第一个,而不是第三个参数)。

答案 2 :(得分:0)

尝试:

{$query="SELECT * FROM test WHERE id='".$this->id."' AND '".$this->pwd".';";

答案 3 :(得分:0)

你错过了一些东西;我从所有答案中集体写作

1 - mysql_conn()不是您在function conn() {}中写的功能  2 - 从'中删除$result = mysql_query('$this->query','$this->conn')  3 - 你错过了mysql语句中的一个参数

    $query="SELECT * FROM test WHERE id='$this->id' AND        '$this->pwd';";
                                                         ^ (here)

4 - 在$this->query而不是$query

中分配查询

答案 4 :(得分:0)

您没有将连接对象传递给登录对象,这就是您遇到此错误的原因:警告:mysql_query():提供的参数不是有效的MySQL-Link资源。在登录对象调用$ db的位置,您正在使用登录类中的资源而不启动它们......在您设置它们之前它们不存在。