I have a program that moves registration data from one datatable to another (think login activation page from temp to permanent after email confirmation). I'm not the best at Mysql yet, still learning so it might be a stupid question. I've checked all over stackoverflow and it looks like I'm doing it correctly.
For some reason my select call is not working. Here is a bit of my code:
$username = mysqli_query($dbc,"SELECT 'username' FROM 'temp_users' WHERE 'activation'= '$key'");
$password = mysqli_query($dbc,"SELECT 'password' FROM 'temp_users' WHERE 'activation'= '$key'");
// Add row to database
mysqli_query($dbc,"INSERT INTO users (username, password, salt', 'email') VALUES ('$username', '$password_hash', '$salt', '$email')");
echo $username, $password, $email, mysqli_affected_rows($dbc), $key;
// Print a customized message:
if (mysqli_affected_rows($dbc) == 1) //if update query was successfull
{
echo '<div>Your account is now active. You may now Log in</div>';
} else {
echo '<div>Oops !Your account could not be activated. Please recheck the link or contact the system administrator.</div>';
}
I threw in the echo my variables so I could see what was going on. At this point, $key is correct, $email is correct from earlier code, mysqli_affected_rows($dbc) is giving me a -1 (which means error). $username and $password are blank variables, so clearly I am doing the SELECT incorrectly.
Any thoughts or help?
Remove '(Single quotes) use (backticks) = ``
SELECT `username` FROM `temp_users` WHERE `activation`= '$key'
Related
I made a signin form that will look through the database and find a match to the user's credentials, but how do I fix this code so it will relocate the page if there is no match.
<?php
session_start();
include_once 'includes/dbh.php';
$username = $_POST['u_name'];
$password = $_POST['pwd'];
$sql = "SELECT * FROM users;";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
if ($username == $row['username'] && $password == $row['password']) {
$_SESSION['username'] = $username;
header("Location: second_index.php?signinSuccessful");
}
if ($username != $row['username'] && $password != $row['password']) {
header("Location: index.php?NotSucessful");
}
}
I tried putting the code inside of the loop, but I know that can't work, and if I put it outside of the loop, It redirects even if the credentials are correct. Please help. Thanks
First of all, this is totally wrong, you're looping trough all the users to see if the user exist, instead of that sql statement try $sql = "SELECT * FROM users where user='$user' and password='$password'";
And to avoid any data breach in that sql statemen you have to serialize the user and pass like that before adding it to the statement
$user = mysql_real_escape_string($conn, $user);
$password =mysql_real_escape_string($conn, $password);
Then you only check if the fields aren't empty (which means the user exist)
You are getting all the users from the users table and checking each record manually in php.
The reason why your code doesn't work is because the while loop doesn't check all the users in user table. If the first record in the retrieved table data doesn't match with entered username and password, it will go to 2nd if block and redirect.
You should change your query to filter by user-entered values.
SELECT * FROM USERS WHERE USERNAME = 'username' AND PASSWORD='password'
And later check in php if any record is returned. If any record is returned, it is a valid user, else redirect the user to failed authentication page.
As a good practice, make sure to use parameterized query.
Update Replace the while loop and block with this.
if(mysqli_num_rows($result) > 0){
// valid user
}else{
// invalid user
}
Why do you need while loop in this case when you fetching data from database? Using sql and make the database fetch the only one correct answer, don't make server site do unnecessary work.
I propose just do simple fetch then if check, no need for while loop at all.
Your logic is always redirect to index.php when username password not correct so of course it will always do so when your while loop on server do not hit the correct user.
I have this script on my site:
<?php
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if($db_found) {
$SQL = "INSERT INTO users (user, address)
VALUES('".$_GET['username']."','".$_GET['password']."')";
$result = mysql_query($SQL);
mysql_close($db_handle);
print "Records added to the database";
}
else {
print "Database NOT found";
mysql_close($db_handle);
}
?>
I then open this url in my browser:
http://ringkapps.altervista.org/addToDatabase.php?user=ringk&address=test
But instead of inserting "ringk" and "test" in the table, it inserts this:
Can't understand why, any help would be greatly appreciated.
This code is wrong!
$SQL = "INSERT INTO users (user, address)
VALUES('".$_GET['username']."','".$_GET['password']."')";
Replace this.
$SQL = "INSERT INTO users (user, address)
VALUES('".$_GET['user']."','".$_GET['address']."')";
It's not working because you're calling
http://ringkapps.altervista.org/addToDatabase.php?user=ringk&address=test
Which creates $_GET["user"] and $_GET["address"] but you are trying to put in the db $_GET['username'] and $_GET['password'] which don't exist.
You should call:
http://ringkapps.altervista.org/addToDatabase.php?username=ringk&password=test
Plus, read something on security for PHP apps, your code is prone to a lot of vulnerabilities!!!
In the url : http://ringkapps.altervista.org/addToDatabase.php?user=ringk&address=test
We can see user = ringk and address = test.
Where user is the key and ringk it's value.
Where address is the key and test it's value.
You can print all the $_GET value by using var_dump($_GET) and see by yourself what's in it.
My guess is that what you want is to access
$_GET['user'] and $_GET['address']
then just replace the line :
VALUES('".$_GET['username']."','".$_GET['password']."')";
with
VALUES('".$_GET['user']."','".$_GET['address']."')";
or you could update the url to match the code.
I am creating a sign up page.
My code was working perfectly before on an intranet, but now, 5 years later I must use MySQL i.
What happens is I connect to the database using external PHP file, dblogin.php
<?php
$connection = mysqli_connect('mywebhost','username','password','db');
?>
That bit works fine, as the login system works using this.
Then comes my registration system.
It has been a while since I coded in PHP, mostly working using Wordpress now.
<?php
include 'dblogin.php';
if(isset($_GET['i'])){
if($_GET['i'] == '1'){ //if we want to insert a new user
$tblName="tblUsers";
//Form Values into store
$FirstName=$_POST['firstnamecreate'];
$Surname=$_POST['Surnamecreate'];
$Username=$_POST['UsernameCreate'];
$UserType="stu"; //never mind this, it just seperates admins from standard users
$Email=$_POST['EmailCreate'];
$Password=$_POST['PasswordCreate'];
$ExistingUserVerification = mysqli_query ($connection,"SELECT COUNT(*) as num FROM tblUsers WHERE UserName = $Username");
$UserResults = mysqli_query($connection,$ExistingUserVerification);
if($UserResults[0] == 1){
$CreatedStatus = "$Username already exists in the user database. Please choose a different Username.";
}else{
$sql="INSERT INTO $tblName(UserName, Password, UserType, FirstName, Surname, EmailAddress)VALUES('$Username', '$Password', '$UserType', '$FirstName', '$Surname', '$Email')";
$result=mysqli_query($connection,$sql);
if($result){
$CreatedStatus = "$FirstName, you have registered successfully. Click " . "<a href=Login.php>". "HERE". "</a>" . " to login. " . "<br />"."Please note: Hacking of this site is not permitted.";
}
else {
$CreatedStatus = "Unfortunately $Username was not created successfully. Please check your entry or check whether the user already exists.";
}
}
}
}
?>
The problem i am getting is around the
$ExistingUserVerification = mysqli_query ($connection,"SELECT COUNT(*) as num FROM tblUsers WHERE UserName = $Username");
$UserResults = mysqli_query($connection,$ExistingUserVerification);
part.
I have tried all sorts. With the current format, it results in:
Warning: mysqli_query(): Empty query in /home/trainman/public_html/Register.php on line 26
removing $connection results in it expecting 2 parameters and removing i says depricated.
Any help much appriciated. It has been a while since I last used php so sorry if the code is untidy. The select COUNT (*) checks if there is another user with the same username, if there isnt it will submit form values to the DB
This error is coming from the extremely simple fact that you are sending an empty query to mysqli. The query is empty. It's but an empty string. Nothing.
So just check your variables.
The second parameter to mysqli_query() should be a PHP string contains a legitimate SQL query. Anything else will cause an error.
I am very new to PHP and Mysql. I have made a registeration form but the values being inputted are not being saved in my database. I don't know why. I am connected to the database. Could anyone give me some insight? By the way, I know you are going to say "Mysql" is deprecated. But I am just starting out and learning how all of this works. As soon as I have a thorough understanding of the processes I am going to change my code to Mysqli...
<?php
//form data
$submit = strip_tags($_POST['submit']);
$fname = strip_tags($_POST['fname']);
$lname = strip_tags($_POST['lname']);
$usernamereg = strip_tags($_POST['usernamereg']);
$passwordreg = strip_tags($_POST['passwordreg']);
$email = strip_tags($_POST['email']);
$emailcheck = strip_tags($_POST['emailcheck']);
$date = date("Y-m-d");
if($submit)
{
//check for existence
if($fname&&$lname&&$usernamereg&&$passwordreg&&$email&&$emailcheck)
{
//encrypt password
$password = md5($passwordreg);
if(strlen($usernamereg)>25)
{
echo "Username must be 25 characters or less.";
}
else
{
//checks password length
if(strlen($passwordreg)<6)
{
echo "Passwords must be atleast 6 characters long";
}
else
{
if($email!=$emailcheck)
{
echo "emails to not match";
}
else
{
//open database
$connect = mysql_connect("localhost","root","clandestine");
mysql_select_db("user_db"); //selects database
$queryreg = mysql_query("INSERT INTO users VALUES('','$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck'");
echo "You have been registered!";
}
}
}
}
else
echo "Please fill in <b>all</b> fields!";
Try assigning the columns in the INSERT query.
$queryreg = mysql_query("INSERT INTO users (`randomField`, `date`, `first_name`, `last_name`, `username`, `password`, `email`, `email_check`) VALUES ('','$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck'");
What is the first column supposed to be?
Have you done any sanity checking? (ie, printing test data to the screen at certain points in the code to make sure your IF statements are evaluating to true?
Additionally, try saving your INSERT query as a variable string:
$query = "INSERT INTO.............";
and then printing it to the screen. Copy and paste that query into PHPMyAdmin (if you have access to it) and see if there are any errors with your statement. PMA will tell you what errors there are, if any.
EDIT: Also, please don't ever MD5 a password or other highly sensitive data. Use a secure algorithm and salt the password. If you're unsure of what this all means:
refer to this link
What do you get if you do:
$query = "INSERT INTO users
(date, first_name, last_name, username, password, email, email_check)
VALUES
('$date','$fname','$lname','$usernamereg','$passwordreg','$email','$emailcheck')";
mysql_query($query)or die('Error: <br />'.$query.'<br />'.mysql_error());
Note the removal of the backticks was just to simplify the code. It's correct to leave them in but with no spaces etc in your column names it should work anyway. Oh, and this is NOT good practice for production, of course. Just really clear debug.
How can I ensure my login script is secure and make it better, This is my first code:
Help is most appreciated.
<?php
include ('../includes/db_connect.php');
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$username = $_POST['username'];
$password = md5($_POST['password']);
// lets check to see if the username already exists
$checkuser = mysql_query("SELECT username FROM users WHERE username='$username'");
$username_exist = mysql_num_rows($checkuser);
if($username_exist > 0){
echo "I'm sorry but the username you specified has already been taken. Please pick another one.";
unset($username);
header("Location: /registration?registration=false");
exit();
}
// lf no errors present with the username
// use a query to insert the data into the database.
$query = "INSERT INTO users (firstname, lastname, email, mobile, username, password)
VALUES('$firstname', '$lastname','$email', '$mobile','$username', '$password')";
mysql_query($query) or die(mysql_error());
mysql_close();
echo "You have successfully Registered";
header("Location: /registration?registration=true");
// mail user their information
//$yoursite = ‘www.blahblah.com’;
//$webmaster = ‘yourname’;
//$youremail = ‘youremail’;
//
//$subject = "You have successfully registered at $yoursite...";
//$message = "Dear $firstname, you are now registered at our web site.
// To login, simply go to our web page and enter in the following details in the login form:
// Username: $username
// Password: $password
//
// Please print this information out and store it for future reference.
//
// Thanks,
// $webmaster";
//
//mail($email, $subject, $message, "From: $yoursite <$youremail>\nX-Mailer:PHP/" . phpversion());
//
//echo "Your information has been mailed to your email address.";
?>
Follow Artefacto's advice about SQL injection and Hashing passwords in the database. Other things ...
echo "I'm sorry but the username you specified has already been taken. Please pick another one.";
unset($username);
header("Location: /registration?registration=false");
Wont work because you can't echo then send a header. Headers must be sent before any output.
Also, there is no point doing this:
header("Location: /registration?registration=false");
echo "I'm sorry but the username you specified has already been taken. Please pick another one.";
unset($username);
The webbrowser will redirect straight away and the user won't see the handy message you've printed.
Also, it's usual to ask for 2 password fields on registration forms incase the user made a typo and didn't notice because all the text was *'s. You compare the 2 and if they are different you assume a typo was made and ask again.
That's not a login script. It's a registration script.
See SQL injection in the PHP manual. Your program is vulnerable to this kind of attacks.
Also, don't just or die(mysql_error()). This will expose information about your database that you may not want to expose (table names, etc.). Use proper error handling. For instance, you can throw an exception and define a uncaught exception handler that shows a "oops" page and logs the error.
Finally, use hashes strong than MD5, such as sha1.
As said by #Artefacto, that's not a login script.
But if you intend to do a login script I would like to give you a suggestion. I've done this a while ago.
Instead of doing something like this:
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
I would do this:
$sql = "SELECT * FROM users WHERE username = '$username'";
$user = //use the php-sql (query, fetch_row) commands to fetch the user row.
if (strcmp($user['password'], $password) == 0) {
//log in success
}
By doing this, you avoid SQL Injection in a simple and elegant way. What you guys think about it?
To reiterate what everyone else mentioned. It's important to protect yourself (and sever) from SQL injection. For example:
$checkuser = mysql_query("SELECT username FROM users WHERE username='$username'");
You're just simple taking the value from $_POST['username'] and placing it in the variable $username.
Some people aren't very nice and will try to break your program :( So it's always recommended to escape any data that was taken from a user, before placing it into an SQL query.
For instance...
This:
$checkuser = mysql_query("SELECT username FROM users WHERE username='$username'");
Becomes:
$checkuser = mysql_query("SELECT username FROM users WHERE username='" .mysql_real_escape_string($username). "'");