Multiple page PHP form elements not being updated in MySQL - php

I've read lots of pages but all seem to say different things and are not direct to my question. I am fairly new at using PHP and MySQL.
I am using PHP sessions for a 3 page form and want to insert the form data into my database. My sessions for the form pages are working in printing the results, however, only the last page's data is being entered into the database. I find no errors except when trying to use mysql_real_escape_string, which will be my next step/challenge – but I want to ensure I have the form working with the database properly first, so that I can understand where my errors are coming from without being overwhelmed.
Here is my code:
form1.php
<form method="post" action="form2.php">
<p>Name:
<input type="text" name="name">
</p>
<p>Email address
<input type="text" name="emailaddress">
<input type="submit" value="Go To Step 2">
</p>
</form>
form2.php
<?php
//start the session
session_start();
?>
<?php
// defining variables
$_SESSION['name'] = $name;
$_SESSION['emailaddress'] = $emailaddress;
//store posted values in the session variables
$_SESSION['name'] = $_POST['name'];
$_SESSION['emailaddress'] = $_POST['emailaddress'];
?>
<form method="post" action="form3.php">
<p>Male
<input type="radio" name="gender" value="Male">
Female
<input type="radio" name="gender" value="Female">
</p>
<p>Age:
<input type="text" name="age">
</p>
<p>Location:
<input type="text" name="location">
<input type="submit" value="Go To Step 3">
</p>
</form>
form3.php
<?php
//start the session
session_start();
?>
<?php
// defining variables
$_SESSION['gender'] = $gender;
$_SESSION['age'] = $age;
$_SESSION['location'] = $location;
//store posted values in the session variables
$_SESSION['gender'] = $_POST['gender'];
$_SESSION['age'] = $_POST['age'];
$_SESSION['location'] = $_POST['location'];
?>
<form method="post" action="pageprocess.php">
<p>Employment status:
<input type="text" name="employmentstatus">
</p>
<p>Hobbies:
<input type="text" name="hobbies">
<input type="submit" value="Finish">
</p>
</form>
pageprocess.php
<?php
session_start();
$userid = $_SESSION['userid'];
$name = $_SESSION['name'];
$emailaddress = $_SESSION['emailaddress'];
$gender = $_SESSION['gender'];
$age = $_SESSION['age'];
$location = $_SESSION['location'] ;
$employment_status = $_SESSION['employmentstatus'];
$hobbies = $_SESSION['hobbies'];
?>
<?php
$con=mysqli_connect("localhost","username","password","databasename");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO userinfo (
userid,
name,
emailaddress,
gender,
age,
location,
employmentstatus,
hobbies
)
VALUES
( '" . $_POST[userid] . "',
'" . $_POST[name] . "',
'" . $_POST[emailaddress] . "',
'" . $_POST[gender] . "',
'" . $_POST[age] . "',
'" . $_POST[location] . "',
'" . $_POST[employmentstatus] . "',
'" . $_POST[hobbies] . "'
)";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
There is a lot of conflicting information out there and I need some clarity.

In the values they need to be the variables you have set from the $_SESSION, not the $_POST
"VALUES
( '" . $userid . "',
'" . $name . "',
'" . $emailaddress . "',
'" . $gender . "',
'" . $age . "',
'" . $location . "',
'" . $employment_status . "',
'" . $hobbies . "'
)";
Also why are you defining the session variables? You don't need to do that. :)

one thing i do is the following:
foreach ($_POST as $key => $value)
{
$_SESSION[$key] = $value;
}
this will take each post and assign it automatically instead of you defining whats already defined.
this part is problematic:
// defining variables
$_SESSION['name'] = $name;
$_SESSION['emailaddress'] = $emailaddress;
those variables are empty. and then next lines you set them...
you never set the employmentstatus variable in the session array anywhere.
on pageprocess.php your values are POST values, those are empty. you should be using the session variables you set earlier. you also need to look into prevent mysql injection.

Related

PHP/HTML to populate a text input with a value from database on load, but write the new value to DB without appearing in URL?

