PHP not writing in MySQL database - php

I have an HTML page with input fields where I'm using PHP to validate and eventually write into my MySQL Database called 'fantasymock'. If validation is successful, the user is directed to an empty page called thankyou.php (using for testing purposes), which I am being directed to. But unfortunately, the data is not being written into the database.
I've looked on the web and previous SO posts and don't see a similar situation likes mines. Can someone look at it and possibly find the issue? Code is somewhat long and apologize. Thank you.
<?php
// define variables and set to empty values
$emailErr = $userErr = $passwordErr = $cpasswordErr = $firstErr = $lastErr = $teamErr = "";
$userid = $email = $username = $password = $cpassword = $firstname = $lastname = $teamname = "";
// The preg_match() function searches a string for pattern, returning true if the pattern exists, and false otherwise.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//Validates email
if (empty($_POST["email"])) {
$email = NULL;
$emailErr = "You Forgot to Enter Your Email!";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)) {
$email = NULL;
$emailErr = "You Entered An Invalid Email Format";
}
}
//Validates Username
if (empty($_POST["username"])) {
$username = NULL;
$userErr = "You Forgot to Enter Your Username!";
} else {
$username = test_input($_POST["username"]);
}
//Validates password & confirm passwords.
if (empty($_POST["cpassword"])) {
$password = NULL;
$cpassword = NULL;
$passwordErr = "You Forgot To Enter Your Password!";
}
if(!empty($_POST["password"]) && ($_POST["password"] == $_POST["cpassword"])) {
$password = test_input($_POST["password"]);
$cpassword = test_input($_POST["cpassword"]);
if (strlen($_POST["password"]) < '7') {
$password = NULL;
$passwordErr = "Your Password Must Contain At Least 8 Characters!";
}
elseif(!preg_match("#[0-9]+#",$password)) {
$password = NULL;
$passwordErr = "Your Password Must Contain At Least 1 Number!";
}
elseif(!preg_match("#[A-Z]+#",$password)) {
$password = NULL;
$passwordErr = "Your Password Must Contain At Least 1 Capital Letter!";
}
elseif(!preg_match("#[a-z]+#",$password)) {
$password = NULL;
$passwordErr = "Your Password Must Contain At Least 1 Lowercase Letter!";
}
}
elseif(!empty($_POST["password"])) {
$password = NULL;
$cpassword = NULL;
$passwordErr = "Please Check You've Entered Or Confirmed Your Password Correctly!";
}
//Validates firstname
if (empty($_POST["firstname"])) {
$firstname = NULL;
$firstErr = "You Forgot to Enter Your First Name!";
} else {
$firstname = test_input($_POST["firstname"]);
//Checks if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
$firstname = NULL;
$firstErr = "You Can Only Use Letters And Whitespaces!";
}
}
if (empty($_POST["lastname"])) {
$lastname = NULL;
$lastErr = "You Forgot to Enter Your Last Name!";
} else {
$lastname = test_input($_POST["lastname"]);
//Checks if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastname)) {
$lastname = NULL;
$lastErr = "You Can Only Use Letters And Whitespaces!";
}
}
if (empty($_POST["teamname"])) {
$teamname = NULL;
$teamErr = "You Forgot to Enter Your Team Name!";
} else {
$teamname = test_input($_POST["teamname"]);
}
if ($email && $username && $password && $cpassword && $firstname && $lastname && $teamname) {
mysql_connect("localhost", "root", "");
#mysql_select_db("fantasymock") or die("Unable To Connect To the Database");
//Variable used for the primary key in User Table in Database.
$userid = $_POST['userid'];
$email = $_POST['email'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$teamname = $_POST['teamname'];
$query = "INSERT INTO user VALUES ('$userid', '$email', '$password', '$cpassword', '$firstname', '$lastname', '$teamname')";
mysql_query($query);
mysql_close();
header("Location: thankyou.php");
die();
} else {
echo '<p align="center"><strong>Errors on page</strong><br><br></p>';
}
}
/*Each $_POST variable with be checked by the function*/
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!--The htmlspecial() function prevents from hackers inserting specific characters in fields with malicious intent-->
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table align="center" border="1" bordercolor="black" bgcolor="white" cellpadding="5" cellspacing="0" width="50%">
<tr>
<td>
<table align="center" bordercolor="white" border="0" cellpadding="5" cellspacing="0">
<tr>
<td align="center" colspan="2"><strong>Registration</strong></b></td>
</tr>
<tr>
<td colspan="2"><br></td>
</tr>
<tr>
<td align="right" width="20%">E-mail:</td>
<td align="left" width="30%"><input class="largeTextBox" type="text" name="email" maxlength="50" size="30" placeholder=" email" value="<?php echo $email;?>"</td>
</tr>
<tr>
<td colspan="2" align="center"><span class="error"><?php echo $emailErr;?></td>
</tr>
<tr>
<td align="right" width="20%">Username:</td>
<td align="left" width="30%"><input class="largeTextBox" type="text" name="username" maxlength="50" size="30" placeholder=" username" value="<?php echo $username;?>"></td>
</tr>
<tr>
<td colspan="2" align="center"><span class="error"><?php echo $userErr;?></td>
</tr>
<tr>
<td align="right" width="20%">Password:</td>
<td align="left" width="30%"><input class="largeTextBox" type="password" name="password" maxlength="50" size="30" placeholder=" password" value="<?php echo $password;?>"></td>
</tr>
<tr>
<td colspan="2" align="center"><span class="error"><?php echo $passwordErr;?></td>
</tr>
<tr>
<td align="right" width="20%">Confirm Password:</td>
<td align="left" width="30%"><input class="largeTextBox" type="password" name="cpassword" maxlength="50" size="30" placeholder=" confirm password" value="<?php echo $cpassword;?>"></td>
</tr>
<tr>
<td colspan="2" align="center"><span class="error"><?php echo $cpasswordErr;?></td>
</tr>
<tr>
<td align="right" width="20%">First Name:</td>
<td align="left" width="30%"><input class="largeTextBox" type="text" name="firstname" maxlength="50" size="30" placeholder=" first name" value="<?php echo $firstname;?>"></td>
</tr>
<tr>
<td colspan="2" align="center"><span class="error"><?php echo $firstErr;?></td>
</tr>
<tr>
<td align="right" width="20%">Last Name:</td>
<td align="left"><input class="largeTextBox" type="text" name="lastname" maxlength="50" size="30" placeholder=" last name" value="<?php echo $lastname;?>"></td>
</tr>
<tr>
<td colspan="2" align="center"><span class="error"><?php echo $lastErr;?></td>
</tr>
<tr>
<td align="right" width="20%">Team Name:</td>
<td align="left" width="30%"><input class="largeTextBox" type="text" name="teamname" maxlength="50" size="30" placeholder=" team name" value="<?php echo $teamname;?>"></td>
</tr>
<tr>
<td colspan="2" align="center"><span class="error"><?php echo $teamErr;?></td>
</tr>
<tr>
<td colspan="2" align="center"><hr/></td>
</tr>
<tr>
<td colspan="2" align="center"><input class="bigButton" type="submit" name="submit" value="Submit"></td>
</tr>
</table>
</td>
</tr>
</table>
</form>

