Multiple form sign up not working - php

I have a sign up process which involves two forms being submitted. The problem is with the first form not being submitted. Also, I need a way to relate the two forms as information from both is inserted into the same table row, I think this can be done by taking the previous table row id.
It is supposed to work like this: First a user must search for an item in the search bar. Matches are then displayed with radio buttons next to each one and a submit button at the bottom. When submitted, the form data (which is the result of the search that they checked with the radio) goes into the database table 'users'. The 'users' table contains a row for id, username, password and radio.
The radio option is submitted into radio. This also creates an id, which is auto incremented. That is the first form. Once the radio option is picked and the data is in a table row, the user must fill out the second form which asks for an email and a password, which is submitted into the same row that the radio option is in.
When I go through this process, the email (referred to as username in table) and password appear in the table along with the id, but the radio is always blank. Not sure why the radio option is not being submitted. Also not sure if i need a way to relate the forms. I am a beginner at this so, please try to make answers understandable. Thanks in advance, heres the code:
<?php
//This code runs if the form has been submitted
if (isset($_POST['submit'])) {
//This makes sure they did not leave any fields blank
if (!$_POST['username'] | !$_POST['pass'] | !$_POST['pass2'] ) {
die('You did not complete all of the required fields');
}
// checks if the username is in use
if (!get_magic_quotes_gpc()) {
$_POST['username'] = addslashes($_POST['username']);
}
$usercheck = $_POST['username'];
$check = mysql_query("SELECT username FROM users WHERE username = '$usercheck'")
or die(mysql_error());
$check2 = mysql_num_rows($check);
//if the name exists it gives an error
if ($check2 != 0) {
die('The email '.$_POST['username'].' is already in use.');
}
// this makes sure both passwords entered match
if ($_POST['pass'] != $_POST['pass2']) {
die('Your passwords did not match. ');
}
// here we encrypt the password and add slashes if needed
$_POST['pass'] = md5($_POST['pass']);
if (!get_magic_quotes_gpc()) {
$_POST['pass'] = addslashes($_POST['pass']);
$_POST['username'] = addslashes($_POST['username']);
}
// now we insert it into the database
$insert = "INSERT INTO users (username, password, radio)
VALUES ('".$_POST['username']."', '".$_POST['pass']."', '".$_POST['radio']."')";
$add_member = mysql_query($insert);
?>
<h2><font color="red">Registered</font></h2>
<p>Thank you, you have registered - you may now login</a>.</p>
<?php
}
else
{
?>
<font color = #000000><h1>Sign Up</h1></font>
<?php
// Search Engine
// Only execute when button is pressed
if (isset($_POST['keyword'])) {
// Filter
$keyword = trim ($_POST['keyword']);
// Select statement
$search = "SELECT * FROM tbl_name WHERE cause_name LIKE '%$keyword%'";
// Display
$result = mysql_query($search) or die('That query returned no results');
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
while($result_arr = mysql_fetch_array( $result ))
{
?>
// Radio button
<input type="radio" name="radio">
<?php
echo $result_arr['cause_name'];
echo " ";
echo "<br>";
}
?>
<input type="submit" name="radio_submit" value="Select Item">
</form>
<?php
$anymatches=mysql_num_rows($result);
if ($anymatches == 0)
{
echo "We don't seem to have that cause. You may add a cause by filling out a short <a href='add.php'>form</a>.<br><br>";
}
}
?>
<!--Sign Up Form-->
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="sign_up_form">
<input type="text" name="keyword" placeholder="Search" onFocus="this.select();" onMouseUp="return false;">
<input type="submit" name="search" value="Search">
<br />
<br />
<input type="email" name="username" maxlength="250" placeholder="Your email" onFocus="this.select();" onMouseUp="return false;">
<input type="password" name="pass" maxlength="50" placeholder="Password" onFocus="this.select();" onMouseUp="return false;">
<input type="password" name="pass2" maxlength="50" placeholder="Re-type Password" onFocus="this.select();" onMouseUp="return false;">
<br />
<input type="submit" name="submit" value="Sign Up">
</form>
<?php
}
?>

