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.
Related
I am trying to design a signup page using the code below. Every time I submit the form, it returns with else condition, please guide me where I am wrong.
<?php
session_start();
$localhost= 'localhost';
$username= 'SK';
$password="29336";
$db = "Internship";
$con= mysqli_connect($localhost,$username,$password,$db);
if (isset($_POST['reg_user']))
{
$name= $_POST['name'];
$email= $_POST['email'];
$psd= md5($_POST['psw']);
$confirm_psd= $_POST['confirm_psw'];
if ($psd == $confirm_psd)
{
$query = "INSERT INTO register (name, email, password)
VALUES('.$name.', '$email', '$psd')";
mysqli_query($con, $query);
echo 'inserted';
}
else
{
echo "your password dont match ";
}
}
?>
Important note
If you're using this code for anything requiring real security (i.e. not just a student project) MD5 is not an appropriate hashing algorithm. Read through the OWASP advice to learn how to do this properly.
Answering your question
You have:
$psd= md5($_POST['psw']);
$confirm_psd= $_POST['confirm_psw'];
if ($psd == $confirm_psd)
{
...
which looks like you're comparing the plain text value of confirm_psd with the MD5 hashed value of psw, which obviously won't match.
I'd suggest you either do the comparison before hashing the psw field, like:
$confirm_psd= $_POST['confirm_psw'];
if ($_POST['psw'] == $confirm_psd)
{
$psd= md5($_POST['psw']);
...
Or also hash the confirm_psw value before the comparison like this:
$psd= md5($_POST['psw']);
$confirm_psd= md5($_POST['confirm_psw']);
if ($psd == $confirm_psd)
{
...
and then your comparison should work as you expect.
I am working on a code for my music site. This is part of the registration phase. I want the code to check the database for any existing email addresses, if found, print " email ("email address") already exists, but if not found, then insert the information into the database. The code seems to run if an email address similar to the one submitted from the html form is found, but if there is no email found, the system stops and does nothing after that. Can someone help me figure out where i went wrong.
if ($_POST['submit2']){
$fname = $_POST['Fname'];
$sname = $_POST['Sname'];
$email = $_POST['Emailaddress'];
$pass = $_POST['newpassword'];
$sql= "select * from cust_information where email = '$email';";
$results = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$row = mysqli_fetch_array($results) or die(mysqli_error($conn));
if (count($row) < 0)
{
$sql2 = "insert into cust_information (firstName, lastName, email, password) values(`$fname`, `$sname`, `$email`, `$pass`)";
$results2 = mysqli_query($conn, $sql) or die(mysqli_error($conn));
if (!$results2){
echo "successfully uploaded cust";
}
}else{
echo "email <strong>".$row["email"]. " </strong> already Exist";
}
}
You are checking whether the number of results returned is less than 0. The length of an array (and the number of results found) cannot ever be less than 0. The manual shows that mysqli_fetch_array returns null if no results are found, thus you want to check for $row === null.
However, I will take this opportunity to point out that concatenating variables into a SQL query string leaves you wide open to a serious security concern called SQL Injection. As the code is currently set up, users of the form will be able to run any query they like on your database which is absolutely not what you want. I recommend reading up on prepared statements to mitigate this problem.
( Sorry for my bad english )
I am new to PHP. I have two input fields. One for the username and one for the comment. My problem is when I Reloaded my page that simply blank entries I posted my table. Why is that?
Existing Code :
$username = $_POST['username'];
$comment = $_POST['comment'];
$db = mysqli_connect('localhost','root','','holycms');
if(!db){
exit ("Verbindungsfehler:" . mysqli_connect_error());
}
$eintrag = "INSERT INTO feedback (username, comment) VALUES ('$username', '$comment')";
$result = mysqli_query($db, $eintrag);
Seeing that your code is coming from a POST form, you can use a conditional statement around it.
For example, in your HTML form:
<input type="submit" name="submit" value="Submit" />
then use:
if(isset($_POST['submit'])){
$username = $_POST['username'];
$comment = $_POST['comment'];
$db = mysqli_connect('localhost','root','','holycms');
if(!db){
exit ("Verbindungsfehler:" . mysqli_connect_error());
}
$eintrag = "INSERT INTO feedback (username, comment) VALUES ('$username', '$comment')";
$result = mysqli_query($db, $eintrag);
}
another thing is to make sure that fields are not left empty, using empty() I.e.:
if(empty($_POST['username'])){
echo "Enter a username.";
exit;
}
also isset(). I.e.:
if(isset($_POST['username'])){
// do something
}
You can also use a header("Location: http://www.example.com/page.php");
but make sure there is nothing else above your PHP, echo, HTML, etc.
In regards to your present code:
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements, it's much safer.
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'
I am validating my form using jquery and after the form is left with no errors, I want to insert the data into the database but for some reasons, it is not working properly. Can you help me find out my mistake. Thanks,
The JQuery is
$.post('register_user.php',
{
'name' : name,
'email' : email,
'password': password
},
function(data) {
if(data == "success"){
alert("success");
} else if(data == "fail"){
alert("fail");
}
});
THE PHP
$name = $_POST['name']; //else assign it a variabl
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT email FROM users WHERE LOWER(email) = '" . $email . "'";
$result = mysql_query($sql) or die("Could not get email: " . mysql_error());
if(mysql_num_rows($result) > 0) {
//email is already taken
}
else {
$query = mysql_query("INSERT INTO `users` ( `name`, `email`, `password`) VALUES ( '$name', '$email', '$password')") or die(mysql_error());
$result2 = mysql_result($query);
if((mysql_affected_rows($result2) ==1){
echo 'success';
} else {
echo 'fail';
}
}
I dont have enough rep yet to comment, so I'll have to put this as an answer.
Step 1:
Echo (or print) out what you can.
Add echo inside your logic, like where you have: //email is already taken
Also echo out the POST variables.
If they all look OK, you should try to echo out your queries.
Eg. copy your query line that is like:
$query = mysql_query("INSERT INTO `users` ( `name`, `email`, `password`) VALUES ( '$name', '$email', '$password')")
Then paste it and change it to:
echo "INSERT INTO `users` ( `name`, `email`, `password`) VALUES ( '$name', '$email', '$password')";
Then if this looks bad, it's your query.. You can of course test the output in mysql directly via phpmyadmin or ssh to your server and run the commands through the console (if they give you shell access)
If you manage to get this to work, as some others commented: mysqli or pdo should be your next steps. You also need to do some basic stuff, even though that will take care of mysql injection.
You are still vunerable to XSS and also simply things like whitespace at the end of the email (users often get this, when they copy stuff and insert it into forms).
You can solve some of it by some helper functions you make in PHP, like:
function cleanData($data) {
return strip_tags(trim($data));
}
That was a very simple sample by me, you can also add other parameters to the function, like casing. Then you can switch the casing and do strtolower, strtoupper, ucwords(strtolower(, etc. And you can then simply wrap your variables inside the function :-)
Btw. E-Mail I would check with regular expressions. Also dont let JS / client side code do the input validation, as it's very easy to manipulate the DOM, or even post from an alternative source. You have to think of this data as "dirty", as it's easy to tamper with.