You should check if your query was succesfull or not. if not show the error.
if (!mysql_query($query))
{
die('Invalid query: ' . mysql_error());
}
And in your database, are all the columns strings(varchar) or are there also integers because if so you wont succeed .
like this
$userid = $_POST['userid'];
i assume userid is a integer but you just assign it from post to var this var will be a string.
in order to get a integer you should something like this
$userid = $_POST['userid'];
$userid+=0;
And if your primary key is set to auto-increment you should not insert anything to that column. It will be done automaticlally

This probably won't solve the problem you're having but hopefully it helps.
try the query as
"INSERT INTO user (`email`,`password`,`cpassword`,`firstname`,`lastname`,`teamname`)VALUES
('$email', '$password', '$cpassword', '$firstname', '$lastname', '$teamname')"
let the db driver handle assigning the id using auto increment.
You should also be aware you have some nasty sql injection vulnerabilities

I noticed you aren't handling MySQL errors. After you call a query, you should always have some kind of error checking. For mysql you should use mysql_error. For example:
$query = "INSERT INTO user VALUES ('$userid', '$email', '$password', '$cpassword', '$firstname', '$lastname', '$teamname')";
mysql_query($query);
echo mysql_errno($link) . ": " . mysql_error($link). "\n";
That should tell you your error.

Related

Problem showing a variable from 1 .php to another one