I have two little bits of code doing the work here:
HTML:
<form action="http://mypage.php">
<input type="text" name="AnswerArea" ID="AnswerArea" value="' . $this_answer . '" />
<input type="hidden" name="Q" value="' . $NextQ . '" />
<input type="hidden" name="P" value="' . $quest . '" />
<input type="hidden" name="ref" value="' . $ref . '" /><br><br>
<input class="button" name="submit" type="submit" value="Next" />
</form>
And the PHP:
<?php if ($AStyle != 'None'){
if(array_key_exists('AnswerArea', $_GET)) {
include 'connection.php';
$newanswer = $_GET['AnswerArea'];
$newSQL = 'UPDATE answers SET Q' . $prev . '="' . $newanswer . '" WHERE strRef="' . $ref . '"';
if (mysqli_query($mysqli, $newSQL)) {
echo 'Successful, comment out when ready';
}
mysqli_close($mysqli);
}
}
?>
The intention is that when submit is clicked the Q, P & ref values are in the URL and the new value of $this_answer is written to the database. However, the input submit and AnswerArea variables are appearing in there as well. I know you can't have GET and POST in the same form, so how should I go about doing this?
The AnswerArea variable could be longer than the permissible URL length so I want to avoid it getting passed as an address.
Any help gratefully received!

PHP update table in MySQL not working

My php won't update my products table. I know my GET request worked as I tested it with echo to display the id. I am confused as to how I can get it to work? I think it may be something to do with the form action= on my form but I am confused! Can someone please help?
<?php
// Connection file
require 'db.php';
if (((!empty($_GET["mode"])) && (!empty($_GET["id"]))) && ($_GET["mode"] == "update")) {
// If update
echo $_GET['id'];
if (isset($_POST["updateSubmit"])) {
$pName = $_POST["updateProductName"];
echo $pName;
$query = "UPDATE products "
. "SET p_name = '" . $_POST["updateProductName"] . "', "
. "p_type = '" . $_POST["updateProductType"] . "', "
. "p_desc = '" . $_POST["updateProductDesc"] . "', "
. "p_price = '" . $_POST["updateProductPrice"] . "', "
. "p_stock = " . $_POST["updateProductStock"] . ", "
. "WHERE id=" . $_GET['id'] . ";";
$result = mysqli_query($conn, $query);
}
}
?>
<div>
<form id="updateForm" name="updateForm" action="<?php echo "?mode=update&id=" . $productDetails["id"]; ?>" method="post">
<label>Product name:</label><br>
<input type="text" name="updateProductName"><br>
<label>Product type</label><br>
<select name="updateProductType">
<option value="Jackets/coats">Jackets/coats</option>
<option value="Accessories">Accessories</option>
<option value="Shirts">Shirts</option>
<option value="Jeans">Jeans</option>
<option value="Trousers">Trousers</option>
<option value="Shoes">Shoes</option>
<option value="Suits">Suits</option>
</select>
<p>Product description:</p>
<textarea name="updateProductDesc" rows="10" cols="30"></textarea><br>
<label>Product price:</label><br>
<input type="text" name="updateProductPrice"><br>
<label>Stock level:</label><br>
<input type="text" name="updateProductStock"><br>
<input type="submit" name="updateSubmit" value="Submit">
</form>
</div>
<?php
?>
I think the problems are misusing of ' in one or both of these lines
. "p_price = '" . $_POST["updateProductPrice"] . "', "
. "p_stock = " . $_POST["updateProductStock"] . ", "
If the type is string you need to use ' as you used in p_price otherwise if it is float or int you should not use ' as you did for p_stock.
It seems you used wrong for these two field. Since the p_price would be float and p_stock is string.
. "p_price = " . $_POST["updateProductPrice"] . ", "
. "p_stock = '" . $_POST["updateProductStock"] . "' , "
There are two issues with your query...
You Have one extra comma before the Where Section and your missing delimeters on p_stock.
Should be:
"p_stock = '" . $_POST["updateProductStock"] . "' "
and
. "WHERE id='" . $_GET['id'] . "'";

mysql update script

