Cannot set email variable from session so mail() function nto working - php

I'm very new to php and sql and I'm trying to set a _SESSION variable for my user_email, I know that the column name is correct and I'm pulling the other information from the session like the user_id etc correctly but cannot seem to get the email to set even though I've done it the same as my other variables. I'm also trying to use the mail() function but I'm not sure if this is set up correctly? Any help would be really appreciated!
I've tried doing the variable as a _POST one using a hidden input but that hasn't worked either.
<div>
<?php
if (isset($_POST['request_date'])) {
$user_email = $_SESSION['user_email'];
$user_id = $_SESSION['user_id'];
$first_name = $_SESSION['first_name'];
$last_name = $_SESSION['last_name'];
// $request_time = date("d-m-Y H:i:s");
$lend_status = 1;
$requested_start_date = date('Y-m-d H:i:s', strtotime($_POST['requested_start_date'] . ' ' . $_POST['requested_start_time'] . ':00:00'));
$requested_end_date = date('Y-m-d H:i:s', strtotime($_POST['requested_end_date'] . ' ' . $_POST['requested_end_time'] . ':00:00'));
$comments = $_POST['comments'];
// Declare available laptops array
$available_laptops = array();
// GET ALL LAPTOPS IN OPERATION
$STH = $DBH->prepare("
SELECT laptop_id,
laptop_name
FROM laptops
WHERE 1
");
$STH->execute(array());
while ($row = $STH->fetch()) {
// CHECK EACH LAPTOP FOR THE REQUESTED DATES
$STH2 = $DBH->prepare("
SELECT lend_id
FROM laptop_system
WHERE (
(
approved_start_date <= ?
AND approved_end_date >= ?
) OR (
approved_start_date <= ?
AND approved_end_date >= ?
) OR (
approved_start_date >= ?
AND approved_end_date <= ?
)
)
AND laptop_id = ?
");
$STH2->execute(array(
$requested_start_date,
$requested_start_date,
$requested_end_date,
$requested_end_date,
$requested_start_date,
$requested_end_date,
$row->laptop_id
));
// IF IT'S NOT BOOKED OUT, ADD TO ARRAY
if ($STH2->rowCount() < 1) {
$available_laptops[$row->laptop_id] = $row->laptop_name;
}
}
if (empty($available_laptops)) {
echo '<h3>Sorry, this date is not available.</h3>';
} else {
$STH = $DBH->prepare("
INSERT INTO laptop_system (
user_id,
first_name,
last_name,
lend_status,
requested_start_date,
requested_end_date,
comments
)
VALUES(?, ?, ?, ?, ?, ?, ?)
");
$STH->execute(array(
$user_id,
$first_name,
$last_name,
$lend_status,
$requested_start_date,
$requested_end_date,
$comments
));
echo '<h2 style="color:#D80B8C; margin-bottom:1em;">' . $first_name . ', your laptop request is now pending approval.</h2>';
$to = $user_email;
$subject = "Laptop Request";
$message = "Thank you for your laptop request for " . $requested_start_date . " - " . $requested_end_date . "It is now pending and you will be notified if it's been approved or declined.";
$message = wordwrap($message,70);
$headers = "From: Timmy and Edwardo";
mail($to,$subject,$txt,$headers);
}
} ?>
<form action="" method="post" >
<div>
<label for="requested_start_date"> Requested Start Date </label>
<input type="date" name="requested_start_date" value="<?php echo $requested_start_date; ?>">
<label for="requested_start_time">Requested start time </label>
<select name="requested_start_time" style="width:auto;margin:1em 1em 1em 0;">
<?php for ($i = 0; $i < 25; $i++) {$i = str_pad($i, 2, "0", STR_PAD_LEFT); ?>
<option value="<?php echo $i; ?>"><?php echo $i . ':00'; ?></option>
<?php } ?>
</select>
</div>
<div>
<label for="requested_end_date">Requested End Date </label>
<input type="date" name="requested_end_date" value="<?php echo $requested_end_date; ?>">
<label for="requested_end_time">Requested end time</label>
<select name="requested_end_time" style="width:auto;margin:1em 1em 1em 0;">
<?php for ($i = 0; $i < 25; $i++) {$i = str_pad($i, 2, "0", STR_PAD_LEFT); ?>
<option value="<?php echo $i; ?>"><?php echo $i . ':00'; ?></option>
<?php } ?>
</select>
</div>
<div>
<p style="margin-bottom:0;">
Please can you let us know below why you need the laptop and if there are any special requirements needed -
</p>
<input type="textarea" rows="4" cols="50" name="comments" placeholder="" required>
<input type="submit" name="request_date" value="Request Date">
<!-- <input type="hidden" name="user_email" value="<?php echo $user_email;?>" > -->
</div>
</form>
<?php
?>
</div>

Related

Getting form data from POST and inserting to mysqli database

Learning PHP and for my most recent assignment, I had to create an HTML form, use PHP for error checking, insert the data into a database using mysqli, and then retrieve the values and display them in a table. I turned the assignment in even though I didn't have it working 100%, but I'm just trying to figure out where I've gone wrong while waiting for feedback from my instructor. I've checked out several similar threads, but so far none of the solutions offered seem to work for me.
So far, my form works and it seems to redirect and connect to the database just fine. It also retrieves data already stored in the database and displays it in a table. But I can't for the life of me seem to get it to actually write the form data that gets submitted via POST. Regardless of what data is or is not entered on the form, when the submit button is clicked, it writes a blank row to my database, which should be prevented by my error-checking. So in addition Here's my code for the form:
<?php
include ("dbinfo.php");
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL & ~E_WARNING);
//declare variables
$errors = 0;
//if form is submitted
if ( isset($_POST['submit']) ) {
//store submitted values
$title = $_POST['title'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$street = $_POST['street'];
$city = $_POST['city'];
$province = $_POST['province'];
$postal = $_POST['postal'];
$country = $_POST['country'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
$newsletter = $_POST['newsletter'];
//error checking routine
if ( !isset($_POST[$title]) || empty($_POST[$title]) ) $errors = 1;
if ( !isset($_POST[$firstName]) || empty($_POST[$firstName]) ) $errors = 2;
if ( !isset($_POST[$lastName]) || empty($_POST[$lastName]) ) $errors = 3;
if ( !isset($_POST[$street]) || empty($_POST[$street]) ) $errors = 4;
if ( !isset($_POST[$city]) || empty($_POST[$city]) ) $errors = 5;
if ( !isset($_POST[$province]) || empty($_POST[$province]) ) $errors = 6;
if ( !isset($_POST[$postal]) || empty($_POST[$postal]) ) $errors = 7;
if ( !isset($_POST[$country]) || empty($_POST[$country]) ) $errors = 8;
if ( !isset($_POST[$phone]) || empty($_POST[$phone]) ) $errors = 9;
if ( !filter_var($email, FILTER_VALIDATE_EMAIL) === false ) $errors = 10;
if ( !isset($_POST[$email]) || empty($_POST[$email]) ) $errors = 11;
}
//if error flag is still 0
if ( $errors == 0 ) {
?>
<!-- display the form -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form</title>
</head>
<body>
<!-- if errors exist, display error message(s -->
<p>
<strong>Instructions:</strong> To complete your registration, please fill out the following form.
<?php if ($errors > 0) echo "<p><font color=red><strong>Please ensure all required fields are filled.</strong></font></p>"; ?>
</p>
<form action="" method="POST" enctype="multipart/form-data">
<label for="title" >Title</label>
<select name="title">
<option value="" <?php if (isset($title) && $title =="") echo "selected";?>></option>
<option value="Mr" <?php if (isset($title) && $title == "Mr") echo "selected";?>>Mr</option>
<option value="Mrs" <?php if (isset($title) && $title == "Mrs") echo "selected";?>>Mrs</option>
<option value="Ms" <?php if (isset($title) && $title =="Ms") echo "selected";?>>Ms</option>
<option value="Dr" <?php if (isset($title) && $title =="Dr") echo "selected";?>>Dr</option>
</select>
<?php if ( $errors > 0 && empty($title) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
<br />
<label for="firstName">First Name: </label>
<input type="text" name="firstName" placeholder="Jane" value="<?php echo isset($_POST["firstName"]) ? $_POST["firstName"] : ''; ?>">
<?php if ( $errors > 0 && empty($firstName) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
<br />
<label for="">Last Name: </label>
<input type="text" name="lastName" placeholder="Doe" value="<?php echo isset($_POST["lastName"]) ? $_POST["lastName"] : ''; ?>">
<?php if ( $errors > 0 && empty($lastName) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
<br />
<label for="">Street Address: </label>
<input type="text" name="street" placeholder="123 ABC Drive" value="<?php echo isset($_POST["street"]) ? $_POST["street"] : ''; ?>">
<?php if ( $errors > 0 && empty($street) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
<br />
<label for="">City: </label>
<input type="text" name="city" placeholder="Anytown" value="<?php echo isset($_POST["city"]) ? $_POST["city"] : ''; ?>">
<?php if ( $errors > 0 && empty($city) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
<br />
<label for="">Province: </label>
<input type="text" name="province" placeholder="Nova Scotia" value="<?php echo isset($_POST["province"]) ? $_POST["province"] : ''; ?>">
<?php if ( $errors > 0 && empty($province) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
<br />
<label for="">Postal Code:</label>
<input type="text" name="postal" placeholder="A1A 1A1" value="<?php echo isset($_POST["postal"]) ? $_POST["postal"] : ''; ?>">
<?php if ( $errors > 0 && empty($postal) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
<br />
<label for="country">Country: </label>
<select name="country">
<option value="" <?php if ( isset($country) && $country == "" ) echo "selected";?>></option>
<option value="canada" <?php if (isset($country) && $country == "canada") echo "selected";?>>Canada</option>
<option value="usa" <?php if (isset($country) && $country == "usa") echo "selected";?>>USA</option>
</select>
<?php if ( $errors > 0 && empty($country) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
<br />
<label for="phone">Phone Number: </label>
<input type="text" name="phone" placeholder="555-555-5555" value="<?php echo isset($_POST["phone"]) ? $_POST["phone"] : ''; ?>">
<?php if ( $errors > 0 && empty($phone) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
<br />
<label for="email">Email Address: </label>
<input type="text" name="email" placeholder="email#domain.com" value="<?php echo isset($_POST["email"]) ? $_POST["email"] : ''; ?>">
<?php if ( $errors > 0 && empty($email) ) echo " <font color='red'><strong>*required</strong></font>"; ?>
<br />
<label for="newsletter">Subscribe to our newsletter? </label>
<input type="checkbox" name="newsletter" value="1">
<br /><br />
<input name="submit" type="submit" value="submit">
</form>
</body>
</html>
<?php
} else {
//redirect to database
header("Location: regdatabase.php");
exit;
}
My dbinfo file only contains $db_host, $db_user, $db_pass, and $db_name. This is the code for the regdatabase.php.
<?php
include ("dbinfo.php");
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
//establish a DB connection to a specific database
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
//check for valid connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully. <br />";
//prepare and bind
$sql = "INSERT INTO registered_users (title, firstName, lastName, street, city, province, postal, country, phone, email, newsletter)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssssssssssi", $_REQUEST['title'], $_REQUEST['firstName'], $_REQUEST['lastName'], $_REQUEST['street'], $_REQUEST['city'], $_REQUEST['province'],
$_REQUEST['postal'], $_REQUEST['country'], $_REQUEST['phone'], $_REQUEST['email'], $_REQUEST['newsletter']);
$stmt->execute();
$stmt->close();
//retrieve values and display in table
$sql = "SELECT * FROM registered_users";
$results = mysqli_query($conn, $sql);
if ($results->num_rows > 0) {
echo "Data stored in database successfully.<br /><br />
<table><tr>
<th>User ID</th>
<th>Title</th>
<th>First Name</th>
<th>Last Name</th>
<th>Street Address</th>
<th>City</th>
<th>Province</th>
<th>Postal Code</th>
<th>Country</th>
<th>Phone Number</th>
<th>Email Address</th>
<th>Newsletter Sub</th>
</tr>";
while($row = mysqli_fetch_assoc($results)) {
echo "<tr><td>" . $row["user_id"]. "</td>" .
"<td>" . $row["title"]. "</td>" .
"<td>" . $row["firstName"]. "</td>" .
"<td>" . $row["lastName"]. "</td>" .
"<td>" . $row["street"]. "</td>" .
"<td>" . $row["city"]. "</td>" .
"<td>" . $row["province"]. "</td>" .
"<td>" . $row["postal"]. "</td>" .
"<td>" . $row["country"]. "</td>" .
"<td>" . $row["phone"]. "</td>" .
"<td>" . $row["email"]. "</td>" .
"<td>" . $row["newsletter"]. "</td></tr>";
}
echo "</table>";
} else {
echo "There are 0 results.";
}
mysqli_close($conn);
?>
A var_dump shows that all my variables are NULL. Blank records are being recorded in the database. I've also rewritten my bind statement in the following format, but had no luck with that either.
$title = $_POST['title'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$street = $_POST['street'];
$city = $_POST['city'];
$province = $_POST['province'];
$postal = $_POST['postal'];
$country = $_POST['country'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$newsletter = $_POST['newsletter'];
$stmt->bind_param("ssssssssssi", $title, $firstName, $lastName, $street, $province, $postal, $country, $phone, $email, $newsletter);
If I write and declare values explicitly like this, they write to the database properly which seems to indicate my prepared statement works properly.
$title = "Ms";
$firstName = "Jane";
$lastName = "Doe";
$street = "123 ABC Lane";
$city = "AnyTown";
$province = "Nova Scotia";
$postal = "A1A 1A1";
$country = "Canada";
$phone = "555-555-5555";
$email = "email#domain.com";
$newsletter = 1;
$stmt->bind_param("ssssssssssi", $title, $firstName, $lastName, $street, $province, $postal, $country, $phone, $email, $newsletter);
I'll be very grateful for any help in diagnosing why everything seems to work except getting the values through POST. Also willing to accept any tips about why my error-checking seems to get skipped over when submitting to the database. Thanks in advance!

Update value based on checkbox selected

I am trying to update the value in a text box based on selections made on the form. When a user checks a box for an option, I am trying to get the total cost to increase by a defined amount. Everything else is working on the form and if I change the cost value manually it will post to database correctly. Is this possible with my approach or do I need to resort to a different technique?
<HEAD>
<script>
function tally()
{
Cost = 60;
if (Document.edituser.survivor10.checked ) { Cost = Cost + 10; }
if (document.edituser.high5.checked ) { Cost = Cost + 10; }
if (document.edituser.margin.checked == true ) { Cost = Cost + 10; }
if (document.edituser.survivor20.checked == true ) { Cost = Cost + 20; }
if (document.edituser.confidence.checked == true ) { Cost = Cost + 10; }
if (document.edituser.loser.checked == true ) { Cost = Cost + 10; }
if (document.edituser.vegas.checked == true ) { Cost = Cost + 10; }
document.edituser.cost.value = Cost;
}
<?php
require('includes/application_top.php');
include('includes/classes/class.formvalidation.php');
if (isset($_POST['submit'])) {
$my_form = new validator;
if($my_form->checkEmail($_POST['email'])) { // check for good mail
if ($my_form->validate_fields('firstname,lastname,email,password')) { //
comma delimited list of the required form fields
if ($_POST['password'] == $_POST['password2']) {
$salt = substr($crypto->encrypt((uniqid(mt_rand(), true))), 0, 10);
$secure_password = $crypto->encrypt($salt . $crypto->encrypt($_POST['password']));
$sql = "update nflp_users ";
$sql .= "set password = '".$secure_password."', salt = '".$salt."', firstname = '".$_POST['firstname']."', lastname = '".$_POST['lastname']."', textOption = '".$_POST['textOption']."', phone = '".$_POST['phone']."', carrier = '".$_POST['carrier']."', email = '".$_POST['email']."', survivor10 = '".$_POST['survivor10']."', survivor20 = '".$_POST['survivor20']."', loser = '".$_POST['loser']."', margin = '".$_POST['margin']."', high5 = '".$_POST['high5']."', vegas = '".$_POST['vegas']."', confidence = '".$_POST['confidence']."', cost = '".$_POST['cost']."'";
$sql .= "where userID = " . $user->userID . ";";
//die($sql);
$mysqli->query($sql) or die($mysqli->error);
//set confirmation message
$display = '<div class="responseOk">Account updated successfully.</div><br/>';
} else {
$display = '<div class="responseError">Passwords do not match, please try again.</div><br/>';
}
} else {
$display = str_replace($_SESSION['email_field_name'], 'Email', $my_form->error);
$display = '<div class="responseError">' . $display . '</div><br/>';
}
} else {
$display = '<div class="responseError">There seems to be a problem with your email address, please check.</div><br/>';
}
}
include('includes/header.php');
$sql = "select * from " . DB_PREFIX . "users where userID = " . $user->userID;
$query = $mysqli->query($sql);
if ($query->num_rows > 0) {
$row = $query->fetch_assoc();
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$email = $row['email'];
$survivor10 = $row['survivor10'];
$survivor20 = $row['survivor20'];
$loser = $row['loser'];
$margin = $row['margin'];
$high5 = $row['high5'];
$confidence = $row['confidence'];
$vegas = $row['vegas'];
// $textOption = $row['textOption'];
// $phone = $row['phone'];
// $carrier = $row['carrier'];
$cost = $row['cost'];
}
if (!empty($_POST['firstname'])) $firstname = $_POST['firstname'];
if (!empty($_POST['lastname'])) $lastname = $_POST['lastname'];
if (!empty($_POST['email'])) $email = $_POST['email'];
if (!empty($_POST['survivor10'])) $survivor10 = $_POST['survivor10'];
if (!empty($_POST['survivor20'])) $survivor20 = $_POST['survivor20'];
if (!empty($_POST['loser'])) $loser = $_POST['loser'];
if (!empty($_POST['margin'])) $margin = $_POST['margin'];
if (!empty($_POST['high5'])) $high5 = $_POST['high5'];
if (!empty($_POST['confidence'])) $confidence = $_POST['confidence'];
if (!empty($_POST['vegas'])) $vegas = $_POST['vegas'];
// if (!empty($_POST['textOption'])) $textOption = $_POST['textOption'];
// if (!empty($_POST['phone'])) $phone = $_POST['phone'];
// if (!empty($_POST['carrier'])) $carrier = $_POST['carrier'];
if (!empty($_POST['cost'])) $cost = $_POST['cost'];
?>
<h1>Edit User Account Details</h1>
<?php if(isset($display)) echo $display; ?>
<form action="user_edit.php" method="post" name="edituser">
<fieldset>
<legend style="font-weight:bold;">Enter User Details:</legend>
<p>First Name:<br />
<input type="text" name="firstname" value="<?php echo $firstname; ?>"></p>
<p>Last Name:<br />
<input type="text" name="lastname" value="<?php echo $lastname; ?>"></p>
<p>Email:<br />
<input type="text" name="email" value="<?php echo $email; ?>" size="30"></p>
<p>New Password:<br />
<input type="password" name="password" value=""></p>
<p>Confirm Password:<br />
<input type="password" name="password2" value=""></p><br>
<tr><td></td></tr>
<legend style="font-weight:bold;">Side Pools:</legend>
<tr>
<p><type=hidden value=" " name="survivor10" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="survivor10" <? if($survivor10== "1") {echo "checked";} ?>><b> Survivor $10</b></p>
<p><type=hidden value=" " name="survivor20" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="survivor20" <? if($survivor20== "1") {echo "checked";} ?>><b> Survivor2 $20</b></p>
<p><type=hidden value=" " name="loser" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="loser" <? if($loser== "1") {echo "checked";} ?> ><b> Loser $10</b></p>
<p><type=hidden value=" " name="high5" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="high5" <? if($high5== "1") {echo "checked";} ?>><b> High 5 $10</b></p>
<p><type=hidden value=" " name="margin" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="margin" <? if($margin== "1") {echo "checked";} ?> ><b> Margin $10</b></p>
<p><type=hidden value=" " name="vegas" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="vegas" <? if($vegas== "1") {echo "checked";} ?> ><b> Vegas $10</b></p>
<p><type=hidden value=" " name="confidence" checked>
<INPUT onclick=tally() TYPE="checkbox" value="1" NAME="confidence" <? if($confidence== "1") {echo "checked";} ?>><b> Confidence $10</b></p>
</tr><br>
<td><font color=red>Your Total Fee Is :</font><input type="int" size="3" name="cost" value= "<? if($cost!= "") {echo "$cost"; } else {echo "60";}?>"</td><br><br>
<!--<tr>Text alert option: Message and data rates may apply. Expect approx. 3 msgs/week.</tr> -->
<p><input type="submit" name="submit" value="Submit" class="btn btn-primary"></p>
</fieldset>
</form>
JavaScript is case sensitive, so Document and document are two different things. In your case, you want to use document. So you should change all if conditions inside tally, to use document.
Btw. never trust the user! You could do the calculation on the client side as an indicator for the user, but you should definitly do it again on the serverside or everyone could post costs as the like - even negative ones.

Post form update error to mysql using php

I'm trying to update a form to mysql database with php but when i add values to the input fields they're posted empty. This is the error:
Error Save [UPDATE Customers SET Forename = '', Surename = '', Father
= '', ID = '', AMKA = '', Address = '', AddressNumber = '', PostCode = '', Area = '', City = '', WHERE CustomerCode = '4']
As you can see the GET for the customer code works fine but the POST is not working.
Here is my code for the edit form:
<?php
$conn = new mysqli('localhost', 'root', 'password','erp');
if ($conn->connect_errno) {
die('Could not connect: ' . $conn->connect_error);
}
$id = $_GET['CustomerCode'];
$sql = $conn->query("SELECT Forename, Surename, FathersName, IDNumber, AMKA, Address, AddressNumber, PostCode, Area FROM Customers WHERE CustomerCode= '$id'");
$sqlList = $conn->query("SELECT City FROM Customers");
$row = $sql->fetch_array();
?>
<form action="SavedRecord.php?CustomerCode=<?php echo $id; ?>" method="post">
<table>
Name: <input type="text" name="Name" value="<?php echo $row['Forename']; ?>">
Surename: <input type="text" name="Surename" value="<?php echo $row['Surename']; ?>">
Father: <input type="text" name="Father" value="<?php echo $row['FathersName']; ?>">
ID: <input type="text" name="ID" value="<?php echo $row['IDNumber']; ?>">
AMKA: <input type="text" name="AMKA" onkeypress="return event.charCode >= 48 && event.charCode <= 57" value="<?php echo $row['AMKA']; ?>">
Address: <input type="text" name="Address" value="<?php echo $row['Address']; ?>">
Address Number: <input type="text" name="AddressNumber" onkeypress="return event.charCode >= 48 && event.charCode <= 57" value="<?php echo $row['AddressNumber']; ?>">
PostCode: <input type="text" name="PostCode" onkeypress="return event.charCode >= 48 && event.charCode <= 57" value="<?php echo $row['PostCode']; ?>">
Area: <input type="text" name="Area" value="<?php echo $row['Area']; ?>">
City: <select name="Cities">
<option>Select
<?php while($list = mysqli_fetch_array($sqlList)) { ?>
<option value="<?php echo $list['City']; ?>"><?php echo $list['City']; ?></option>
<?php if($list['City'] == $select) { echo $list['City']; } ?>
</option>
<?php } ?>
</option>
</select>
</table>
<input type="submit" value="Update">
</form>
And the update form:
<?php
$conn = new mysqli('localhost', 'root', 'password','erp');
if ($conn->connect_errno) {
die('Could not connect: ' . $conn->connect_error);
}
print_r($_POST);
$name = $_POST['Name'];
$surename = $_POST['Surename'];
$father = $_POST["Father"];
$id = $_POST["ID"];
$amka = $_POST["AMKA"];
$address = $_POST["Address"];
$addressNum = $_POST["AddressNumber"];
$postcode = $_POST["PostCode"];
$area = $_POST["Area"];
$city = $_POST["City"];
$customerCode = $_GET["CustomerCode"];
$updData = "UPDATE Customers SET
Forename = '$name',
Surename = '$surename',
Father = '$father',
ID = '$id',
AMKA = '$amka',
Address = '$address',
AddressNumber = '$addressNum',
PostCode = '$postcode',
Area = '$area',
City = '$city',
WHERE CustomerCode = '$customerCode'";
$updQuery = $conn->query($updData);
if($updQuery) {
echo "Data Updated";
} else {
echo "Error Save [".$updData."]";
}
?>
Your Error is you have misspelled the table field values. Have a check below and replace the code in the WITH Section
Replace
$updData = "UPDATE Customers SET
Forename = '$name',
Surename = '$surename',
Father = '$father',
ID = '$id', // here is your error the field name is not ID it is IDNumber
AMKA = '$amka',
Address = '$address',
AddressNumber = '$addressNum',
PostCode = '$postcode',
Area = '$area',
City = '$city',
WHERE CustomerCode = '$customerCode'";
With
$updData = "UPDATE Customers SET
Forename = '$name',
Surename = '$surename',
FathersName = '$father',
IDNumber = '$id',
AMKA = '$amka',
Address = '$address',
AddressNumber = '$addressNum',
PostCode = '$postcode',
Area = '$area',
City = '$city',
WHERE CustomerCode = '$customerCode'";
Here i will provide with the Exact output that is needed for you and i have tested it in my local-host and working fine.
Edit form Page:
<?php
$conn = new mysqli('localhost', 'root', '','erp');
if ($conn->connect_errno) {
die('Could not connect: ' . $conn->connect_error);
}
$id = $_GET['CustomerCode'];
$sql = $conn->query("SELECT Forename, Surename, FathersName, IDNumber, AMKA, Address, AddressNumber, PostCode, Area, City FROM Customers WHERE CustomerCode= '$id'");
$sqlList = $conn->query("SELECT City FROM Customers");
$row = $sql->fetch_array();
?>
<form action="SavedRecord.php?CustomerCode=<?php echo $id; ?>" method="post">
<table>
Name: <input type="text" name="Name" value="<?php echo $row['Forename']; ?>">
Surename: <input type="text" name="Surename" value="<?php echo $row['Surename']; ?>">
Father: <input type="text" name="Father" value="<?php echo $row['FathersName']; ?>">
ID: <input type="text" name="ID" value="<?php echo $row['IDNumber']; ?>">
AMKA: <input type="text" name="AMKA" onkeypress="return event.charCode >= 48 && event.charCode <= 57" value="<?php echo $row['AMKA']; ?>">
Address: <input type="text" name="Address" value="<?php echo $row['Address']; ?>">
Address Number: <input type="text" name="AddressNumber" onkeypress="return event.charCode >= 48 && event.charCode <= 57" value="<?php echo $row['AddressNumber']; ?>">
PostCode: <input type="text" name="PostCode" onkeypress="return event.charCode >= 48 && event.charCode <= 57" value="<?php echo $row['PostCode']; ?>">
Area: <input type="text" name="Area" value="<?php echo $row['Area']; ?>">
City: <select name="Cities">
<option>Select
<?php while($list = mysqli_fetch_array($sqlList)) { ?>
<option value="<?php echo $list['City']; ?>" <?php if($list['City']==$row['City']){echo 'selected="selected"';} ?>><?php echo $list['City']; ?></option>
</option>
<?php } ?>
</option>
</select>
</table>
<input type="submit" value="Update">
</form>
SavedRecord.php
<?php
$conn = new mysqli('localhost', 'root', '','erp');
if ($conn->connect_errno) {
die('Could not connect: ' . $conn->connect_error);
}
print_r($_POST);
$name = $_POST['Name'];
$surename = $_POST['Surename'];
$father = $_POST["Father"];
$id = $_POST["ID"];
$amka = $_POST["AMKA"];
$address = $_POST["Address"];
$addressNum = $_POST["AddressNumber"];
$postcode = $_POST["PostCode"];
$area = $_POST["Area"];
$city = $_POST["Cities"];
$customerCode = $_GET["CustomerCode"];
$updData = "UPDATE Customers SET
Forename = '$name',
Surename = '$surename',
FathersName = '$father',
IDNumber = '$id',
AMKA = '$amka',
Address = '$address',
AddressNumber = '$addressNum',
PostCode = '$postcode',
Area = '$area',
City = '$city's
WHERE CustomerCode = '$customerCode'";
$updQuery = $conn->query($updData);
if($updQuery) {
echo "Data Updated";
} else {
echo "Error Save [".$updData."]";
}
?>
This code works perfect. have it a try and let me know if any hurdles happens to you again.

Insert same ID connected to multiple selection options ID

I need to have the array pulling multiple FacultyIDs also connect to the same PubID in the FACULTYPUBLICATION table.
FacultyName is a multiple select option field
Publication is a single insert and creates an auto generated id
the Publication ID gets inserted into the PUBLICATION table
the FacultyID comes from a lookup table that is predefined
the PubID and the FacultyID gets inserted into the FACULTYPUBLICATIONS table
PROBLEM: When multiple Faculty are selected only 1 faculty gets inserted into FACULTYPUBLICATIONS. I need to find a way to connect a single PubID to multiple faculty in the FACULTYPUBLICATIONS table
//insert form values into database
$sql = "SELECT JournalName, JournalID, Rating, JournalActive from JOURNAL where JournalActive = 1;";
//Can take out JournalActive if we do not want it
$result = mysqli_query($conn, $sql);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
echo "there was an issue";
}
$sql2 = "SELECT FName, LName, FacultyID from FACULTY where FacultyActive = 1;";
//Can take out JournalActive if we do not want it
$result2 = mysqli_query($conn, $sql2);
if (!$result2) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
echo "there was an issue";
}
//array to hold all of the data
$journals = array();
//print out all of the first names in the database
$rownumber = 0;
while ($row = mysqli_fetch_assoc($result)) {
$journals[$rownumber][0] = $row['JournalName'];
$journals[$rownumber][1] = $row['JournalID'];
$journals[$rownumber][2] = $row['JournalRating'];
$journals[$rownumber][3] = $row['JournalActive'];
$rownumber++;
}
$faculty = array();
//print out all of the first names in the database
$rownum = 0;
while ($row = mysqli_fetch_assoc($result2)) {
$faculty[$rownum][0] = $row['FName'];
$faculty[$rownum][1] = $row['LName'];
$faculty[$rownum][2] = $row['FacultyID'];
$rownum++;
}
?>
<!DOCTYPE html>
<head>
<link href="styles.css" rel="stylesheet">
<h1> Miami University </h1>
<h4> Information Systems and Analytics Department </h4>
</head>
<body>
<div class="StyleDiv" >
<!-- coding for journal -->
<form id="form1" name="form1" method="post" action="RR2.php">
<label for="FacultyName">Faculty Name</label>
<select multiple="multiple" name="FacultyID" id="FacultyID">
<?php
for($i = 0; $i < sizeof($faculty); $i++) {
print "<option value=\"" . $faculty[$i][2] . "\">" . $faculty[$i][0] .' '. $faculty[$i][1] . "</option>\r\n";
}
?>
</select>
<br class="clear" />
<br class="clear" />
<label for="JournalID">Journal Name</label>
<select name="JournalID" id="JournalID">
<?php
for($i = 0; $i < sizeof($journals); $i++) {
print "<option value=\"" . $journals[$i][1] . "\">" . $journals[$i][0] . "</option>\r\n";
}
?>
</select>
<br class="clear" />
<label for="JournalRating">Journal Rating</label><input type="text" name="JournalRating" id="JournalRating" />
<br class="clear" />
<!-- coding for publication -->
<label for="Title">Publication Title</label><input type="text" name="PubID" id="PubID" />
<br class="clear" />
<label for="Year">Year</label><input type="text" name="Year" id="Year" />
<br class="clear" />
<label for="Volume">Volume</label><input type="text" name="Volume" id="Volume" />
<br class="clear" />
<label for="Issue">Issue</label><input type="text" name="Issue" id="Issue" />
<br class="clear" />
<label for="Comments">Comments</label><textarea name="Comments" id="Comments" cols="45" rows="5"></textarea>
<br class="clear" />
<input type="submit" name="Submit" id="Submit" value="Submit" />
<br class="clear" />
</br>
</br>
</div>
</form>
<?php
//Post Parameters
$JournalID = $_POST['JournalID'];
//for($i = 0; $i < sizeof($journals); $i++) {
//if ($JournalID = $journals[$i][1]) {
//$JournalName = $journals[$i][0];
//}
//}
$Year = $_POST['Year'];
$Comments = $_POST['Comments'];
$Volume = $_POST['Volume'];
$Issue = $_POST['Issue'];
$Title = $_POST['Title'];
$JournalRating = $_POST['JournalRating'];
$FacultyMemID = $_POST['FacultyID'];
//Query
//INSERT
$stmt = $conn->prepare(" INSERT INTO PUBLICATION ( JournalID, Year, Comments, Volume, Issue, Title, JournalRating ) VALUES ( '$JournalID', '$Year', '$Comments', '$Volume', '$Issue', '$Title', '$JournalRating' )");
$stmt->execute();
// would need to add inserts for JournalName if we re-add it in
$stmt = $conn->prepare(" INSERT INTO FACULTYPUBLICATIONS ( FacultyID, PubID ) VALUES ( '$FacultyMemID', last_insert_id() )");
$stmt->execute();
mysqli_close($conn);
?>
</body>
</html>
To get multiple selections, add [] to the name of the input:
<select multiple="multiple" name="FacultyID[]" id="FacultyID">
This tells PHP to make $_POST['FacultyID'] an array of all the values. Then you can loop through them:
$stmt = $conn->prepare(" INSERT INTO PUBLICATION ( JournalID, Year, Comments, Volume, Issue, Title, JournalRating ) VALUES ( ?, ?, ?, ?, ?, ?, ? )");
$stmt->bind_param('sssssss', $JournalID, $Year, $Comments, $Volume, $Issue, $Title, $JournalRating);
$stmt->execute();
$pubID = $conn->insert_id;
$stmt = $conn->prepare(" INSERT INTO FACULTYPUBLICATIONS ( FacultyID, PubID ) VALUES ( ?, ? )");
$stmt->bind_param('si', $FacultyMemID, $pubID);
for ($_POST['FacultyID'] as $FacultyMemID) {
$stmt->execute();
}
Note that you can't use the SQL LAST_INSERT_ID() in the loop, because after the first iteration it will contain the ID of the row that was just inserted into FACULTYPUBLICATIONS, not the ID of the row that was inserted into PUBLICATION before the loop. So I used the PHP $stmt->insert_id to get the ID.
I've also recoded using bind_param to prevent SQL injection.
This makes it work as well because calling the array from the original function.
$stmt = $conn->prepare(" INSERT INTO FACULTYPUBLICATIONS ( FacultyID, PubID ) VALUES ( ?, ? )");
$stmt->bind_param('ii', $facmemid, $pubID);
//for ($_POST['FacultyID'] as $FacultyMemID) {
for($i = 0; $i < sizeof($FacultyMemID); $i++) {
$facmemid = $FacultyMemID[$i];
$stmt->execute();
}

PHP form not submitting until all the info entered

I am submitting an HTML form using php and I have these fields in my form:
Name:(varchar)
Address:(varchar)
FAX:(int)
PHONE:(int)
EMAIL:(varchar)
plus a primary ID that gets added on its own.
Now my form doesn't get submitted until I enter the fax field? Does anyone know why is it happening?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<body>
<?php
require_once('../../public_html/input.php');
require_once('../../public_html/nauth.php');
require_once('../../public_html/mysql.php');
if (isset($_GET['more']))
{
$more = $_GET['more'];
$new = 8;
}
if (isset($_POST['submit']))
{
$more = 4;
$new = 8;
$name = $_SESSION['username'];
$dbc = mysqli_connect(cname, chost, cpwd, cdb);
$com_name = mysqli_real_escape_string($dbc, trim($_POST['com_name']));
$com_address = mysqli_real_escape_string($dbc, trim($_POST['com_address']));
$com_phone = mysqli_real_escape_string($dbc, trim($_POST['com_phone']));
$com_fax = mysqli_real_escape_string($dbc, trim($_POST['com_fax']));
$source_id = $_POST['source'];
$com_email = mysqli_real_escape_string($dbc, trim($_POST['com_email']));
$entered_by = $name;
$query = "select * from company_customers where name='$com_name'";
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) == 0) //to check if the name already exists
{
$query="insert into company_customers(name,address,phone,fax,email,entered_by,source_id) values('$com_name','$com_address','$com_phone','$com_fax','$com_email','$entered_by','$source_id')";
mysqli_query($dbc, $query);
$query = "select * from company_customers where name='$com_name'";
$data = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($data);
$id = $row['id']; //to add the company id in the contacts table
$i = 0;
while (!empty($_POST['name' . $i]))
{
$name = $_POST['name' . $i];
$designation = $_POST['desig' . $i];
$phone = $_POST['phone' . $i];
$query = "insert into contacts(name,designation,id,phone) values('$name','$designation','$id','$phone')";
mysqli_query($dbc, $query);
$i++;
}
mysqli_close($dbc);
echo 'Added';
require_once('option.php');
exit();
}
else echo 'company already entered';
}
else if (isset($_POST['more']))
{
$more = $_POST['count'];
$new = $more + 4;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<fieldset><legend>Company Profile</legend>
<label for="com_name">Company Name:</label><input type="text" name="com_name" value="<?php if(isset($_POST['more'])) echo $_POST['com_name']; ?>"/><br />
<label for="com_address">Company Address:</label><input type="text" name="com_address" value="<?php if(isset($_POST['more'])) echo $_POST['com_address']; ?>" /><br />
<label for="com_phone">Company Phone:</label><input type="text" name="com_phone" value="<?php if(isset($_POST['more'])) echo $_POST['com_phone']; ?>" /><br />
<label for="com_fax">Company Fax:</label><input type="text" name="com_fax" value="<?php if(isset($_POST['more'])) echo $_POST['com_fax']; ?>" /><br />
<label for="com_email">Company Email:</label><input type="text" name="com_email" value="<?php if(isset($_POST['more'])) echo $_POST['email']; ?>" /><br />
<?php
$dbc = mysqli_connect(cname, chost, cpwd, cdb);
$query = "select * from source";
$data = mysqli_query($dbc, $query);
$number_row = mysqli_num_rows($data);
$source[0] = '';
$source_id[0] = '';
$i = 1;
while ($row = mysqli_fetch_array($data))
{
$source[$i] = $row['src'];
$source_id[$i] = $row['source_id'];
$i++;
}
echo '<label for="source">Source</label><select name="source">';
for ($i = 0; $i <= $number_row; $i++)
echo '<option value="' . $source_id[$i] . '">' . $source[$i] . '</option>';
echo '</select>';
?>
</fieldset>
<fieldset><legend>Company Contact</legend>
<?php
for ($i = 0; $i < $more; $i++)
{
?>
<label for="<?php echo 'name' . $i; ?>">Name:</label><input type="text" name="<?php echo 'name' . $i; ?>" value="<?php if (isset($_POST['more'])) echo $_POST['name' . $i]; ?>" />
<label for="<?php echo 'desig' . $i; ?>">Designation:</label><input type="text" name="<?php echo 'desig' . $i; ?>" value="<?php if (isset($_POST['more'])) echo $_POST['desig' . $i];?>" />
<label for="<?php echo 'phone' . $i;?>">Phone:</label><input type="text" name="<?php echo 'phone' . $i;?>" value="<?php if (isset($_POST['more'])) echo $_POST['phone' . $i]; ?>" /><br />
<?php
}
?>
<input type="hidden" name="count" value="<?php echo $new; ?>" />
<input type="submit" name="more" value="more" />
</fieldset>
<input type="submit" name="submit" value="ADD" />
</form>
</body>
</html>
Try setting the column to allow null values in mysql. E.g.
ALTER TABLE company_customers CHANGE fax fax INT(11) NULL

Categories