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.
Related
since i am new new here,i'm trying to be specific on my question. please tell me if you need more info.
Whenever i'm trying to submit the form it doesn't show any error regarding the code. it only show echo statement "FAILED"
i am using this loop to see if the values are submitted or not. this is working fine. it shows that all the values are submitted but these values are not inserting into database .
foreach ($_POST as $key => $value) {
echo "($key) => ($value)<br/>";
}
my html form code is :
<div class="formstyle">
<h2> Sign up </h2>
<center>
<form method = 'POST' name="form1" onSubmit="return validateForm()" action="">
<table border='0'>
<tr>
<td><LABEL for="firstname">First Name:<sup style="color:#F00">*</sup> </LABEL></td>
<td><INPUT type="text" name = "fname" id="fname" value="<?php echo $fname;?>"></td><td width="200px"><i style="color:red;" id="pointfn"></i></td>
</tr>
<tr>
<td><LABEL for="lastname">Last Name:<sup style="color:#F00">*</sup> </LABEL></td>
<td><INPUT type="text" name ="lname" id="lname" value="<?php echo $lname;?>"> </td><td width="200px"><i style="color:red;" id="pointln"></i></td>
</tr>
<tr>
<td><LABEL for="gender">Gender:<sup style="color:#F00">*</sup> </LABEL></td> <td>
<INPUT type="radio" name="gender" id="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male"> Male
<INPUT type="radio" name="gender" id="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female"> Female</td><td width="200px"> <i style="color:red;" id="pointgendr"></i></td>
</tr>
<tr>
<td><LABEL for="email">Email:<sup style="color:red;">*</sup> </LABEL></td>
<td><INPUT type="text" name = "email" id="email" value="<?php echo $email;?>"></td><td width="200px"><i style="color:red;" id="pointemail"></i></td>
</tr>
<tr>
<td><LABEL for="password">Password:<sup style="color:#F00">*</sup> </LABEL></td>
<td><INPUT type="password" name ="password" id="password" value="<?php echo $password;?>"></td><td width="200px"><i style="color:red;" id="pointpassword"></i></td>
</tr>
<tr>
<td></td><td><br/><INPUT type="submit" name = "register" value="Create Account">
<INPUT type="reset" onClick="return confirmreset()"></td>
</tr>
<tr>
<td></td><td style="font-size:12px;text-align:right;"><br/><i style="color:red;font-size:12px;align:right;" >* - Mandatory</i></td>
</tr>
</table>
</form></center>
this is the php code that inserting everything into database
require('connect.php');
$fname = $lname = $gender = $email = $password = "";
if(isset($_POST['register'])){
$stmt = $pdo->prepare('INSERT INTO user(fname,lname,gender,email,password)
VALUES (:fname, :lname, :gender, :email, :password)');
$stmt->bindValue(':fname',$fname);
$stmt->bindValue(':lname',$lname);
$stmt->bindValue(':gender',$gender);
$stmt->bindValue(':email',$email);
$passwordHash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 12));
$stmt->bindValue(':password',$passwordHash);
$stmt->execute();
$email_stmt = $pdo->prepare("SELECT email FROM user WHERE email = :email");
$email_stmt->bindParam(':email', $email);
$email_stmt->execute();
if ($email_stmt->rowCount()>0){
echo 'Email Already Exists. Use Different Email OR Login ';
} else {
//Successful Registration
echo 'Registration Successful';
}
} else {
echo 'FAILED';
}
?>
any help would be appreciated. Cheers.
you are checking if email taken after using insert
try this
if(isset($_POST['register'])){
$password = $_POST['password'];
$fname = $_POST['fname'];
$email = $_POST['email'];
$lname = $_POST['lname'];
$gender = $_POST['gender'];
$passwordHash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 12));
//validate form here
$email_stmt = $pdo->prepare("SELECT email FROM user WHERE email = :email");
$email_stmt->bindParam(':email', $email);
$email_stmt->execute();
$result = $email_stmt->fetch(PDO::FETCH_ASSOC);
if (empty($result)) {
$stmt = $pdo->prepare('INSERT INTO user(fname,lname,gender,email,password)
VALUES (:fname, :lname, :gender, :email, :password)');
$stmt->bindValue(':fname',$fname);
$stmt->bindValue(':lname',$lname);
$stmt->bindValue(':gender',$gender);
$stmt->bindValue(':email',$email);
$stmt->bindValue(':password',$passwordHash);
if ($stmt->execute()) {
echo 'Registration Successful';
}
else {
echo 'FAILED';
}
}
else {
echo 'Email Already Exists. Use Different Email OR Login ';
}
}
Looks like you don't need a foreach for this form. I think you should try for example:
echo $_POST['fname'];
http://php.net/manual/en/reserved.variables.post.php
Also this name = "fname" should be this name="fname"
You must put POST'S into variables.
Try this
require('connect.php');
$fname = $lname = $gender = $email = $password = "";
if(isset($_POST['register'])){
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$gender = $_POST['gender'];
$email = $_POST['email'];
$password = $_POST['password'];
$stmt = $pdo->prepare('INSERT INTO user(fname,lname,gender,email,password)
VALUES (:fname, :lname, :gender, :email, :password)');
$stmt->bindValue(':fname',$fname);
$stmt->bindValue(':lname',$lname);
$stmt->bindValue(':gender',$gender);
$stmt->bindValue(':email',$email);
$passwordHash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 12));
$stmt->bindValue(':password',$passwordHash);
$stmt->execute();
$email_stmt = $pdo->prepare("SELECT email FROM user WHERE email = :email");
$email_stmt->bindParam(':email', $email);
$email_stmt->execute();
if ($email_stmt->rowCount()>0){
echo 'Email Already Exists. Use Different Email OR Login ';
} else {
//Successful Registration
echo 'Registration Successful';
}
} else {
echo 'FAILED';
}
?>
i have made a registration from (followed e.g from w3schools.com) where they have used the $_SERVER["PHP_SELF"] in the action of form method.
$_SERVER["PHP_SELF"] this helps for validation part but it doesn't allow to insert data into db.
I have also written code for mobile no. where only numbers should be inserted but that is also not working.Please help.
<html>
<head>
<title>Meeting Room Application</title>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $mobErr = $uidErr = $pwdErr = $roleErr = "";
$txtname = $gender = $txtmob = $txteid = $txtuid = $txtpwd = $role = "";
if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["txtname"])) {
$nameErr = "Name is required";
} else {
$txtname = test_input($_POST["txtname"]);
// check if name only contains letters and whitespace
if(!preg_match("/^[a-zA-Z ]*$/", $txtname)) {
$nameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["txteid"])) {
$emailErr = "Email is required";
} else {
$txteid = test_input($_POST["txteid"]);
// check if e-mail address is well-formed
if(!filter_var($txteid, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if(empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
if(empty($_POST["txtmob"])) {
$mobErr = "Mobile is required";
} else {
$txtmob = test_input($_POST["txtmob"]);
//check only numbers are given
if(preg_match("/^d{10}$/", $txtmob)) {
$mobErr = "Only numbers are allowed";
}
}
if(empty($_POST["txtuid"])) {
$uidErr = "User Id is required";
} else {
$txtuid = test_input($_POST["txtuid"]);
}
if(empty($_POST["txtpwd"])) {
$pwdErr = "Password is required";
} else {
$txtpwd = test_input($_POST["txtpwd"]);
}
if(empty($_POST["role"])) {
$roleErr = "Role is required";
} else {
$role = test_input($_POST["role"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<table align="center" cellpadding="5" cellspacing="5">
<tr>
<th colspan="2"><img src="Hitech Logo1.png" alt="HiTech"></th>
</tr>
<tr>
<th colspan="2"><h1>User Registration</h1></th>
</tr>
<tr>
<td colspan="2" align="left"><font color="red">All fields are mandatory</font></td>
</tr>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<tr>
<td>Full Name : </td>
<td><input type="text" name="txtname" value="<?php echo $txtname ?>"> <font color="red"><?php echo $nameErr; ?></td>
</tr>
<tr>
<td>Gender : </td>
<td><input type="radio" name="gender" <?php if(isset($gender) && $gender == "Male") echo "checked"; ?> value="Male">Male
<input type="radio" name="gender" <?php if(isset($gender) && $gender == "Female") echo "checked"; ?> value="Female">Female
<font color="red"><?php echo $genderErr; ?>
</td>
</tr>
<tr>
<td>Mobile No. : (+91)</td>
<td><input type="text" name="txtmob" maxlength="10" value="<?php echo $txtmob ?>">
<font color="red"><?php echo $mobErr; ?>
</td>
</tr>
<tr>
<td>Email Id : </td>
<td><input type="text" name="txteid" value="<?php echo $txteid ?>">
<font color="red"><?php echo $emailErr; ?>
</td>
</tr>
<tr>
<td>User Id : </td>
<td><input type="text" name="txtuid" value="<?php echo $txtuid ?>">
<font color="red"><?php echo $uidErr; ?>
</td>
</tr>
<tr>
<td>Password : </td>
<td><input type="password" name="txtpwd" value="<?php echo $txtpwd ?>">
<font color="red"><?php echo $pwdErr; ?>
</td>
</tr>
<tr>
<td>Role : </td>
<td><input type="radio" name="role" <?php if(isset($role) && $role == "User") echo "checked"; ?> value="User">User
<input type="radio" name="role" <?php if(isset($role) && $role == "Admin") echo "checked"; ?> value="Admin">Admin
<font color="red"><?php echo $roleErr; ?>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" name="btnsave">
</td>
</tr>
</form>
</tr>
</table>
<?php
$host = "localhost"; // Host name
$username = "root"; // Mysql username
$password = ""; // Mysql password
$db_name = "testmra"; // Database name
// Connect to server and select databse.
$conn = mysqli_connect($host, $username, $password) or die("cannot connect");
mysqli_select_db($conn, $db_name);
$name = mysqli_real_escape_string($conn, $_POST['txtname']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$mobile = mysqli_real_escape_string($conn, $_POST['txtmob']);
$email = mysqli_real_escape_string($conn, $_POST['txteid']);
$username = mysqli_real_escape_string($conn, $_POST['txtuid']);
$userpass = mysqli_real_escape_string($conn, $_POST['txtpwd']);
$role = mysqli_real_escape_string($conn, $_POST['role']);
$res = mysqli_query($conn, "SELECT username FROM trialusers WHERE username='$username'");
$row = mysqli_fetch_row($res);
if($row > 0) {
echo "Username $username has already been taken";
} else {
$sql = "INSERT INTO newuser (name,gender,contactno,emailid,username,userpass,role)VALUES('$name','$gender','$mobile','$email','$username','$userpass','$role')";
if(mysqli_query($conn, $sql)) {
header("location:registration.php");
} else {
die('Error: Cannot connect to db');
}
}
?>
</body>
</html>
Change the last part of your code to this:
<?php
if(!empty($_POST)){
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="testmra"; // Database name
// Connect to server and select databse.
$conn=mysqli_connect($host,$username,$password) or die("cannot connect");
mysqli_select_db($conn,$db_name);
$name = mysqli_real_escape_string($conn, $_POST['txtname']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$mobile = mysqli_real_escape_string($conn, $_POST['txtmob']);
$email = mysqli_real_escape_string($conn, $_POST['txteid']);
$username = mysqli_real_escape_string($conn, $_POST['txtuid']);
$userpass = mysqli_real_escape_string($conn, $_POST['txtpwd']);
$role= mysqli_real_escape_string($conn, $_POST['role']);
$res=mysqli_query($conn,"SELECT username FROM trialusers WHERE username='$username'");
$row=mysqli_fetch_row($res);
if($row>0)
{
echo "Username $username has already been taken";
}
else
{
$sql="INSERT INTO newuser (name,gender,contactno,emailid,username,userpass,role)VALUES('$name','$gender','$mobile','$email','$username','$userpass','$role')";
if (mysqli_query($conn,$sql))
{
header("location:registration.php");
}
else
{
die('Error: Cannot connect to db' );
}
}
}
?>
This will trigger the data insert part only when you actually post data from the form and will remove the error you see. BTW the code you are using is outdated and use a mysql library that is deprecated. Please consider update to PDO
It is not always possible to receive a POST request on your page so keep your bottom PHP code into a condition
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="testmra"; // Database name
// Connect to server and select databse.
$conn=mysqli_connect($host,$username,$password) or die("cannot connect");
mysqli_select_db($conn,$db_name);
$name = mysqli_real_escape_string($conn, $_POST['txtname']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$mobile = mysqli_real_escape_string($conn, $_POST['txtmob']);
$email = mysqli_real_escape_string($conn, $_POST['txteid']);
$username = mysqli_real_escape_string($conn, $_POST['txtuid']);
$userpass = mysqli_real_escape_string($conn, $_POST['txtpwd']);
$role= mysqli_real_escape_string($conn, $_POST['role']);
$res=mysqli_query($conn,"SELECT username FROM trialusers WHERE username='$username'");
$row=mysqli_fetch_row($res);
if($row>0)
{
echo "Username $username has already been taken";
}
else
{
$sql="INSERT INTO newuser (name,gender,contactno,emailid,username,userpass,role)VALUES('$name','$gender','$mobile','$email','$username','$userpass','$role')";
if (mysqli_query($conn,$sql))
{
header("location:registration.php");
}
else
{
die('Error: Cannot connect to db' );
}
}
}
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.
I have tried to implement a form that changes a password in a database, however, when I submit the details on the form, it just directs me to the target page...but shows up and the plaintext code on the browser....why is it doing this!
The form:
<h1 align="center">Change Password</h1>
<form method="POST" action="reset_pwd.php">
<table class='altrowstable' id='alternatecolor' >
<tr>
<td align="right">Username: </td>
<td><input type="TEXT" name="username" value=""/></td>
</tr>
<tr>
<td align="right">Current Password: </td>
<td><input type="password" name="password" value=""/></td>
</tr>
<tr>
<td align="right">New Password: </td>
<td><input type="password" name="npassword" value=""/></td>
</tr>
<tr>
<td align="right">Repeat New Password: </td>
<td><input type="password" name="rpassword" value=""/></td>
</tr>
<tr><td align="center">
Forgot password
</td>
<td>
<input type="submit" name="submit" value="Change Password"/>
</td>
</tr>
</table>
</form>
<br>
<?php echo $msg; ?>
and the target php page:
<?php
include('dbconfig.php');
$msg = "";
if (mysql_real_escape_string($_POST['submit'])):
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string(md5($_POST['password']));
$npassword = mysql_real_escape_string(md5($_POST['npassword']));
$rpassword = mysql_real_escape_string(md5($_POST['rpassword']));
$sql = "SELECT * FROM user_info WHERE user_id = '$username' ";
$query = mysql_query($sql);
$numrows = mysql_num_rows($query);
while ($rows = mysql_fetch_array($query)):
$dbusername = $rows['username'];
$dbpassword = $rows['password'];
$dbfirstname = $rows ['firstname'];
$dblastname = $rows ['lastname'];
endwhile;
if (empty($username) || empty($password) || empty($npassword) ||
empty($rpassword)):
$msg = "All fields are required";
elseif ($numrows == 0):
$msg = "This username does not exist";
elseif ($password != $dbpassword):
$msg = "The CURRENT password you entered is incorrect.";
elseif ($npassword != $rpassword):
$msg = "Your new passwords do not match";
elseif ($npassword == $password):
$msg = "Your new password cannot match your old password";
else:
mysql_query("UPDATE user_info SET password = '$npassword' WHERE user_id =
'$username'");
$to = $email;
$subject = "YOUR PASSWORD HAS BEEN CHANGED";
$message = "<p>Hello $dbfirstname $dblastname. You've received this E-Mail
because you have requested a PASSWORD CHANGE. ";
$from = "myemail#.com";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
endif;
endif;
?>
PLease check... What is the type of "user_id" in "user_info" table... and what are you getting in user name field from your form.
am asking about this query...
$sql = "SELECT * FROM user_info WHERE user_id = '$username' ";
First $msg in target php is only for target php,won't return value back to the form
Second,you may looking for
if (isset($_POST['submit'])): instead of
if (mysql_real_escape_string($_POST['submit'])):
There is no html response from the target page to be displayed in browser. For displaying content you need to form proper html so that it can be displayed in browser.
In target page add the below html code at the end so that the message (validation or success) can be displayed.
<html><body>put your message here</body></htm>
You might have forgotten an extra ?> at the end of your included file "dbconfig.php", thus treating your target php page as html.
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.