So, I have a problem when trying to modify only 1 user columns data in the database. The code I`ve made will only modify the data of the last user in the database and not the current user.
For example: I am logged on Asd account with the columns:
email username nume prenume tara
if i edit it,it will show the values on this one in the database but it will not show them on screen
if i have more users like asd abc abcd
it will show the values of abcd
<?php include('server.php');
$result = mysqli_query($db,"SELECT * FROM users");
while($row = mysqli_fetch_array($result))
{
if($username=$row['username'])
{
$email=$row['email'];
$user=$row['username'];
$nume=$row['nume'];
$prenume=$row['prenume'];
$tara=$row['tara'];
$oras=$row['oras'];
$adresa=$row['adresa'];
$numar=$row['numar'];
}
}
?>
<form method="post" action="editprofil.php">
<table class="table-fill">
<thead>
<tr>
<th class="text-left" style="font-size:32px;padding-bottom:1em;" >Profil</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-left">Username</td>
<td class="text-left"><?php echo $user ?></td>
</tr>
<tr>
<td class="text-left">Nume</td>
<td class="text-left"><input type="text" name="nume" /></td>
</tr>
<tr>
<td class="text-left">Prenume</td>
<td class="text-left"><input type="text" name="prenume" /></td>
</tr>
<tr>
<td class="text-left" >Email </td>
<td class="text-left"> <?php echo $email; ?></td>
</tr>
<tr>
<td class="text-left">Tara</td>
<td class="text-left"><input type="text" name="tara" /></td>
</tr>
<tr>
<td class="text-left">Oras</td>
<td class="text-left"><input type="text" name="oras" /></td>
</tr>
<tr>
<td class="text-left">Adresa</td>
<td class="text-left"><input type="text" name="adresa"/></td>
</tr>
<tr>
<td class="text-left">Telefon mobil</td>
<td class="text-left"><input type="text" name="telefon" /></td>
</tr>
<tr>
<td class="text-left">Data nasterii</td>
<td class="text-left"><input type="text" name="varsta" /></td>
</tr>
</tbody>
</table>
<div class="input-container"style="padding-top:1em;">
<input type="username" name="username" id="#{label}" />
<label for="#{label}">Confirm username</label>
<div class="bar"></div>
</div>
<div class="input-container"style="padding-top:1em;">
<input type="password" name="password" id="#{label}" />
<label for="#{label}">Confirm password</label>
<div class="bar"></div>
</div>
<div class="button-container">
<button type="submit" class="btn" name="edit_user">Register</button>
</div>
</form>
server.php
<?php
session_start();
$username = "";
$oras ="";
$nume ="";
$prenume ="";
$tara ="";
$adresa ="";
$telefon ="";
$varsta ="";
$email="";
$errors = array();
$db = mysqli_connect('localhost', 'root', '12345678', 'registration');
if (isset($_POST['reg_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($email)) { array_push($errors, "email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
$user_check_query = "SELECT * FROM users WHERE username='$username' OR email='$email' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) { // if user exists
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
}
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO users (username, email, password)
VALUES('$username', '$email', '$password')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['success'] = "You are now logged in";
header('location: primapagina.php');
}
}
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['success'] = "You are now logged in";
header('location: primapagina.php');
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
if (isset($_POST['edit_user']))
{
$oras = mysqli_real_escape_string($db, $_POST['oras']);
$tara = mysqli_real_escape_string($db, $_POST['tara']);
$adresa = mysqli_real_escape_string($db, $_POST['adresa']);
$nume = mysqli_real_escape_string($db, $_POST['nume']);
$prenume = mysqli_real_escape_string($db, $_POST['prenume']);
$telefon = mysqli_real_escape_string($db, $_POST['telefon']);
$varsta = mysqli_real_escape_string($db, $_POST['varsta']);
$password = md5(mysqli_real_escape_string($db, $_POST['password']));
$username = mysqli_real_escape_string($db, $_POST['username']);
$sql = "UPDATE users SET tara='$tara', oras='$oras', nume='$nume', prenume='$prenume', tara='$tara', adresa='$adresa' WHERE password = '$password' and username='$username' ";
mysqli_query($db, $sql);
}
?>
As # AKX wrote, when you type "$username = $row['username']", you're assigning the row's username into $username and always be true, executing the code inside the if all time for all your records. Here you will find more information PHP If PHP Expressions
As I can see in your code, You are fetching all the records from the users table, at the last iteration all the variable like $email, $user.... have the last row information that's why the code is updating the last user.

Registration error messages

In my registration page when you forget to fill your username you receives this message: "Please insert a username", when you forget to fill the password then you receives this message: "Please insert a password" or when you forget to fill the email then you receives this message: "Please insert a email" as you can see in the code bellow.
<?php
include"header"
if(isset($_POST["register"])){
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if(($username) == ""){
?><p><?php echo "Please insert a username"; ?></p><?php
}
if(($password) == ""){
?><p><?php echo "Please insert a password"; ?></p><?php
}
if(($email) == ""){
?><p><?php echo "Please insert a email"; ?></p><?php
}
else{
$checkusername = mysql_query("SELECT `id` FROM `user` WHERE `username` = '".$username."'") or die(mysql_error());
$checkemail = mysql_query("SELECT `id` FROM `user` WHERE `email` = '".$email."'") or die(mysql_error());
if(mysql_num_rows($checkusername) == 1){
?><p><?php echo "Username already exists"; ?></p><?php
}
if(mysql_num_rows($checkemail) == 1){
?><p><?php echo "Email already exists"; ?></p><?php
}
else{
mysql_query("INSERT INTO `database`.`user`(`username`,`password`,`email`) VALUES ('".$username."','".$password."','".$email."')") or die(mysql_error());
?><p><?php echo "You are Registered"; ?></p><?php
}
}
}
?>
<div id="loginform">
<form name="loginform" method="post">
<table cellpadding="0" id="tb">
<tr>
<td colspan="2"><div class="loginheader"><h2>Register</h2></div></td>
</tr>
</table>
<table cellpadding="0" id="REGOPTIONS">
<tr>
<td class="field">Username:</td>
<td><input type="text" class="text" name="username"></td>
</tr>
<tr>
<td class="field">Password:</td>
<td><input type="password" class="text" name="password"></td>
</tr>
<tr>
<td class="field">Email:</td>
<td><input type="email" class="text" name="email"></td>
</tr>
</table>
<table cellpadding="0">
<tr>
<td class="field"></td>
<td><input type="submit" class="submitbutton" name="register" value="Register" /></td>
</tr>
</table>
</form>
</div>
But my registration page can only display one error message at a time. I need my page to display all of them at once if you forget to fill your informations (username, password and email) at the same time like that:
"Please insert a username"
"Please insert a password"
"Please insert a email"
Transformed into an array. Try:
<?php
if(isset($_POST["register"])){
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if (!empty($username) && !empty($password) && !empty($email)){
$checkusername = mysql_query("SELECT `id` FROM `user` WHERE `username` = '".$username."'") or die(mysql_error());
$checkemail = mysql_query("SELECT `id` FROM `user` WHERE `email` = '".$email."'") or die(mysql_error());
if(mysql_num_rows($checkusername) == 1){
?><p><?php echo "Username already exists"; ?></p><?php
}
if(mysql_num_rows($checkemail) == 1){
?><p><?php echo "Email already exists"; ?></p><?php
}
else{
mysql_query("INSERT INTO `database`.`user`(`username`,`password`,`email`) VALUES ('".$username."','".$password."','".$email."')") or die(mysql_error());
?><p><?php echo "You are Registered"; ?></p><?php
}
} else{
if(empty($username)){
$error[] = "Please insert a username";
}
if(empty($password)){
$error[] = "Please insert a password";
}
if(empty($email)){
$error[] = "Please insert a email";
}
foreach ($error as $value) {
echo "Erros: $value<br />\n";
}
}
}
?>
<div id="loginform">
<form name="loginform" method="post">
<table cellpadding="0" id="tb">
<tr>
<td colspan="2"><div class="loginheader"><h2>Register</h2></div></td>
</tr>
</table>
<table cellpadding="0" id="REGOPTIONS">
<tr>
<td class="field">Username:</td>
<td><input type="text" class="text" name="username"></td>
</tr>
<tr>
<td class="field">Password:</td>
<td><input type="password" class="text" name="password"></td>
</tr>
<tr>
<td class="field">Email:</td>
<td><input type="email" class="text" name="email"></td>
</tr>
</table>
<table cellpadding="0">
<tr>
<td class="field"></td>
<td><input type="submit" class="submitbutton" name="register" value="Register" /></td>
</tr>
</table>
</form>
</div>
What I normally do is run through my form validation, and save each error (is there is one) to an array.
ie
$la_errors = array();
if(($username) == ""){
$la_errors[] = "Please insert username";
}
//etc. Then
if(!empty($la_errors)) {
break;
}
When you need to display the errors, explode the array, and display in a format (like or whatever) of your choice

Connect form to my SQL database?

I am trying to have this form submit to a database but I am having no luck. I am a complete newbie and based this code off another form that is already in use. Can anyone spot errors that would make it not work properly? Any help would be huge.
<?php
include("includes/captcha.php");
if (!empty($_POST['submitcontestant'])) {
$addcontestantsql = "INSERT INTO ".$config['db_dbpaper'].".contest (company, name, address, phone)";
$company = mysql_real_escape_string($_POST['company']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$phone = mysql_real_escape_string($_POST['phone']);
$captcha = mysql_real_escape_string($_POST['captcha']);
<?php
include("includes/captcha.php");
if (!empty($_POST['submitcontestant'])) {
$addcontestantsql = "INSERT INTO ".$config['db_dbpaper'].".contest (company, name, address, phone)";
$company = mysql_real_escape_string($_POST['company']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$phone = mysql_real_escape_string($_POST['phone']);
$captcha = mysql_real_escape_string($_POST['captcha']);
$addcontestantsql .= " VALUES('$company', '$name', '$email', '$phone')";
$allowed = false;
if (empty($company) && empty($name) && empty($address) && empty ($email) && empty($phone)) {
echo '<strong>Please go back and fill out all the fields!</strong>';
}
elseif ($captcha != $captchaans) {
echo '<strong>CAPTCHA incorrect!</strong>';
}
else {
$allowed = true;
echo '<strong>You are in the contest!</strong>';
}
if ($allowed) {
db_exec($addcontestantql);
}
}
?>
<?php
$companysql = "SELECT DISTINCT company FROM ".$config['db_dbpaper'].".contest ";
$mainsql = "SELECT * FROM ".$config['db_dbpaper'].".contest ";
if (!empty($_POST['submit'])) {
$companyname = mysql_real_escape_string($_POST['company']);
$mainsql .= "WHERE company like '$companyname'";
}
$company = db_list($companysql);
$contest = db_list($mainsql);
?>
<div id="fullwidthpage">
<h2>Contest</h2>
<p>Please fill the out form and then click submit. Thank you.</p>
<form method="post">
<table width="491" border="0">
<tr>
<td width="107">Company:</td>
<td width="374"><input name="company" type="text" /></td>
</tr>
<tr>
<td>Name:</td>
<td><input name="name" type="text" /></td>
</tr>
<tr>
<td>Email:</td>
<td><input name="address" type="text" /></td>
</tr>
<tr>
<td>Phone:</td>
<td><input name="phone" type="text" /></td>
</tr>
</table>
<p><?php echo '<img src="'.BASE_URL.'images/captcha/'.date('n').'.jpg">'; ?><br />
What color is this?:<br />
<input name="captcha" size="25" style="text-transform: lowercase;"/>
<input name="submitcontestant" type="submit" value="Submit" />
</p>
</form>
id suggest you to start here : http://se2.php.net/manual/en/intro.mysqli.php
you're way off track at the moment and basically asking someone to code it for you.
after your posts update : it seems that the problem is you're not connecting to sql at all try using $link = mysql_connect('host', 'mysql_user', 'mysql_password');
All set, I was creating my data table in the wrong database, new table was added in the appropriate database and all better :). Thanks to everyone who gave me input!

Why won't the data from my php upload to my sql server?

I've started writing a community-based website with a login (user / pass / avatar etc.). All of these variables are being stored on a sql server so I can access them for the login, etc.
I've looked all over google, and my code seems sound, and my email validation is sent. But none of the data uploads to my sql database, so no users can be created.
I've included the code for my website below, with the connect info taken out for security reasons. Why aren't I able to write data to my database? Any help would be appreciated.
register.php
<?php require('top.php'); ?>
<div id="full">
<?php
$form = " <form action='register.php' method='post'>
<table cellspacing='10px'>
<tr>
<td></td>
<td>Required Feilds <font color='red'>*</font></td>
</tr>
<tr>
<td>First Name:</td>
<td><input type='text' name='firstname' class='textbox'><font color='red'>*</font></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type='text' name='lastname' class='textbox'><font color='red'>*</font></td>
</tr>
<tr>
<td>Username:</td>
<td><input type='text' name='username' class='textbox'><font color='red'>*</font></td>
</tr>
<tr>
<td>Email:</td>
<td><input type='text' name='email' class='textbox'><font color='red'>*</font></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password' class='textbox'><font color='red'>*</font></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type='password' name='repassword' class='textbox'><font color='red'>*</font></td>
</tr>
<tr>
<td>Avatar:</td>
<td><input type='file' name='avatar' > </td>
</tr>
<tr>
<td>Website Address:</td>
<td><input type='text' name='website' class='textbox'></td>
</tr>
<tr>
<td>YouTube Username:</td>
<td><input type='text' name='youtube' class='textbox'></td>
</tr>
<tr>
<td>Bio:</td>
<td><textarea name='bio' cols='35' rows='5' class='textbox'></textarea> </td>
</tr>
<tr>
<td></td>
<td><input type='submit' name='submitbtn' value='Register' class='button'></td>
</tr>
</table>
</form>";
if($_POST['submitbtn']) {
$firstname = strip_tags($_POST['firstname']);
$lastname = strip_tags($_POST['lastname']);
$username = strip_tags($_POST['username']);
$email = strip_tags($_POST['email']);
$password = strip_tags($_POST['password']);
$repassword = strip_tags($_POST['repassword']);
$website = strip_tags($_POST['website']);
$youtube = strip_tags($_POST['youtube']);
$bio = strip_tags($_POST['bio']);
$name = $_FILES['avatar']['name'];
$type = $_FILES['avatar']['type'];
$size = $_FILES['avatar']['size'];
$tmpname = $_FILES['avatar']['tmp_name'];
$ext = substr($name, strrpos($name, '.'));
if ($firstname && $lastname && $username && $email && $password && $repassword) {
if ($password == $repassword){
if ( strstr($email, "#") && strstr($email, ".") && strlen($email) >= 6) {
require('connect.php');
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if ($numrows == 0) {
$query = mysql_query("SELECT * FROM users WHERE email='$email'");
$numrows = mysql_num_rows($query);
if ($numrows == 0) {
$pass = md5(md5($password));
$date =date("F d, Y");
if ($name) {
move_uploaded_file($tmpname, "avatars/$username.$ext");
$avatar = "$username.$ext";
}
else
$avatar = "avatars/defavatar.png";
$code = substr(md5(rand (1111111111, 99999999999999999)), 2, 25);
mysql_query("INSERT INTO users VALUES ('','$firstname','$lastname,'$username','$email','$pass','$avatatar','$bio','$website','$youtube','','0','$code','0','$date')");
$webmaster = "email#email.com";
$subject = "Activate Your Account";
$headers = "From: a person <$webmaster>";
$message = "Hello $firstname. Welcome to awebsite.com Below is a link for you to activate your account.\n\n Click Here to Activate Your Account: http://awebsite.netii.net/activate.php?code=$code";
mail ($email, $subject, $message, $headers);
echo "Thank You for registering. To access your account please activate your account by folowing the link sent to <b>$email</b>. If you do not see the email in your inbox, check your junk mail as it may have been filtered. If you are expeiriencing any problems please contact the site administrator at <a href='mailto:email#email.com'>email#email.com</a>";
}
else
echo "That email is already taken. $form";
}
else
echo "That username is already taken. $form";
}
else
echo "You did not enter a valid email. $form";
}
else
echo "Your Passwords did not match. $form";
}
else
echo "You did not fill in all the required feilds. $form";
}
else
echo "$form";
?>
</div>
<?php require('bottom.php');?>
</div>
</body>
</html>
Activate.php
<?php $title = "Activate Your Account"; ?>
<?php require('top.php');?>
<div id="full">
<?php
$getcode =$_GET['code'];
$form = "<form action='activate.php' method='post'>
<table>
<tr>
<td>Activate Code:</td>
<td><input type='text' name='code' value='$getcode' size='30' </td>
</tr>
<tr>
<td>Username:</td>
<td><input type='text' name='username' </td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password' </td>
</tr>
<tr>
<td></td>
<td><input type='submit' name='submitbtn' value='Activate'</td>
</tr>
</table>
</form>";
if ($_POST['submitbtn']) {
$code = strip_tags($_POST['code']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
if ($code && $username && $password) {
if (strlen($code) == 25) {
$pass = md5(md5($password));
require('connect.php');
$query = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$pass'");
$numrows = mysql_num_rows($query);
if ($numrows == 1) {
$row = mysql_fetch_assoc($query);
$dbcode = $row['code'];
if ($code == $dbcode) {
mysql_query("UPDATE users SET active='1' WHERE username='$username'");
echo "Your account has been activated. You may now login. Click<a href='login.php'>here</a> to login.";
}
else
echo"Your activation code was incorrect. $form";
}
else
echo "Your username or password are invalid. $form";
}
else
echo "You have not supplied a valid code. $form";
}
else
echo "You did not fill out the entire form. $form";
}
else
echo "$form";
?>
</div>
<?php require('bottom.php');?>
connect.php
<?php
$server = "";
$dbuser = "";
$dbpass = "";
$database = "";
mysql_connect($server, $dbuser, $dbpass) or die("Unable to connect to $server");
mysql_select_db($database) or die( "Unable to select $database" );
?>
There is typo mistake in your code.
First we have to check if submit request is set or not, so => if($_POST['submitbtn']) should be,
if( isset($_POST['submitbtn']) ) {
...
}
Make change in code and check.
EDIT
You can reformat your code. Check for all variables not empty, use mysql escape instead of strip tags and don't use any escapes on password, only hash(md5).
if (isset($_POST['submitbtn'])) {
$code = mysql_real_escape_string($_POST['code']);
$username = mysql_real_escape_string($_POST['username']);
$password = md5($_POST['password']);
$errors = array();
if (empty($code) || empty($username) || empty($password)) {
$errors[] = "You did not fill out the entire form." . $form;
} elseif(strlen($code) !== 25) {
$errors[] = "You have not supplied a valid code." . $form;
} else {
// further code...
}
} else {
echo $form;
}
In register.php, change:
<form action='register.php' method='post'>
To:
<form action='register.php' method='post' enctype="multipart/form-data">
This is required to upload files using <input type="file" ...>.
You should not use $pass = md5(md5($password)); - It is just way to easy to crack. Instead look into crypt() - http://php.net/crypt
As this is new code, please consider changing from mysql_* functions to mysqli_* or PDO as PHP is depreciating mysql_* and this will save you time later.

Trouble inserting a new user into a mysql database

I have a form that allows me to enter a user into my database. However, whenever I click on submit I receive the query failed error message. Below is my the form I have built:
register-admin.php
<form id="resgisterform" name="registerform" method="post" action="register-admin-exec.php">
<table width="300" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<th>Username </th>
<td><input name="username" type="text" class="textfield" id="username" /></td>
</tr>
<tr>
<th>First Name </th>
<td><input name="first_name" type="text" class="textfield" id="first_name" /></td>
</tr>
<tr>
<th>Last Name </th>
<td><input name="last_name" type="text" class="textfield" id="last_name" /></td>
</tr>
<tr>
<th>Muvdigital Email </th>
<td><input name="muvdigital_email" type="text" class="textfield" id="muvdigital_email" /></td>
</tr>
<tr>
<th>Personal Email </th>
<td><input name="personal_email" type="text" class="textfield" id="personal_email" /></td>
</tr>
<tr>
<th>Title </th>
<td><input name="title" type="text" class="textfield" id="title" /></td>
</tr>
<tr>
<th>Address 1 </th>
<td><input name="address_1" type="text" class="textfield" id="address_1" /></td>
</tr>
<tr>
<th>Address 2 </th>
<td><input name="address_2" type="text" class="textfield" id="address_2" /></td>
</tr>
<tr>
<th>City </th>
<td><input name="city" type="text" class="textfield" id="city" /></td>
</tr>
<tr>
<th>State </th>
<td><input name="state" type="text" class="textfield" id="state" /></td>
</tr>
<tr>
<th>Zip Code </th>
<td><input name="zip" type="text" class="textfield" id="zip" /></td>
</tr>
<tr>
<th>Phone </th>
<td><input name="phone" type="text" class="textfield" id="phone" /></td>
</tr>
<tr>
<th>Password </th>
<td><input name="password" type="password" class="textfield" id="password" /></td>
</tr>
<tr>
<th>Confirm Password </th>
<td><input name="cpassword" type="password" class="textfield" id="cpassword" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Register" /></td>
</tr>
</table>
</form>
The values from this form are then brought over to the register-admin-exec.php page which is below
<?php
//Start session
session_start();
//Include database connection details
require_once('config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//define and validate the post values
/*if (isset ($_POST['admin_id']) && !empty ($_POST['admin_id'])) {
$admin_id = $_POST['admin_id'];
} else {
echo 'Error: admin id not provided!';
}*/
if (isset ($_POST['username']) && !empty ($_POST['username'])) {
$username = clean($_POST['username']);
} else {
echo 'Error: username not provided!';
}
if (isset ($_POST['first_name']) && !empty ($_POST['first_name'])) {
$first_name = clean($_POST['first_name']);
} else {
echo 'Error: first name not provided!';
}
if (isset ($_POST['last_name']) && !empty ($_POST['last_name'])) {
$last_name = clean($_POST['last_name']);
} else {
echo 'Error: last name not provided!';
}
if (isset ($_POST['muvdigital_email']) && !empty ($_POST['muvdigital_email'])) {
$muvdigital_email = clean($_POST['muvdigital_email']);
} else {
echo 'Error: muvdigital email not provided!';
}
if (isset ($_POST['personal_email']) && !empty ($_POST['personal_email'])) {
$personal_email = clean($_POST['personal_email']);
} else {
echo 'Error: personal email not provided!';
}
if (isset ($_POST['title']) && !empty ($_POST['title'])) {
$title = clean($_POST['title']);
} else {
echo 'Error: title not provided!';
}
if (isset ($_POST['phone']) && !empty ($_POST['phone'])) {
$phone = clean($_POST['phone']);
} else {
echo 'Error: phone not provided!';
}
if (isset ($_POST['address_1']) && !empty ($_POST['address_1'])) {
$address_1 = clean($_POST['address_1']);
} else {
echo 'Error: address 1 not provided!';
}
$address_2 = clean($_POST['address_2']);
if (isset ($_POST['city']) && !empty ($_POST['city'])) {
$city = clean($_POST['city']);
} else {
echo 'Error: city not provided!';
}
if (isset ($_POST['state']) && !empty ($_POST['state'])) {
$state = clean($_POST['state']);
} else {
echo 'Error: state not provided!';
}
if (isset ($_POST['zip']) && !empty ($_POST['zip'])) {
$zip = clean($_POST['zip']);
} else {
echo 'Error: zip not provided!';
}
if (isset ($_POST['password']) && !empty ($_POST['password'])) {
$password = clean($_POST['password']);
} else {
echo 'Error: password not provided!';
}
if (isset ($_POST['cpassword']) && !empty ($_POST['cpassword'])) {
$cpassword = clean($_POST['cpassword']);
} else {
echo 'Error: confirm password not provided!';
}
//encrypt the password
$salt = sha1($username);
$password = sha1($salt.$password);
//Check for duplicate login ID
if($username != '') {
$qry = "SELECT * FROM members WHERE username='".$username."'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) > 0) {
$errmsg_arr[] = 'Login ID already in use';
$errflag = true;
}
#mysql_free_result($result);
}
else {
die("Query failed");
}
}
//If there are input validations, redirect back to the registration form
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: register-admin.php");
exit();
}
//Create INSERT query
$qry = "INSERT INTO admins (
'username',
'password',
'first_name',
'last_name',
'muvdigital_email',
'personal_email',
'titles',
'phone',
'address_1',
'address_2',
'city',
'state',
'zip')
VALUES (
'$username',
'$password',
'$first_name',
'$last_name',
'$muvdigital_email',
'$personal_email',
'$title',
'$phone',
'$address_1',
'$address_2',
'$city',
'$state',
'$zip')";
$result = mysql_query($qry);
//Check whether the query was successful or not
if($result) {
header("location: register-success.php");
exit();
}else {
die("Query failed $qry");
}
?>
I know it is failing at my insert statement because I have tried commenting out the previous validation check for duplicate login ids and it still fails. I cannot figure out why my insert statement isn't working. After echoing the $qry, i get
INSERT INTO admins ( 'username', 'password', 'first_name', 'last_name', 'muvdigital_email', 'personal_email', 'titles', 'phone', 'address_1', 'address_2', 'city', 'state', 'zip') VALUES ( 'johndoe', '7afbb2186cf26d85bdfe948d367fb6baa6739283', 'john', 'doe', 'john.doe#muvdigital.com', 'jdoe#gmail.com', 'intern', '6024013776', '18b main st', 'apt 12', 'Hooksett', 'NH', '03106')
so the $_POST function is working. I have tried manually entering the insert statement at the command line and i receive ERROR 1054 (42S22): Unknown column 'johndoe' in 'field list'.
The admin_id is an auto_increment field which is why I have commented it out (and I have tried uncommenting it and manually creating an admin_id, which stil does not work)
Anyone have an idea as to why this is happening?
You have quoted all your column names with single quotes, which is incorrect. They should be unquoted, except if you have used a MySQL reserved keyword (which you have not)
// Column names are unquoted, but VALUES() should be quoted.
$qry = "INSERT INTO admins (
username,
password,
first_name,
last_name,
muvdigital_email,
personal_email,
titles,
phone,
address_1,
address_2,
city,
state,
zip)
VALUES (
'$username',
'$password',
'$first_name',
'$last_name',
'$muvdigital_email',
'$personal_email',
'$title',
'$phone',
'$address_1',
'$address_2',
'$city',
'$state',
'$zip')";
$result = mysql_query($qry);

Categories