Modify your code like this
<input type="radio" name="radio" value="<?php echo $result_arr['cause_name']; ?>" >
and then submit it you should get the value
update the below query as well
<?php
echo $insert = "INSERT INTO users (username, password, radio) VALUES ('$_POST[username]', '$_POST[pass]', '$_REQUEST[radio]')";
$add_member = mysql_query($insert);
?>
change the below code
//This code runs if the form has been submitted
if (isset($_POST['radio_submit'])) {
/////
<?php
if (isset($_REQUEST['submit']))
{
$radio = $_REQUEST['radio'];
$insert = mysql_query("INSERT INTO users (radio) VALUE ('$radio')");
if (!$insert)
{
echo mysql_error();
}
}
?>
<form action="" method="get">
<input type="radio" name="radio" value="red">red
<input type="radio" name="radio" value="blue">blue
<input type="submit" name="submit" />
</form>

Related

Failing to get POST values from HTML form in PHP

I am struggling to get values from an HTML form into PHP variables using POST. It used to work but now no matter what I do it isn't working. Here is the php file:
<?php
include "DBConn.php";
session_start();
?>
<html>
<head>
<title>Register</title>
<link rel="stylesheet" href="Register.css" type = "text/css">
</head>
<body>
<div id="container">
<form action="register.php" method = "post">
<label for="name">Name:</label>
<input type="text" id="name" name="txtName" value = <?php if(isset($_POST['txtName'])) echo $_POST['txtName'];?>>
<label for="surname">Surname:</label>
<input type="text" id="surname" name="txtSurname" value = <?php if(isset($_POST['txtSurname'])) echo $_POST['txtSurname'];?>>
<label for="address">Address:</label>
<input type="text" id="address" name="txtAddress" value = <?php if(isset($_POST['txtAddress'])) echo $_POST['txtAddress'];?>>
<label for="email">Email:</label>
<input type="email" id="email" name="txtEmail" value = <?php if(isset($_POST['txtEmail'])) echo $_POST['txtEmail'];?>>
<label for="password">Password:</label>
<input type="password" id="password" name="txtPassword" value = <?php if(isset($_POST['txtPassword'])) echo $_POST['txtPassword'];?>>
<label for="password2">Re-enter Password:</label>
<input type="password" id="password2" name="txtPassword2" value = <?php if(isset($_POST['txtPassword2'])) echo $_POST['txtPassword2'];?>>
<div id="lower">
<input type="submit" value="Register" name = "btnRegister">
</div><!--/ lower-->
</form>
</div>
</body>
</html>
<?php
//Runs if btnRegister is clicked. Registers a user.
if (isset($_POST['btnRegister'])) {
//Assigns form data to variables
$_SESSION["Name"] = $_POST['txtName'];
$_SESSION["Surname"] = $_POST['txtSurname'];
$_SESSION["Email"] = $_POST['txtEmail'];
$_SESSION["Password"] = $_POST['txtPassword'];
$_SESSION["Password2"] = $_POST['txtPassword2'];
$_SESSION["Address"] = $_POST['txtAddress'];
$sqlSelect =
"SELECT *
FROM tbl_Customer
WHERE Email = '{$_SESSION["Email"]}'";
//Runs select query
$result = $conn->query($sqlSelect);
$md5pass = md5($_SESSION["Password"]);
//Checks to see if user exists based on query
if ($result->num_rows == 0) {
//Checks to see if passwords match
if ($_SESSION["Password"] == $_SESSION["Password2"]) {
//Passwords match
echo '<script>alert("Passwords match")</script>';
//Insert statement to insert user into table
$sqlInsert = "INSERT INTO tbl_Customer (Name, Surname, Email, Password, Address)
VALUES ('{$_SESSION["Name"]}','{$_SESSION["Surname"]}','{$_SESSION["Email"]}','$md5pass','{$_SESSION["Address"]}');";
if ($conn->query($sqlInsert) === TRUE) {
echo '<script>alert("Registered successfully")</script>';
}
else {
echo '<script>alert("Registration error: " . $sql . "<br>" . $conn->error)</script>';
}
}
else {
echo '<script>alert("Passwords do not match")</script>';
}
}
else {
//User exists
echo '<script>alert("User already exists, choose a different email.")</script>';
}
header('Location: login.php');
exit();
}
?>
None of the alerts are working indicating that they echos are not working. Also, the second I click the register button I am taken to the login page which means the register button must be working. It doesn't give me any errors or messages.
Remove action="register.php" from <form> tag if your PHP code is on the same page as HTML code. The action attribute specifies where to send the form-data when a form is submitted, since your PHP code is on the same page you should remove action and the form-data will be submitted on that same page.
Or
create a register.php and put PHP code there.

Dynamic insert into with multiple values

This is my index.php file and it has a simple form but with jscript I'll add some more inputs dynamically, then I need to insert these inputs to my database.
<form action="insert.php" method="post">
<input type="text" name="uid" placeholder="uid">
<input type="text" name="cid_1" placeholder="cid1">
<input type="text" name="cid_2" placeholder="cid2">
<input type="submit" value="Register" name="submit" />
</form>
I've created insert.php as below. I just needed to type for each inputs but actually inputs will be added dynamically as I said, so I just need to apply while or foreach function I guess but I'm not that sure how to do, hope someone there can help me about this.
One more thing I need, In this case everything is working but it inserts everytime even if some inputs are empty. I could not found anything about this too.
Thank you for your help from now.
<?php
$link = mysqli_connect("localhost", "root", "", "test");
$uid = mysqli_real_escape_string($link, $_POST['uid']);
$cid1 = mysqli_real_escape_string($link, $_POST['cid_1']);
$cid2 = mysqli_real_escape_string($link, $_POST['cid_2']);
$sql = "INSERT INTO table (uid, cid) VALUES ('$uid', '$cid1'), ('$uid', '$cid2')";
mysqli_query($link, $sql)
?>
From your SQL query I understood that under uid, you are storing dynamic "cid" values from input. So you are adding dynamic input fields for "cid".
In order to capture dynamic fields on server, you have to name your input fields as given below which will be posted as an array on server.
<input type="text" name="cid[]" placeholder="cid1">
Next you will loop through that array and save each input data in your table.
Complete code:
HTML
<form action="insert.php" method="post">
<input type="text" name="uid" placeholder="uid">
<input type="text" name="cid[]" placeholder="cid1">
<input type="text" name="cid[]" placeholder="cid2">
<input type="submit" value="Register" name="submit" />
PHP
$mysqli = new mysqli('localhost','usename','password','table');
$uid = $mysqli->real_escape_string($_POST['uid']);
if($uid !== ''){
if(isset($_POST["cid"]) && is_array($_POST["cid"])){
foreach ($_POST["cid"] as $key => $value) {
$value = $mysqli->real_escape_string($value);
if($value !== ''){
// insert into table
$insert_row = $mysqli->query("INSERT INTO test ( uid, cid ) VALUES( '$uid', '$value' )");
}
else{
echo ($key+1)." no cid field is empty";
break;
}
}
}
}
else
echo "uid is empty";

How to validate the username textfield in a form in php

I want to check in the username text field to be typed only letters how can i do it in PHP? Plus in the password area to input both letters and numbers. When I click the Register button it displays Successful Registration although the form is not filled and I also put an else statement to display a message to fill all the fields.
the form
<form action = "register.php" method = "POST">
Username: <input type="text" name="username" > <br /><br/>
Password: <input type="password" name="password"> <br /><br/>
Confirm Password: <input type="password" name="repassword"> <br /><br/>
Type:
<select name="type">
<option value="Choose">Please select..</option>
<?php
$sql=mysql_query("SELECT type FROM type");
while($row=mysql_fetch_array($sql)){
echo "<option value='".$row['type']."'>".$row['type']."</option>";
}
?>
</select><br/><br/>
<input type="submit" value="Register" name="submit">
</form>
the register code
<?php
require('connect.php');
$username=$_POST['username'];
$password=$_POST['password'];
$repass=$_POST['repassword'];
$type=$_POST['type'];
if (isset($_POST['submit'])){
//input only letters in username textfield
if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['type'])){
$sql = "INSERT INTO users (username, password, type) VALUES ('$username', '$password', '$type')";
$result = mysql_query($sql);
echo "Successful Registration";
}
if(!$result){
$msg = "User Failed to be Registered.";
}
}
else{
echo "Please fill all the fields.";
}
?>
don't validate the userinput with the isset() function. Instead use !empty().
Because isset() also returns true if the POST variable is an empty string.
Also be careful with your SQL-Query (SQL-Injection), you have to escape the $_POST inputs.
You can use this code
$username = real_escape_string ($_POST['username']);
$password = real_escape_string ($_POST['password']);
$type = real_escape_string($_POST['type']); //if type is int, use intval() to escape
BTW: you don't validate the password against the repassword.