Anyone who can point a php novice in the right direction? It won't update the database and I can't figure it out. I get the article that I want to change and put it a form, and use the "update1.php" file to update the database.
Getting the article:
<?php
include ('../db_connect.php');
$getid = $_GET['artikkelID'];
$query = mysql_query('SELECT tittel, ingress, publ, tekst, forfatter, bildetekst, photo FROM hovedartikler WHERE artikkelID = "' . $getid . '"');
$rows = mysql_fetch_assoc($query);
$titteldb = $rows['tittel'];
$ingressdb = $rows['ingress'];
$tekstdb = $rows['tekst'];
$forfatterdb = $rows['forfatter'];
$bildetekstdb = $rows['bildetekst'];
$photodb = $rows['photo'];
echo '<form action="update1.php" method="post" enctype="multipart/form-data">
<span>
ArtikkelID
<input type="text" name="artikkelID" readonly="readonly" size="3" value="' . $getid . '">
</span>
<span style="margin-left: 20px;">
Artikkelens Tittel ( maks 100 tegn)
<input type="text" name="tittel" cols="80" size="50" value="' . $titteldb . '" /><br />
</span>
<br />
Ingress (maks 255 tegn)<br />
<textarea name="ingress" rows="4" cols="60" />' . $ingressdb . '</textarea><br />
Artikkelens tekst (ingen begrensning på antall tegn)<br />
<textarea id="textarea1" name="tekst" size="100%">' . $tekstdb . '</textarea>
<script language="javascript1.2">
generate_wysiwyg("textarea1");
</script>
Skriv inn artikkelens forfatter (maks 50 tegn)<br />
<input type="text" name="forfatter" size="80" cols="80" value="' . $forfatterdb . '" /><br />
Skriv inn tekst til artikkel-bilde<br />
<textarea name="bildetekst" rows="3" cols="60">' . $bildetekstdb . '</textarea><br />
Last opp bilde til bruk i artikkelen<br />
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input type="file" name="file" size="80" value="' . $photodb . '" /><br />
<br />
<input type="submit" name="submit" value="Oppdater" />
</form>';
?>
And the update-script:
<?php
$id = $_POST['artikkelID'];
$tittel = $_POST['tittel'];
$ingress = $_POST['ingress'];
$tekst = $_POST['tekst'];
$forfatter = $_POST['forfatter'];
$bildetekst = $_POST['bildetekst'];
$pic = $_FILES['file']['name'];
include '../db_connect.php';
if(isset($_POST['Oppdater']))
$mysql_query=("UPDATE hovedartikler SET
tittel='" . $_POST['tittel'] . "', ingress='" . $_POST['ingress'] . "', tekst='" . $_POST['tekst'] . "', forfatter='" . $_POST['forfatter'] . "', bildetekst='" . $_POST['bildetekst'] . "', file='" . $_FILES['pic'] . "' WHERE artikkelID='$id'")
or die (mysql_error());
mysql_query($query);
echo "Artikkelen er oppdatert!<br/><br/>
Du vil nå automatisk bli dirigert til Admin-forsiden.";
print_r($ingress);
mysql_close();
?>
<script type="text/javascript">
setTimeout("window.location.href='http://mss-seil.no/admin/adminIndex.php'", 3000);
</script>
All help appreciated!
For a start stop using mysql_* functions and start using mysqli or PDO and prepared statements with bound values or you will face SQL injection attacks.
Secondly, for now change mysql_query($query) to mysql_query($mysql_query) and remove the brackets from around the actual query and the die statement when setting the variable. You are trying to run the query held in $query but the UPDATE query is actually held in $mysql_query
It should look more like this:
$mysql_query = "UPDATE hovedartikler SET
tittel='" . $_POST['tittel'] . "', ingress='" . $_POST['ingress'] . "', tekst='" . $_POST['tekst'] . "', forfatter='" . $_POST['forfatter'] . "', bildetekst='" . $_POST['bildetekst'] . "', file='" . $_FILES['pic'] . "' WHERE artikkelID='$id'";
mysql_query($mysql_query);
$mysql_query=("UPDATE hovedartikler SET tittel='" . $_POST['tittel'] . "', ingress='" . $_POST['ingress'] . "', tekst='" . $_POST['tekst'] . "', forfatter='" . $_POST['forfatter'] . "', bildetekst='" . $_POST['bildetekst'] . "', file='" . $_FILES['pic'] . "' WHERE artikkelID='$id'") or die (mysql_error());
Note it's "$mysql_query" not "$query".
mysql_query($mysql_query);
Just a few side notes too:
the mysql_* functions should not really be used now. Take a look at mysqli or PDO.
You are not sanitizing your input before inserting it into the database. This is not a good idea - you're leaving yourself wide open to SQL injection attacks. You should escape strings and cast integers as integers. If you follow the first suggestion and use PDO or mysqli, look into using prepared statements.
Hope that helps!
Please look for SQL-Injections and escape your values from $_POST, please :) - And the Javascript-redirect can be replaced with a server-sided PHP-redirect with "header", I guess.
$mysql_query=("UPDATE hovedartikler SET
tittel='" . $_POST['tittel'] . "', ingress='" . $_POST['ingress'] . "', tekst='" . $_POST['tekst'] . "', forfatter='" . $_POST['forfatter'] . "', bildetekst='" . $_POST['bildetekst'] . "', file='" . $_FILES['pic'] . "' WHERE artikkelID='$id'")
or die (mysql_error());
mysql_query($query);
You've got a variable "$mysql_query" with the Update-Statement. But you send a variable "$query" to the mysql_query function. Shouldn't you send the $mysql_query variable to the mysql_query function? Maybe better variable names could be helpful :)
I do not know if this is the cause but you are using different quotes in the two files.
In the getting:
"' . $getid . '"'
And in the setting
WHERE artikkelID='$id'"
What datatype is artikkelID?
If it is an int, the first will work as double quote is not a string quote but a "grouping" quote which can be used to have columns with reserved words names
The last will not work as single quote IS a string quote, and you cannot use string for an int column.
For example
I could query an int column like this
WHERE id > "20"
but not like this
WHERE id > '20'
Whereas for a string column
WHERE name = "Hello World"
Would try to match the name column with the Hello World column, not the Hello World string

