Jump to content

PHP queries not working


kwaabs

Recommended Posts

Hi,

I need some help. I dont really know what is wrong with my code. It seems not to work. The reg.php does not send the data into the database and the log in can not query the database either. I need help. HELP ME PLEASE

<?php 
	require 'database-config.php';

	session_start();

	$username = "";
	$password = "";
	
	if(isset($_POST['username'])){
		$username = $_POST['username'];
	}
	if (isset($_POST['password'])) {
		$password = $_POST['password'];

	}
	
	echo $username ." : ".$password;

	$q = 'SELECT * FROM users WHERE username=:username AND password=:password';

	$query = $dbh->prepare($q);

	$query->execute(array(':username' => $username, ':password' => $password));


	if($query->rowCount() == 0){
		header('Location: index.php?err=1');
	}else{

		$row = $query->fetch(PDO::FETCH_ASSOC);

		session_regenerate_id();
		$_SESSION['sess_user_id'] = $row['id'];
		$_SESSION['sess_username'] = $row['username'];
        $_SESSION['sess_userrole'] = $row['role'];

        echo $_SESSION['sess_userrole'];
		session_write_close();

		if( $_SESSION['sess_userrole'] == "admin"){
			header('Location: adminhome.php');
		}else{
			header('Location: userhome.php');
		}
		
		
	}


?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap 101 Template</title>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    
    <style>
        body
{
    background-color: white;
    padding-top: 40px;
}


.input-group-addon
{
    background-color: rgb(50, 118, 177);
    border-color: rgb(40, 94, 142);
    color: rgb(255, 255, 255);
}
.form-control:focus
{
    background-color: rgb(50, 118, 177);
    border-color: rgb(40, 94, 142);
    color: rgb(255, 255, 255);
}
.form-signup input[type="text"],.form-signup input[type="password"] { border: 1px solid rgb(50, 118, 177); }
    </style>
  </head>
  <body>
      <div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <div class="panel panel-default">
                <div class="panel-body">
                    <form class="form-horizontal" method="POST" action="process_user.php">
<fieldset>

<!-- Form Name -->
<legend>User registration</legend>

<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="user">Username:</label>  
  <div class="col-md-6">
  <input id="user" name="username" type="text" placeholder="" class="form-control input-md" required="">
    
  </div>
</div>

<!-- Password input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="pass">Password:</label>
  <div class="col-md-6">
    <input id="pass" name="password" type="password" placeholder="" class="form-control input-md" required="">
    
  </div>
</div>

<!-- Multiple Radios (inline) -->
<div class="form-group">
  <label class="col-md-4 control-label" for="user_type">User type:</label>
  <div class="col-md-4"> 
    <label class="radio-inline" for="user_type-0">
      <input type="radio" name="user_type" id="user_type-0" value="admin" >
      Admin
    </label> 
    <label class="radio-inline" for="user_type-1">
      <input type="radio" name="user_type" id="user_type-1" value="user">
      User
    </label>
  </div>
</div>

<!-- Button -->
<div class="form-group">
  <label class="col-md-4 control-label" for="submit"></label>
  <div class="col-md-4">
    <button id="submit" name="submit" class="btn btn-primary">Create new user</button>
  </div>
</div>

</fieldset>
</form>

                </div>
        </div>
    </div>
</div>
</div> 
  </body>
</html>
<?php
	require 'database-config.php';
	
	 if(!empty($_POST))
    {
        // Ensure that the user has entered a non-empty username
        if(empty($_POST['username']))
        {
            die("Please enter a username.");
        }
        
        // Ensure that the user has entered a non-empty password
        if(empty($_POST['password']))
        {
            die("Please enter a password.");
        }
        $query = "
            SELECT
                id
            FROM users
            WHERE
                username = :username
        ";
        $query_params = array(
            ':username' => $_POST['username']
        );
        
		try
        {
            // These two statements run the query against your database table.
            $stmt = $dbh->prepare($query);
            $result = $stmt->execute($query_params);
        }
        catch(PDOException $ex)
        {
            die("Failed to run query: " . $ex->getMessage());
        }
        
        $row = $stmt->fetch();
        
        if($row)
        {
            die("This username is already in use");
        }
		
		$query = "
            INSERT INTO users (
                username,
                password,
                salt,
                role
            ) VALUES (
                :username,
                :password,
                :salt,
		:user_type
            )
        ";
        
        $salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
        
        $password = hash('sha256', $_POST['password'] . $salt);
        
        $query_params = array(
            ':username' => $_POST['username'],
            ':password' => $password,
            ':salt' => $salt,
            ':role' => $_POST['user_type']
        );
        
		try
        {
            $stmt = $dbh->prepare($query);
            $result = $stmt->execute($query_params);
        }
        catch(PDOException $ex)
        {
            die("Failed to run query: " . $ex->getMessage());
        }
		
        header("Location: index.php");
     
        die("Redirecting to index");
    }
?>
Link to comment
Share on other sites

It would be very good to know what exactly isn't working, but in the meantime you need to set up error checking on your queries. Don't just blindly assume that the query executed properly. Turn on error reporting and set up some checks on those queries - I'll bet that'll tell you pretty much exactly what's going wrong.

Link to comment
Share on other sites

Your preparing the statement and executing it straight away, You are ment to bind the values and you have not got the result from the query

$q = 'SELECT * FROM users WHERE username=:username AND password=:password';

	$query = $dbh->prepare($q);

	$query->execute(array(':username' => $username, ':password' => $password));


	if($query->rowCount() == 0){
		header('Location: index.php?err=1');

This won't work because you haven't asked for results. You need to read up on Prepared Statements

Also you are vulnerable to cross site scripting (XSS) and SQL Injection.

Edited by Tom10
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.