Eivind Bergman Eivind Bergman - 1 year ago 86
PHP Question

mysqli_num_rows($) doesn't get "colored" in text editor, code doesn't work

I've looked through all questions posted here about mysqli_num_rows. But none seem to have the problem I have. I think I've gotten the code correct, but clearly not since the num_rows doesn't work. I've done my research but I can't find anything that answers my question, so lastly I seek your wisdom Stackoverflow.
Here's my code. As I said the mysqli_num_rows doesn't seem to work.

And i do have mysqli connect

$dbconnect = mysqli_connect($serverName, $userName, $password,$databaseName);


if($_POST) {
$q = "SELECT * FROM User WHERE userName = '$_POST[username]' and
userPass = SHA1('$_POST[password]')";

$r = mysqli_query($dbconnect, $q);

if(mysqli_num_rows($r) == 1) {
$_SESSION['username'] = $_POST['username'];
header('Location: index.php')
<form method="post" action="login.php" role="form">

<div class="form-group">
<label for="text">username</label>
<input type="text" class="form-control" name="username" id="username" placeholder="username">

<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Password">

<button type="submit" class="btn btn-default">Submit</button>

So, what happens is just when i type the username and password i have in my database nothing happens, the page just reloads.

Answer Source

WARNING: This code is still wide open to SQL injections and must not be used in production.

1: Use dot . to join strings with variables or functions

Instead of WHERE userName = '$_POST[username]' use WHERE userName = '".$_POST[username]."'

Instead of and userPass = SHA1('$_POST[password]') use and userPass = ".SHA1($_POST[password])."

2: Use string index for $_POST

Instead of $_POST[username] use $_POST["username"]

Instead of $_POST[password] use $_POST["password"]

3: It is better to use backtick around the column name or table name

Instead of User use `User`

Instead of userName use `userName`

Instead of userPass use `userPass`

So the final solution is to change this:

$q = "SELECT * FROM User WHERE userName = '$_POST[username]' and 
  userPass = SHA1('$_POST[password]')";

to this:

$q = "SELECT * FROM `User` WHERE `userName` = '".$_POST['username']."' and 
  `userPass` = '".SHA1($_POST['password'])."';";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download