Insert into value of Radio button

I am trying to insert the value of a radio button when its checked into mysql db table. Below is the HTML and the PHP for doing so. Please let me know what is going wrong?
Here is the HTML first:
<div class='container'>
<label for='username' >Business*:</label><br/>
<input type="radio" name="bus" id="username" value="bus" maxlength="50" /><br/>
<span id='register_username_errorloc' class='error'></span>
</div>
<div class='container'>
<label for='username' >Personal*:</label><br/>
<input type="radio" name="pers" id="username" value="per" maxlength="50" /><br/>
<span id='register_username_errorloc' class='error'></span>
</div>
Now the PHP:
function InsertIntoDB(&$formvars)
{
$confirmcode = $this->MakeConfirmationMd5($formvars['email']);
$formvars['confirmcode'] = $confirmcode;
$insert_query = 'insert into '.$this->tablename.'(
name,
email,
username,
password,
confirmcode,
dob,
business,
personal
)
values
(
"' . $this->SanitizeForSQL($formvars['name']) . '",
"' . $this->SanitizeForSQL($formvars['email']) . '",
"' . $this->SanitizeForSQL($formvars['username']) . '",
"' . md5($formvars['password']) . '",
"' . $confirmcode . '",
"' . $this->SanitizeForSQL($formvars['dob']) . '",
"' . $this->SanitizeForSQL($formvars['bus']) . '",
"' . $this->SanitizeForSQL($formvars['pers']) . '"
)';
if(!mysql_query( $insert_query ,$this->connection))
{
$this->HandleDBError("Error inserting data to the table\nquery:$insert_query");
return false;
}
return true;
}
I think there is a logical error. You should only save one of the variable in radio button in database.
"' . $this->SanitizeForSQL($formvars['bus']) . '",
"' . $this->SanitizeForSQL($formvars['pers']) . '"