POST REDIRECT GET in form that submits to itself duplicate entries in database

I am having the hardest time of my life for not understanding the basics of the POST REDIRECT GET pattern in forms that submit to themselves.
The main problem is that when the user goes back or refreshes the page, I get duplicate entries in the database
So basically I have a page that contains two forms, each one submits to itself.
I have some code implemented regarding the PRG pattern but it doesn't seem to work.
I'll post a brief example where I'll try to explain what I am doing.
<?php
function saveUser1($UserName_1)
{
include 'db_conn.php';
//MySQL code etc...
if($result) return 1; //registro correcto
else return -2; //error
header('Location: samepage.php' , true, 303);
exit();
}
function saveUser2($UserName_2)
{
include 'db_conn.php';
//MySQL code etc...
if($result) return 1; //registro correcto
else return -2; //error
header('Location: samepage.php' , true, 303);
exit();
}
$error1 = 0;
$error2 = 0;
if(isset($_POST['userForm1']))
{
$error1 = saveUser1(clean_form($_POST['txtUserName_1']);
}
if(isset($_POST['userForm2']))
{
$error2 = saveUser2(clean_form($_POST['txtUserName_2']);
}
?>
Now the HTML
<form action="" name="userForm1" method="POST">
<label for="data">Some Data</label>
<input type="text" value="some test data to post" name="txtUserName_1" id="txtUserName_1" /><br />
<input type="submit" name="userForm1" id="userForm1"/>
</form>
<form action="" name="userForm2" method="POST">
<label for="data">Some Data</label>
<input type="text" value="some test data to post" name="txtUserName_2" id="txtUserName_2" /><br />
<input type="submit" name="userForm2" id="userForm2"/>
</form>
I just created this code in example of what I am trying to accomplish, but I haven't had any luck with the PGR pattern.
Could you guys tell me where the error is? Or redirect me (no kidding) to some good tutorial regarding this subject?
I have been looking to a lot of questions / answers, blogs but I can't find anything really solid (from my point of view).
Thanks in advance.
Below is sample code if you want try.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
Password: <input type="password" name="password">
<input type="submit" value="submit" name="send">
</form>
PHP Code and common.php is database connection file
<?php
require_once "common.php";
if(isset($_REQUEST['send']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$check = "SELECT * FROM user WHERE name = '".$name."' AND email = '".$email."' AND password = '".$password."'";
$check_result = mysql_query($check) or die(mysql_error());
if(mysql_num_rows($check_result) > 0)
{
header('Location : post.php');
}
else
{
$sql = "INSERT INTO user (name,email,password) VALUES ('$name','$email','$password')";
$result = mysql_query($sql) or die(mysql_error());
}
}
?>
Instead of checking for the form name itself check for a unique field within the form. E.g. If(isset($_POST[txtUserName_1'']))
The form name itself won't exist in the post.
To see what gets posted try:
print_r($_POST);
exit;
Maybe you have to set the post action to the same page.
And your form should not have the same name as your submit buttons(not sure about that).
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<label for="data">Some Data</label>
<input type="text" value="some test data to post" name="data" id="data" /><br />
<input type="submit" name="submit1" id="userForm1"/>
</form>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" name="form2" method="POST">
<label for="data">Some Data</label>
<input type="text" value="some test data to post" name="data" id="data" /><br />
<input type="submit" name="submit2" id="userForm2"/>
</form>
For the php:
if(isset($_POST['submit1']))
{
$error1 = saveUser1(clean_form($_POST['txtUserName_1']);
}
if(isset($_POST['submit2']))
{
$error1 = saveUser1(clean_form($_POST['txtUserName_2']);
}
you can add a hidden field for checking if its executed:
<input type="hidden" name="executed" value="0"/>
then you can set it to 0 when you have executed the mysql query
function saveUser1($UserName_1)
{
if($_POST['executed'] == 0)
{
include 'db_conn.php';
//MySQL code etc...
if($result) $_POST['executed'] = 1; //registro correcto
header('Location: samepage.php' , true, 303);
exit();
}
}

PHP email subscription validation and check for existing

I am creating an email subscription form in PHP and want to check for a valid address as well as if the email is already existing in my database.
My code is connecting to my database and inserting but the validation as well as checking for an existing email are not working.
No matter what I type into my form it inserts it into my database even if I don't type anything.
Here is all of my code:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset>
<legend>Subscribe to Our Newsletter </legend>
<?php if ($feedback!='')
echo('<p>'.$feedback.'</p>'); ?>
<label>Name: <input name="name" type="text" value="<?php echo $name; ?>" /></label>
<label>Email: <input name="email" type="text" value="<?php echo $email; ?>" /></label>
<label><input type="submit" value="Sign Up!" /></label>
</fieldset>
</form>
<?php
$feedback='';
if (!$email) {
$feedback .= '<strong>Please enter your email address</strong><br />';
}
if (!$name) {
$feedback .= '<strong>Please enter your name</strong><br />';
}
list($username, $mailDomain) = explode("#", $email);
if (!#checkdnsrr($mailDomain, "MX")) {
$feedback .= '<strong>Invalid email domain</strong><br />';
}
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email)) {
$feedback .= '<strong>Your email address doesn\'t appear to be valid - please check and try again';
}
function cleaninput($value, $DB) {
if (get_magic_quotes_gpc()) {
$value = stripslashes( $value );
}
return mysql_real_escape_string( $value, $DB );
}
$name=$_POST['name'];
$email=$_POST['email'];
include_once "connect.php";
$sql = mysql_query("SELECT * FROM subscribers WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if ($numRows>0) {
$feedback = '<strong>That email address is already subscribed.</strong>';
}
$insertresult = mysql_query("INSERT INTO subscribers (name, email) VALUES('$name', '$email')") or die (mysql_error());
if ($insertresult) {
$completed = true;
}
if($competed=false) {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?> method="post">
<fieldset>
<legend>Subscribe to OUr Newsletter </legend>
<?php
if ($feedback!='')
echo('<p>'.$feedback.'</p>'); ?>
<label>Name: <input name="name" type="text" value="<?php echo $name; ?>" /></label>
<label>Email: <input name="email" type="text" value="<?php echo $email; ?>" /></label>
<label><input type="submit" value="Sign Up!" /></label>
</fieldset>
</form>
<?php
}
else {
echo('Thanks - you have subscribed to our newsletter successfully. You can unsubscribe at any time by clicking the link at the bottom of each email we send.');
}
?>
Also the last echo in my script is always there. It is displayed under my my form always. Not sure why that is. Maybe I have it in the wrong place in my code.
else {
echo('Thanks - you have subscribed to our newsletter successfully. You can unsubscribe at any time by clicking the link at the bottom of each email we send.');
}
Thanks!
This code is a bit of a mess, to be honest :) It's slightly difficult to read, but I can see at least two problems: you write $competed rather than $completed in one of your if statements, and you don't actually have the INSERT query in an if block: it'll always execute. Try putting it in an else block after the if block that checks whether the address is already in your database, like this:
$sql = mysql_query("SELECT * FROM subscribers WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if ($numRows>0) {
$feedback = '<strong>That email address is already subscribed.</strong>';
}
else {
$insertresult = mysql_query("INSERT INTO subscribers (name, email) VALUES('$name', '$email')") or die (mysql_error());
}
You also don't need to use both addslashes and mysql_real_escape_string; just the latter will do. And I'm not sure why you have the same form in your code twice. Surely once should do? :)

Categories