我正在尝试编写一个代码,其中所有 SQL 语句都存储在一个单独的 PHP 文件中,以便以后可以将它们作为函数调用。
我尝试了不同的方法,但似乎无法使其正常工作。
这是我的代码(我正在尝试在这里创建一个登录页面)
登录.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);
它现在正在工作。