benpete420 benpete420 - 4 months ago 8
HTML Question

Post function not functioning as expected with database

I am having some problems with this code. I am connecting to an SQL Database and it connects, but the post function doesn't appear to be working. When I inspect element and look at the network connections, it posts one thing, but not the other two things. If someone could help me out, that would be great.

Thanks,

Ben

<?php

$connection = mysql_connect("localhost", "root", "password") or die("There is no connection to the server");
mysql_select_db("tutorial", $connection) or die("Couldn't connect to database");

if ($_POST['login']){
if ($_POST['username'] && $_POST['password']){
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string(hash("sha512", $_POST['password']));
$user = mysql_fetch_array(mysql_query("SELECT * FROM `users` WHERE `Username`='$username'"));
if ($user == '0'){
die("That username does not exist. <a href='index.php'>&larr; Back</a>");
echo "<h1> Test </h1>";
}
if ($user['Password'] != $password) {
die("Incorrect password! <a href='index.php'>&larr; Back</a>");
echo "<h1> Test </h1>";
}
$salt = hash("sha512", rand() . rand() . rand());
setcookie("c_user", hash("sha512", $username), time() + 24 * 60 * 60, "/");
setcookie("c_salt", $salt, time() + 24 * 60 * 60, "/");
$userID = $user['ID'];
mysql_query("UPDATE `users` SET `Salt`='$salt' WHERE `ID`='$userID'");
die("You are now logged in as $username");
}
}

echo "
<body style='font=family: verdana, sans-serif;'>
<div>
<h1>Login to Access Coins</h1>
<br />
<form action='' method='post'>
<table>
<tr>
<td>
<b> Username </b>
</td>
<td>
<input type='text' name='username' style='padding: 6px;' />
</td>
</tr>
<tr>
<td>
<b>Password</b>
</td>
<td>
<input type='password' name='password' style='padding: 6px;' />
</td>
</tr>
<tr>
<td>
<input type='submit' value='Login' />
</td>
</tr>
</table>
</form>
<br />
<h6>
Need an account? <a href='register.php'>Click Here
</h6>
</div>
</body>

";

Answer

Your problem come from the fact you expect $_POST['login'] to be defined, and rely on it to log the user. As login is not defined, you can simply remove (or comment for further use ) :

if ($_POST['login']){

and the corresponding

}

Another way of solving this would be to put :

 <input name="login" type ="hidden" value="">

inside your form for this value can be passed.