如何在mysql_num_rows中使用if else选择页面

时间:2015-01-30 07:18:30

标签: php mysql if-statement mysql-num-rows

请帮助我,如果网站尚未用户名,我希望我的程序选择一个网站,然后将其转到 ch_uname.php 。然后,如果登录凭据已经用户名,那么它将在 index_profile.php 之前。提前谢谢。

if(mysql_num_rows($runcreds)> 0 ) //checking log in forms
{
    if(mysql_num_rows($run_uname)>=1 ) //if username has already avalaible(proceed)
    {
        $_SESSION['Email_add']=$email;
        echo "<script>window.open('modules/index_profile.php','_self')</script>";
    }
    if(mysql_num_rows($run_uname)<1)//choouse username if has not yet username
    {
        $_SESSION['Email_add']=$email;
        echo "<script>window.open('forms/ch_uname.php','_self')</script>";
        //modules/index_profile.php
    }
}
else
{
    echo "<script>alert('Admin details are incorrect!')</script>";
}
}

1 个答案:

答案 0 :(得分:1)

以下是您正在寻找的我认为的基本演示(使用PDO连接)?我在这里假设一些东西,因为你没有在你的代码片段之前提供足够的信息:

session_start();
// I will use PDO because I cannot bring myself to use mysql_ in this demonstration
// Initiate connection (assigning credentials assumed)
$con =  new PDO("mysql:host=$mysqlDB;dbname=$mysqlTable", $mysqlUser, $mysqlPass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT));

if(isset($_POST['login'])) {
    $username = trim($_POST['username']);
    // Stop if empty
    if(empty($username)) {
            // You can echo or assign to a variable to echo down the page
            echo 'Username cannot be empty';
            return;
        }
    // Set up prepared statement
    $query = $con->prepare("select Email_add,password from `users` where username = :username");
    $query->execute(array(":username"=>$username));
    // Loop through returned
    while($row = $query->fetch(PDO::FETCH_ASSOC)) {
            $result[] = $row;
        }
    // If the loop comes up blank, assign false (0)        
    $result = (isset($result) && !empty($result))? $result:0;
    // If username exists
    if($result != 0) {
            // I am assuming you have some form of super secure hash method for passwords...
            $password = bcrypt($_POST['password']);
            // If passwords match, create session
            if($result[0]['password'] == $password) {
                    $_SESSION['Email_add'] = $result[0]['Email_add'];
                    // You probably don't need javascript to redirect
                    header('Location: modules/index_profile.php');
                    exit;
                }
            else {
                    // Password doesn't match
                    // You can echo or assign to a variable to echo down the page
                    echo 'Invalid Username/Password';
                }

        }
    // This would mean the username doesn't exist
    else {
            header('Location: forms/ch_uname.php');
            exit;
        }
}