我正在尝试编写一个代码,其中所有SQL语句都存储在一个单独的PHP文件中,以便以后可以将它们作为函数来调用。
我尝试了不同的方法,但似乎无法使其正常工作。
这是我的代码(我正在尝试在此处创建登录页面)
login.php
<?php include('sql.php'); $sql = new sql(); ?> <form class = "form-inline" method = "post" style="color: #FFF; position: absolute; margin-top:100px; margin-left:500px;"> <table width="100%" border="0"> <tr> <td>Username</td> <td><input type="text" id = "username" name = "username" class="large" placeholder=""></td> </tr> <tr> <td>Password</td> <td><input type="password" id = "password" name = "password" class="large" placeholder=""></td> </tr> </table> <br /> <center><button type="submit" id = "submit" name = "submit" class="btn btn-primary">Log in</button></center> </form> <?php //echo $sql->admin(); ?> <?php if(isset($_POST['submit'])) { // username and password sent from form $username=$_POST['username']; $password=$_POST['password']; // To protect MySQL injection (more detail about MySQL injection) $username = stripslashes($username); $password = stripslashes($password); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); //THIS IS THE PART WHERE I CALL THE SQL STATEMENT FROM A SEPARATE PHP FILE echo $sql->admin($username,$password); // Mysql_num_row is counting table row $count=mysql_num_rows($sql); // If result matched $username and $password, table row must be 1 row if($count==1) { //unset($_SESSION); $row = mysql_fetch_assoc($sql); $_SESSION[logged] = $row[logged]; // Register $username, $password and redirect to file "index.php" $_SESSION['username'] = $username; $_SESSION['password'] = $password; $_SESSION['submitted'] = $row[submitted]; $_SESSION['date_submitted'] = $row[date_submitted]; session_register($_SESSION['username']); session_register($_SESSION['password']); ?> <script>window.location="index.php";</script> <?php } else { ?> <center><span style="color:white;">Wrong Username or Password</span></center> <?php } } ?>
sql.php
<?php include('connect.php'); class sql{ function sql() { } function admin($username,$password) { echo $sql=mysql_query("SELECT * FROM admin WHERE admin_username= '$username' and admin_password= '$password' "); } } ?>
此代码出现的错误是
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in login.php on line 40
我的40号线是
$count=mysql_num_rows($sql);
我终于明白了 如您所说,我在sql.php中添加了一行
return $result;
我的代码无法正常工作的另一个原因是,我没有放置自己的代码
$sql->admin($username,$password);
里面的一个变量。现在看起来像这样
$a = $result->admin($username,$password);
现在正在工作。
您应该在函数中返回结果集
function admin($username,$password) { $result=mysql_query("SELECT * FROM admin WHERE admin_username= '$username' and admin_password= '$password' "); return $result; // return result set back }