Problem with my registration form. Not inserting second query

First of all sorry for my language. I am a doing a shopping cart application for my assignment for college. I have a problem with registration for. The problem is that it is inserting the first query
$addsql = "INSERT INTO customers(forename, surname, add1, add2, add3, postcode, phone, email, registered)
VALUES('"
. strip_tags(addslashes($_POST['forenameBox'])) . "', '"
. strip_tags(addslashes($_POST['surnameBox'])) . "', '"
. strip_tags(addslashes($_POST['add1Box'])) . "', '"
. strip_tags(addslashes($_POST['add2Box'])) . "', '"
. strip_tags(addslashes($_POST['add3Box'])) . "', '"
. strip_tags(addslashes($_POST['postcodeBox'])) . "', '"
. strip_tags(addslashes($_POST['phoneBox'])) . "', '"
. strip_tags(addslashes($_POST['emailBox'])) . "',
1)";
mysql_query($addsql);
and it does not insert the second one.
$customer_id = mysql_insert_id(); // Gets The id Of Last MySql INSERT Query
$insert_query = 'INSERT INTO logins (
username,
password,
customer_id
)
VALUES
(
"' . $_POST['userregBox'] . '",
"' . md5($_POST['passregBox']) . '",
"' . $customer_id . '",
)';
mysql_query($insert_query);
header("Location: " . $basedir . "login.php?ok=1");
I tried different approaches with no result. I am using Xammp.
Here is the full code
<?php
session_start();
require_once("db.php");
/* Checking if user is logged in, if not redirecting to the main page */
if(isset($_SESSION['SESS_LOGGEDIN']) == TRUE) {
header("Location: " . $config_basedir);
}
if($_POST['login'])
{
$loginsql = "SELECT * FROM logins
WHERE username = '" . $_POST['userBox'] . "' AND password = '" . $_POST['passBox'] . "'";
$loginres = mysql_query($loginsql);
$numrows = mysql_num_rows($loginres);
if($numrows == 1)
{
$loginrow = mysql_fetch_assoc($loginres);
session_register("SESS_LOGGEDIN");
session_register("SESS_USERNAME");
session_register("SESS_USERID");
$_SESSION['SESS_LOGGEDIN'] = 1;
$_SESSION['SESS_USERNAME'] = $loginrow['username'];
$_SESSION['SESS_USERID'] = $loginrow['id'];
$ordersql = "SELECT id FROM orders WHERE customer_id = " . $_SESSION['SESS_USERID'] . " AND status <2";
$orderres = mysql_query($ordersql);
$orderrow = mysql_fetch_assoc($orderres);
session_register("SESS_ORDERNUM");
$_SESSION['SESS_ORDERNUM'] = $orderrow['id'];
header("Location: " . $config_basedir);
}
else
{
header("Location: http://" . $HTTP_HOST . $SCRIPT_NAME . "?error=1");
}
}
if($_POST['register'])
{
$loginchecksql = "SELECT * FROM logins
WHERE username = '" . $_POST['userBox'] . "'";
$logincheckres = mysql_query($loginchecksql);
$loginchecknumrows = mysql_num_rows($logincheckres);
if($loginchecknumrows == 1)
{
header("Location: http://" . $HTTP_HOST . $SCRIPT_NAME . "?error=3");
}
else{
if(empty($_POST['forenameBox']) ||
empty($_POST['surnameBox']) ||
empty($_POST['add1Box']) ||
empty($_POST['add2Box']) ||
empty($_POST['add3Box']) ||
empty($_POST['postcodeBox']) ||
empty($_POST['phoneBox']) ||
empty($_POST['userregBox']) ||
empty($_POST['passregBox']) ||
empty($_POST['emailBox']))
{
header("Location: " . $basedir . "login.php?error=2");
exit;
}
$addsql = "INSERT INTO customers(forename, surname, add1, add2, add3, postcode, phone, email, registered)
VALUES('"
. strip_tags(addslashes($_POST['forenameBox'])) . "', '"
. strip_tags(addslashes($_POST['surnameBox'])) . "', '"
. strip_tags(addslashes($_POST['add1Box'])) . "', '"
. strip_tags(addslashes($_POST['add2Box'])) . "', '"
. strip_tags(addslashes($_POST['add3Box'])) . "', '"
. strip_tags(addslashes($_POST['postcodeBox'])) . "', '"
. strip_tags(addslashes($_POST['phoneBox'])) . "', '"
. strip_tags(addslashes($_POST['emailBox'])) . "',
1)";
mysql_query($addsql);
$customer_id = mysql_insert_id(); // Gets The id Of Last MySql INSERT Query
$insert_query = 'INSERT INTO logins (
username,
password,
customer_id
)
VALUES
(
"' . $_POST['userregBox'] . '",
"' . md5($_POST['passregBox']) . '",
"' . $customer_id . '",
)';
mysql_query($insert_query);
header("Location: " . $basedir . "login.php?ok=1");
}
}
else
{
require_once("header.php");
?>
<?php
if($_GET['ok'] == 1) {
echo "<b>Your registration was succesfull</b><p>Start shooping now</p>";
}
else
{
?>
<?php
if($_GET['error'] == 1) {
echo "<b>Incorrect details, please try again</b>";
}
?>
<?php
if($_GET['error'] == 2) {
echo "<b>Please fill all fields</b>";
}
?>
<?php
if($_GET['error'] == 3) {
echo "<b>User name exist</b>";
}
?>
<div style="width:50%;float:left;">
<fieldset style="width:90%;background:#fff; ">
<legend>Customer Login</legend>
<form action="<?php echo $SCRIPT_NAME; ?>" method="POST">
<ul>
<li>
<fieldset>
<legend>Username</legend>
<div>
<input type="textbox" name="userBox" class="text" />
</div>
<p class="guidelines">Please enter your username</p>
</fieldset>
</li>
<li>
<fieldset>
<legend>Password</legend>
<div>
<input type="password" name="passBox" class="text" />
</div>
<p class="guidelines">Please enter your password</p>
</fieldset>
</li>
<li>
<button type="submit" name="login" value="login">Log In</button>
</li>
</ul>
</form>
</fieldset>
</div>
<div style="width:50%;float:right;">
<fieldset style="width:95%;background:#fff; ">
<legend>Register</legend>
<form action="<?php echo $SCRIPT_NAME; ?>" method="POST">
<ul>
<li>
<fieldset>
<legend>Username</legend>
<div>
<input type="textbox" name="userregBox" class="text" />
</div>
<p class="guidelines">Please enter your username</p>
</fieldset>
</li>
<li>
<fieldset>
<legend>Password</legend>
<div>
<input type="password" name="passregBox" class="text" />
</div>
<p class="guidelines">Please enter your password</p>
</fieldset>
</li>
<li>
<fieldset>
<legend>Delivery details</legend>
<table style="width:99%;">
<tr>
<td>Forename</td>
<td><input type="text" name="forenameBox" class="text"></td>
</tr>
<tr>
<td>Surname</td>
<td><input type="text" name="surnameBox" class="text"></td>
</tr>
<tr>
<td>House Number, Street</td>
<td><input type="text" name="add1Box" class="text"></td>
</tr>
<tr>
<td>Town/City</td>
<td><input type="text" name="add2Box" class="text"></td>
</tr>
<tr>
<td>County</td>
<td><input type="text" name="add3Box" class="text"></td>
</tr>
<tr>
<td>Postcode</td>
<td><input type="text" name="postcodeBox" class="text"></td>
</tr>
<tr>
<td>Phone</td>
<td><input type="text" name="phoneBox" class="text"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="emailBox"class="text"></td>
</tr>
</table>
</fieldset>
</li>
<li>
<button type="submit" name="register" value="Register">Register</button>
</li>
</ul>
</form>
</fieldset>
</div>
<?php
}
}
require_once("footer.php");
?>
You have an extra comma.
Change
"' . $customer_id . '",
to
"' . $customer_id . '"
in your INSERT INTO LOGINS query.

Categories