Jerum Labsan Jerum Labsan - 7 months ago 17
SQL Question

How to choose page using if else in mysql_num_rows

Please help me I want my program to choose a site if it has not yet username then it will proceed it to ch_uname.php. Then if the login credentials have already username then it will be preceded to index_profile.php. Thank you in advance.

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>";
}
}

Answer

Here is a basic demonstration (using a PDO connection) of what I think you are looking for? I am assuming some stuff here because you don't give enough info before your code snippet:

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;
        }
}
Comments