My code is given below (didn't include any html, no error/warning/notice). The program executes fine. The only problem I have is when I try to change the member_id and date fields in database- it doesn't work! As you can see I have used separate names for same fields mmid (used in the form) for member_id and dd (used in the form) for today. So, when user enters a different value it is assigned to mmid and dd while keeping the original values to member_id and dd allowing me to properly execute the update query. All other fields update is done as expected. None of the fields in the db is primary/unique/index. Could you please help me find where the problem is?
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$memberErr = $employeeErr = $dateErr = $blankfieldErr ="";
$mmid = $dd = $member_id = $employee_id = $paid_installment = $savings_deposit = $late_fee = $today = $dayx = $monthx = $yearx = "";
if (isset($_POST['SubmitFirst']))
{
if (empty($_POST["member_id"])) {
$memberErr = "আপনি সদস্যর আইডি দিতে ভুলে গেছেন";
} else {
$member_id = test_input($_POST["member_id"]);
}
if(!empty($_POST["dayx"]))
{
$dayx = test_input($_POST["dayx"]);
}
if(!empty($_POST["monthx"]))
{
$monthx = test_input($_POST["monthx"]);
}
if(!empty($_POST["yearx"])) // if all of them are selected
{
$yearx = test_input($_POST["yearx"]);
}
if(!empty($_POST["dayx"]) and !empty($_POST["monthx"]) and !empty($_POST["yearx"])){
$today= $yearx. "-" . $monthx. "-" . $dayx; }
else { $dateErr = "আপনি দিন / মাস / বছর লিখতে ভুলে গেছেন"; }
}
if (isset($_POST['Submit']))
{
echo $mmid;
echo " ";
echo $dd;
if (empty($_POST["mmid"])) {
$memberErr = "আপনি সদস্যর আইডি দিতে ভুলে গেছেন";
} else {
$mmid = test_input($_POST["mmid"]);
}
if (empty($_POST["dd"])) {
$dateErr = "আপনি সদস্যর আইডি দিতে ভুলে গেছেন";
} else {
$dd = test_input($_POST["dd"]);
}
if (empty($_POST["employee_id"])) {
$employeeErr = "আপনি কর্মীর আইডি দিতে ভুলে গেছেন";
} else {
$employee_id = test_input($_POST["employee_id"]);
}
if (empty($_POST["paid_installment"]) and empty($_POST["savings_deposit"]) and empty($_POST["late_fee"])) {
$blankfieldErr = "আপনি installment/savings/late_fee দিতে ভুলে গেছেন";
} else {
$paid_installment = test_input($_POST["paid_installment"]);
$savings_deposit = test_input($_POST["savings_deposit"]);
$late_fee = test_input($_POST["late_fee"]);
}
$servername = "localhost";
$username = "xxxxx";
$password = "yyyyy";
$dbname = "zzzzz";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to UPDATE a record
$sql1 = "UPDATE daily_collection set date='$dd', member_id='$mmid', employee_id='$employee_id', paid_installment='$paid_installment', savings_deposit='$savings_deposit', late_fee='$late_fee' where member_id='$member_id' and date='$today'";
if ($result1=mysqli_query($conn,$sql1)) {
echo "<h2>". "সাবাস আপনি ঠিকভাবে তথ্য রেকর্ড করেছেন!". "</h2>";
} else {
echo "<h2>"."প্রোগ্রামে কিছু একটা সমস্যা হয়েছে, সুদিন স্যার-এর সাথে যোগাযোগ করুন ". "</h2>";
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
সদস্যর আইডি <input type="text" name="member_id" value="<?php echo $member_id;?>" size="50">
<span class="error"> <?php echo $memberErr;?></span>
<br><br>
তারিখ দিন <input type="text" name="dayx" value="<?php echo $dayx;?>" size="10"> মাস <input type="text" name="monthx" value="<?php echo $monthx;?>" size="10"> বছর <input type="text" name="yearx" value="<?php echo $yearx;?>" size="10">
<span class="error"> <?php echo $dateErr;?></span>
<br><br>
<center><input type="submit" name="SubmitFirst" value="SubmitFirst"></center><br>
</form>
<?php
if(isset($_POST['SubmitFirst']) and $member_id!="" and $today!="")
{
$servername = "localhost";
$username = "xxxxx";
$password = "yyyyy";
$dbname = "zzzzz";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="select * from daily_collection where member_id='$member_id' and date='$today'";
if ($result=mysqli_query($conn,$sql))
{
while ($row=mysqli_fetch_row($result))
{
$dd=$row["0"];
$mmid=$row["1"];
$employee_id=$row["2"];
$paid_installment=$row[3];
$savings_deposit=$row[4];
$late_fee=$row[5];
}
echo $member_id;
echo " ";
echo $today;
}
else { echo "no such entry found";}
?>
<center><h2>দৈনিক কালেকশন এন্ট্রি ফর্ম</h2></center>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
সদস্যর আইডি <input type="text" name="mmid" value="<?php echo $mmid;?>" size="50">
<span class="error"> <?php echo $memberErr;?></span>
<br><br>
কর্মীর আইডি <input type="text" name="employee_id" value="<?php echo $employee_id;?>" size="50">
<span class="error"> <?php echo $employeeErr;?></span>
<br><br>
কিস্তির টাকা <input type="text" name="paid_installment" value="<?php echo $paid_installment;?>" size="50">
<br><br>
সঞ্চয় <input type="text" name="savings_deposit" value="<?php echo $savings_deposit;?>" size="50">
<br><br>
লেট ফী <input type="text" name="late_fee" value="<?php echo $late_fee;?>" size="50">
<span class="error"> <?php echo $blankfieldErr;?></span>
<br><br>
তারিখ <input type="text" name="dd" value="<?php echo $dd;?>" size="10">
<span class="error"> <?php echo $dateErr;?></span>
<br><br>
<center><input type="submit" name="Submit" value="Submit"></center><br>
</form>
<?php
}
if(!empty($_POST['Submit']))
{
}
?>
Inside if (isset($_POST['Submit']))
{ this block you have print $mmid, As $mmid is not set here so it will not print anything. To get the exact update query please echo $sql1
Update below part by
while ($row=mysqli_fetch_row($result))
{
$dd=$row["0"];
$mmid=$row["1"];
$employee_id=$row["2"];
$paid_installment=$row[3];
$savings_deposit=$row[4];
$late_fee=$row[5];
}
**while ($row=mysqli_fetch_assoc($result))** or instead of $row["0"] put $row[0] or exact column name like $row['date']
Related
I'm trying to add form data into my database table on Xampp ,but while My echo displays everything properly ,it doesn't input anything into the database table and I wonder if I'm missing something here.I made sure to spell everything the same ,so I doubt it's a spelling error atleast....Any help,suggestions and or corrections are greatly appreciated !
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$VarErr = $PavErr = $AdErr = $PkErr = $KiekErr = "";
$Vardas = $Pavarde = $Adresas = $Pk = $Kiekis = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Vardas"])) {
$VarErr = "Įveskite vardą";
} else {
$Vardas= test_input($_POST["Vardas"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$Vardas)) {
$VarErr = "Galima vesti tik su raidėmis";
}
}
if (empty($_POST["Pavarde"])) {
$PavErr = "Įveskite pavardę";
} else {
$Pavarde = test_input($_POST["Pavarde"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$Pavarde)) {
$PavErr = "Galima vesti tik su raidėmis";
}
}
if (empty($_POST["Adresas"])) {
$AdErr = "Įveskite adresą";
} else {
$Adresas= test_input($_POST["Adresas"]);
}
if (empty($_POST["Pk"])) {
$Pk = "Įveskite prekės kodą";
} else {
$Pk = test_input($_POST["Pk"]);
}
if (empty($_POST["Kiekis"])) {
$KiekErr = "Įveskite kiekį";
} else {
$Kiekis = test_input($_POST["Kiekis"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Vardas: <input type="text" name="Vardas" value="<?php echo $Vardas;?>">
<span class="error">* <?php echo $VarErr;?></span>
<br><br>
Pavarde: <input type="text" name="Pavarde" value="<?php echo $Pavarde;?>">
<span class="error">* <?php echo $PavErr;?></span>
<br><br>
Adresas: <input type="text" name="Adresas" value="<?php echo $Adresas;?>">
<span class="error"><?php echo $AdErr;?></span>
<br><br>
Pk: <input type="number" name="Pk" value="<?php echo $Pk;?>">
<span class="error"><?php echo $PkErr;?></span>
<br><br>
Kiekis:<input type="number" name="Kiekis" value="<?php echo $Kiekis;?>">
<span class="error"><?php echo $KiekErr;?></span>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $Vardas;
echo "<br>";
echo $Pavarde;
echo "<br>";
echo $Adresas;
echo "<br>";
echo $Pk;
echo "<br>";
echo $Kiekis;
$host = "localhost";
$user = "root";
$password ="";
$database = "uzsakymas";
try{
$connect = mysqli_connect($host,$user,$password,$database);
}
catch(mysqli_sql_exception $ex){
echo 'database connection error';
}
if(isset($_POST['insert'])) {
$Vardas = $_POST['Vardas'];
$Pavarde = $_POST['Pavarde'];
$Adresas = $_POST['Adresas'];
$Pk = $_POST['Pk'];
$Kiekis = $_POST['Kiekis'];
$insert_query = "INSERT INTO uzsakymai (Vardas,Pavarde,Adresas,Pk,Kiekis)VALUES('$Vardas','$Pavarde','$Adresas','$Pk','$Kiekis')";
try {
$insert_result = mysqli_query($connect,$insert_query);
if($insert_result){
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Inserted';
}else{
echo'Data not Inserted';
}
}
} catch(Exception $ex) {
echo 'Error Insert'.$ex->getMessmessage();
}
}
?>
</body>
</html>
hi your are checking value in insert isset($_POST['insert']) but insert name not assign in any control so assign insert name to your submit control check below :
<input type="submit" value="Submit" name="insert">
I'm kinda confused with your code but I think the wrong part is in here:
<input type="submit" name="submit" value="Submit">
You have this submit but look at this:
if(isset($_POST['insert']))
You are trying to check if POST is set to insert instead of submit.
In my code below i have two form section first one is to fetch information from database and second one is verify a record in the database my problem is how do verify a record and redirect to error page or if the input form do not march any record redirect to index page this my code;
<?php
include_once 'init.php';
$error = false;
//check if form is submitted
if (isset($_POST['book'])) {
$book = mysqli_real_escape_string($conn, $_POST['book']);
$action = mysqli_real_escape_string($conn, $_POST['action']);
if (strlen($book) < 6) {
$error = true;
$book_error = "booking code must be alist 6 in digit";
}
if (!is_numeric($book)) {
$error = true;
$book_error = "Incorrect booking code";
}
if (empty($_POST["action"])) {
$error = true;
$action_error = "pick your action and try again";
}
if (!$error) {
if(preg_match('/(check)/i', $action)) {
echo "6mameja";
}
if (preg_match('/(comfirm)/i', $action)) {
if(isset($_SESSION["user_name"]) && (trim($_SESSION["user_name"]) != "")) {
$username=$_SESSION["user_name"];
$result=mysqli_query($conn,"select * from users where username='$username'");
}
if ($row = mysqli_fetch_array($result)) {
$id = $row["id"];
$username=$row["username"];
$idd = $row["id"];
$username = $row["username"];
$ip = $row["ip"];
$ban = $row["validated"];
$balance = $row["balance"];
$sql = "SELECT `item_name` , `quantity` FROM `books` WHERE `book`='$book'";
$query = mysqli_query($conn, $sql);
while ($rows = mysqli_fetch_assoc($query)) {
$da = $rows["item_name"]; $qty = $rows["quantity"];
$sqll = mysqli_query($conn, "SELECT * FROM promo WHERE code='$da' LIMIT 1");
while ($prow = mysqli_fetch_array($sqll)) {
$pid = $prow["id"];
$price = $prow["price"];
$count = 0;
$count = $qty * $price;
$show = $count + $show;
}
}
echo "$show";
echo "$balance";
if ($show<$balance) {
if (isset($_POST["verify"])) {
$pass = mysqli_real_escape_string($conn, $_POST["pass"]);
if ($pass != "$username") {
header("location: index.php");
}
elseif ($pass = "$username") {
header("location: ../error.php");
}
}
echo '<form action="#" method="post" name="verify"><input class="text" name="pass" type="password" size="25" /><input class="text" type="submit" name="verify" value="view"></form>';
echo "you cant buy here";
exit();
}
} else {
$errormsg = "Error in registering...Please try again later!";
}
}
}
}
?>
<form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="booking">
<fieldset>
<legend>Check Booking</legend>
<div class="form-group">
<label for="name">Username</label>
<input type="text" name="book" placeholder="Enter Username" required value="<?php if($error) echo $book; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($book_error)) echo $book_error; ?></span>
</div>
<input type="submit" name="booking" value="Sign Up" class="btn btn-primary" />
<table>
<input type="radio" name="action" value="comfirm" <?php if(isset($_POST['action']) && $_POST['action']=="comfirm") { ?>checked<?php } ?>>
<input type="radio" name="action" value="check" <?php if(isset($_POST['action']) && $_POST['action']=="check") { ?>checked<?php } ?>> Check booking <span class="text-danger"><?php if (isset($action_error)) echo $action_error; ?></span>
</div>
</table>
</fieldset>
</form>
in achievement am expected to redirect to error or index page but my code above refress back to first form what are my doing wrong. Big thanks in advance
I am wanting to populate a drop down list from another mysql table and then assign the values from two of the columns into variables - i.e. "select name, eid, perc from employee". "John Doe" would be $eid = 1234 and $perc = 20.
Any help with this would be greatly appreciated!
Thank you - Matt
Here is the code I have been working with:
PHP
<?php
//session_start();
$page_title = 'New invoice';
include ('includes/header.html');
// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require ('mysqli_connect.php'); // Connect to the db.
/*$errors = array(); // Initialize an error array. */
// Invoice number is automatic
if (empty($_POST['op1'])) {
$errors[] = 'Operation needs to be entered.';
} else {
$op1 = mysqli_real_escape_string($dbc, trim($_POST['op1']));
}
// Amount:
if (empty($_POST['amount1'])) {
$errors[] = 'Amount to be charged.';
} else {
$amount1 = mysqli_real_escape_string($dbc, trim($_POST['amount1']));
}
// percentage:
if (empty($_POST['perc'])) {
$errors[] = 'Select a percentage.';
} else {
$perc = mysqli_real_escape_string($dbc, trim($_POST['perc']));
}
// eid:
if (empty($_POST['eid'])) {
$errors[] = 'Enter a techician.';
} else {
$eid = mysqli_real_escape_string($dbc, trim($_POST['eid']));
}
// Stocknum:
if (empty($_POST['stocknum'])) {
$errors[] = 'Need a stock number.';
} else {
$stocknum = mysqli_real_escape_string($dbc, trim($_POST['stocknum']));
}
// Stocknum:
if (empty($_POST['myear'])) {
$errors[] = 'Enter vehicle year.';
} else {
$myear = mysqli_real_escape_string($dbc, trim($_POST['myear']));
}
if (empty($_POST['make'])) {
$errors[] = 'Enter vehicle make.';
} else {
$make = mysqli_real_escape_string($dbc, trim($_POST['make']));
}
if (empty($_POST['model'])) {
$errors[] = 'Enter vehicle model.';
} else {
$model = mysqli_real_escape_string($dbc, trim($_POST['model']));
}
if (empty($_POST['vin'])) {
$errors[] = 'Enter last 6 of the VIN.';
} else {
$vin = mysqli_real_escape_string($dbc, trim($_POST['vin']));
}
if (empty($_POST['mileage'])) {
$errors[] = 'Enter current mileage.';
} else {
$mileage = mysqli_real_escape_string($dbc, trim($_POST['mileage']));
}
if (empty($errors)) { // If everything's OK.
$q = "INSERT INTO `mwcc`.`wp` (`tdate`, `stocknum`, `myear`, `make`, `model`,`vin`, `eid`, `op1`, `amount1`,`mileage`,`ecomm`) VALUES (CURRENT_DATE(), '$stocknum', '$myear', '$make', '$model','$vin', '$eid', '$op1', '$amount1','$mileage', ($amount1*$perc));";
$r = #mysqli_query ($dbc, $q); // Run the query.
//echo ($q);
if ($r) { // If it ran OK.
// Print a message:
echo '<h1>Success!</h1>
<p>Invoice has been created!<br /></p>';
} else { // If it did not run OK.
// Public message:
echo '<h1>System Error</h1>
<p class="error">Uh oh. There has been an error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';
} // End of if ($r) IF.
mysqli_close($dbc); // Close the database connection.
exit();
} else { // Report the errors.
echo '<h1>Error!</h1>
<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br />\n";
}
echo '</p><p>Please try again.</p><p><br /></p>';
} // End of if (empty($errors)) IF.
mysqli_close($dbc); // Close the database connection.
} // End of the main Submit conditional.
?>
HTML :
<form action="newinv.php" method="post">
<p>Stock #
<input type="text" name="stocknum" size="15" maxlength="20" value="<?php if (isset($_POST['stocknum'])) echo $_POST['stocknum']; ?>" />
Last 6 of VIN
<input type="text" name="vin" size="15" maxlength="6" value="<?php if (isset($_GET['vin'])) echo $_POST['vin']; ?>" /> </p>
<p>Year
<input type="text" name="myear" size="4" maxlength="4" value="<?php if (isset($_POST['myear'])) echo $_POST['myear']; ?>" />
Make
<input type="text" name="make" size="30" maxlength="20" value="<?php if (isset($_POST['make'])) echo $_POST['make']; ?>" />
Model
<input type="text" name="model" size="30" maxlength="20" value="<?php if (isset($_POST['model'])) echo $_POST['model']; ?>" /></p>
Mileage
<input type="text" name="mileage" sizesize="15" maxlength="6" value="<?php if (isset($_POST['mileage'])) echo $_POST['mileage']; ?>" /> </p>
<p>Operation <input type="text" name="op1" size="60" maxlength="250" value="<?php if (isset($_POST['op1'])) echo $_POST['op1']; ?>" />
Amount <input type="text" name="amount1" size="8" maxlength="20" value="<?php if (isset($_POST['amount1'])) echo $_POST['amount1']; ?>" /></p>
<br>
<input type="radio" name="eid" value="1767">Alex H<br>
<input type="radio" name="eid" value="1688">Blake S<br>
<input type="radio" name="eid" value="1506">Brian M<br>
<input type="radio" name="eid" value="1898">Chris V<br>
<input type="radio" name="eid" value="3000">Kim R<br>
<input type="radio" name="eid" value="1916">Jorden U<br>
<input type="radio" name="eid" value="1931">Tina M<br>
<input type="radio" name="eid" value="1506">Tanner C<br>
<br>
<input type="radio" name="perc" value=".35">35%
<br>
<input type="radio" name="perc" value=".40">40%
<p><input type="submit" name="submit" value="Add" /></p>
</form>
My understanding from your question.
Get query result as you mentioned.select name, eid, perc from employee
For Front End if you want pass both values in single select then use some unique separator like i'm using double underscore __
<?php foreach($result as $user): ?>
<select name="eid__perc" >
<option value="<?php $user->eid . '__' . $user->perc?>">
<?php $user->name; //in array case $user['name'];?>
<option>
<select>
<?php endforeach;?>
And when you save information use same separator to explode data like
list($eid, $perc) = explode('__', $_POST['eid__per'])
You need to use WHERE condition for that:
SELECT name, eid, perc FROM employee WHERE eid = ? AND perc = ?
Than use mysqli_stmt_bind_param($stmt, 'ss', $eid, $perc); to bind parameters.
I wrote a customer_display.php to validate data (only First Name so far), but no matter First Name field is empty or not, the webpage will jump to customer_search.php & did not change information in database. why?
<?php include '../view/header.php';
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// Initialize variables and set to empty strings
$firstName=$lastName="";
$firstNameErr=$lastNameErr="";
// Control variables
$app_state = "empty"; //empty, processed, logged in
$valid = 0;
// Validate input and sanitize
if ($_SERVER['REQUEST_METHOD']== "POST") {
if(isset($_POST["first_name"]))
{
if (empty($_POST["first_name"])) {
$firstNameErr = "First name is required";
}
else {
$firstName = test_input($_POST["firstName"]);
if(strlen($firstName)>5){
$firstNameErr = "First name is too long";
}
else{
$valid++;
}
}
}
if (empty($_POST["lastName"])) {
$lastNameErr = "Last name is required";
}
else {
$lastName = test_input($_POST["lastName"]);
$valid++;
}
if ($valid >= 2) {
$app_state = "processed";
}
}
// Sanitize data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($app_state == "empty") {
?>
<!-- display a table of customer information -->
<h2>View/Update Customer</h2>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="POST" id="aligned">
<input type="hidden" value="update_customer">
<input type="hidden" name="customer_id"
value="<?php echo htmlspecialchars($customer['customerID']); ?>">
<label>First Name:</label>
<input type="text" name="first_name"
value="<?php echo htmlspecialchars($customer['firstName']); ?>">
<span class="error"><?php echo $firstNameErr;?></span><br>
<label>Last Name:</label>
<input type="text" name="last_name"
value="<?php echo htmlspecialchars($customer['lastName']); ?>"><br>
<label>Address:</label>
<input type="text" name="address"
value="<?php echo htmlspecialchars($customer['address']); ?>"
size="50"><br>
<label>City:</label>
<input type="text" name="city"
value="<?php echo htmlspecialchars($customer['city']); ?>"><br>
<label>State:</label>
<input type="text" name="state"
value="<?php echo htmlspecialchars($customer['state']); ?>"><br>
<label>Postal Code:</label>
<input type="text" name="postal_code"
value="<?php echo htmlspecialchars($customer['postalCode']); ?>"><br>
<label>Country:</label>
<select name="selected">
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass ='';
$db = 'tech_support';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db);
if($conn->connect_error)
die('Could not connect: '. $conn->connect_error);
$selected= $conn->query("select * from countries where countryCode = '" .$customer['countryCode']. "'");
$sql = $conn->query("select * from countries order by countryName");
if($selectedrow = $selected->fetch_assoc()){
echo "<option selected value='" . $selectedrow['countryName']."'>". $selectedrow['countryName']."</option>";
}
//echo "<select>";
while ($row = $sql->fetch_assoc()) {
echo "<option value ='". $row['countryName']."'>". $row['countryName']."</option>";
}
//echo "</select>";
$conn->close();
?>
</select><br>
<label>Phone:</label>
<input type="text" name="phone"
value="<?php echo htmlspecialchars($customer['phone']); ?>"><br>
<label>Email:</label>
<input type="text" name="email"
value="<?php echo htmlspecialchars($customer['email']); ?>"
size="50"><br>
<label>Password:</label>
<input type="text" name="password"
value="<?php echo htmlspecialchars($customer['password']); ?>"><br>
<label> </label>
<input type="submit" value="Update Customer"><br>
</form>
<p>Search Customers</p>
</body>
</html>
<?php
}
elseif ($app_state == "processed") {
if ($firstName == "Vincent") {
$app_state = "Logged in";
}
}
if ($app_state == "Logged in") {
echo("Logged in<br> Hello Vincent</body></html>");
}
?>
<?php include '../view/footer.php'; ?>
index.php(to process the data):
<?php
require('../model/database.php');
require('../model/customer_db.php');
$action = filter_input(INPUT_POST, 'action');
if ($action === NULL) {
$action = filter_input(INPUT_GET, 'action');
if ($action === NULL) {
$action = 'search_customers';
}
}
//instantiate variable(s)
$last_name = '';
$customers = array();
if ($action == 'search_customers') {
include('customer_search.php');
} else if ($action == 'display_customers') {
$last_name = filter_input(INPUT_POST, 'last_name');
if (empty($last_name)) {
$message = 'You must enter a last name.';
} else {
$customers = get_customers_by_last_name($last_name);
}
include('customer_search.php');
} else if ($action == 'display_customer') {
$customer_id = filter_input(INPUT_POST, 'customer_id', FILTER_VALIDATE_INT);
$customer = get_customer($customer_id);
include('customer_display.php');
} else if ($action == 'update_customer') {
$customer_id = filter_input(INPUT_POST, 'customer_id', FILTER_VALIDATE_INT);
$first_name = filter_input(INPUT_POST, 'first_name');
//echo $first_name;
$last_name = filter_input(INPUT_POST, 'last_name');
$address = filter_input(INPUT_POST, 'address');
$city = filter_input(INPUT_POST, 'city');
$state = filter_input(INPUT_POST, 'state');
$postal_code = filter_input(INPUT_POST, 'postal_code');
$country_name = $_POST["selected"];
$phone = filter_input(INPUT_POST, 'phone');
$email = filter_input(INPUT_POST, 'email');
$password = filter_input(INPUT_POST, 'password');
//if(!$valid_fname == null){require ('customer_display.php');};
//echo $country_name;
$country_code = get_countryCode($country_name);
update_customer($customer_id, $first_name, $last_name,
$address, $city, $state, $postal_code, $country_code,
$phone, $email, $password);
include('customer_search.php');
}
?>
You have no name attribute with the value of 'action', so your update never happens.
<form action="" method="POST">
<input type="hidden" value="update_customer">
<!-- rest of the form -->
</form>
Edited for clarity.
I have made a page for registering hardware, with 2 drop-down menus, which work.
The page looks like this:
<!DOCTYPE HTML>
<html>
<head>
<title>Registrer ny hardware</title>
</head>
<body>
Her registreres ny hardware. Udfyld formularen herunder og tryk gem. <br>
<form action="Registerhardware.php" method="post">
<!-- VARCHAR -->
Serienr: <br>
<input type="text" name="Series"> <br>
<!-- VARCHAR -->
Mærke: <br>
<select id="Brand" name="Brand">
<?php
include('Mysql.php');
$conn = new mysqli($server, $user, $password, $database);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
$sql = "SELECT Brand FROM hardware";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
$Brand=$row["Brand"];
echo "<option>
$Brand
</option>";
}
?>
</select>
<br>
<!-- <input type="text" name="Brand"> <br> -->
<!-- VARCHAR -->
Model: (* <a href=Registernymodel.php>Ny model - læg den ind her først</a>)<br>
<select id="Model" name="Model">
<?php
// include('Mysql.php');
// $conn = new mysqli($server, $user, $password, $database);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
$sqlm = "SELECT Model FROM hardware";
$resultm = $conn->query($sqlm);
while($rowm = $resultm->fetch_assoc())
{
$Model=$rowm["Model"];
echo "<option>
$Model
</option>";
}
?>
</select>
<br>
<!-- VARCHAR -->
Detaljer: <br>
<input type="text" name="Detaljer"> <br>
<!-- VARCHAR -->
Indkøbsdato (yyyy-dd-mm): <br>
<input type="date" name="Date"> <br>
<!-- VARCHAR -->
Leverandør: <br>
<input type="text" name="Firm"> <br>
<!-- VARCHAR -->
Hardwarenavn: <br>
<input type="text" name="Hardwarename"> <br>
<!-- VARCHAR -->
<!-- INT -->
Stregkode: <br>
<input type="number" name="Barcode"> <br>
<!-- VARCHAR -->
Placering: <br>
<input type="text" name="Place"> <br><br>
<!-- ENUM -->
SIMKort: <br>
<input type="radio" name="SIMCard" value="Ja">Ja
<input type="radio" name="SIMCard" value="Nej" checked>Nej<br><br>
<!-- ENUM -->
På lager: <br>
<input type="radio" name="Stock" value="Ja" checked>Ja
<input type="radio" name="Stock" value="Nej">Nej<br><br>
<!-- ENUM -->
Udlånes: <br>
<input type="radio" name="Borrow" value="Ja" >Ja
<input type="radio" name="Borrow" value="Nej" checked>Nej<br><br>
<!-- TEXT -->
Kommentarer: <br>
<textarea name="Comments" style="width: 200px; height: 50px;"> </textarea> <br>
<input type="submit" value="Gem og send mail">
</form>
</body>
</html>
But now I'm trying to edit data from one post in the table, but the first drop-down menu doesn't have any data and the form stops there.
The page looks like this:
<?php
/*
Allows the user to both create new records and edit existing records
*/
// connect to the database
include("Mysql.php");
// creates the new/edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($Serienr = '', $Hardwarenavn ='', $error = '', $IDNr = '')
{ ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>
<?php if ($IDNr != '') { echo "Edit Record"; } else { echo "New Record"; } ? >
</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<h1><?php if ($IDNr != '') { echo "Edit Record"; } else { echo "New Record"; } ?></h1>
<?php if ($error != '') {
echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error
. "</div>";
} ?>
<form action="" method="post">
<div>
<?php if ($IDNr != '') { ?>
<input type="hidden" name="IDNr" value="<?php echo $IDNr; ?>" />
<p>IDNr: <?php echo $IDNr; ?></p>
<?php } ?>
<strong>IDNr: *</strong> <input type="text" name="IDNr"
value="<?php echo $IDNr; ?>"/><br/>
<strong>Serienummer: *</strong> <input type="text" name="Series"
value="<?php echo $Serienr; ?>"/><br/>
<strong>Mærke: *</strong>
<select id="Brand" name="Brand">
<?php
include('Mysql.php');
$conn = new mysqli($server, $user, $password, $database);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
$sql = "SELECT Brand FROM hardware";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
$Brand=$row["Brand"];
echo
"<option>
$Brand
</option>";
}
?>
</select>
<br>
<br/>
<strong>Model: *</strong>
<select id="Model" name="Model">
<?php
// include('Mysql.php');
// $conn = new mysqli($server, $user, $password, $database);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
$sqlm = "SELECT Model FROM hardware";
$resultm = $conn->query($sqlm);
while($rowm = $resultm->fetch_assoc())
{
$Model=$rowm["Model"];
echo "<option>
$Model
</option>";
}
?>
</select>
<br>
<br/>
<strong>Detaljer: *</strong> <input type="text" name="Detaljer"
value="<?php echo $Detaljer; ?>"/><br/>
<strong>Dato: *</strong> <input type="date" name="Date"
value="<?php echo $Date; ?>"/><br/>
<strong>Leverandør: *</strong> <input type="text" name="Firm"
value="<?php echo $Firm; ?>"/><br/>
<strong>Hardwarenavn: *</strong> <input type="text" name="Hardwarename"
value="<?php echo $Hardwarenavn; ?>"/><br/>
<strong>Stregcode: *</strong> <input type="number" name="Barcode"
value="<?php echo $Barcode; ?>"/><br/>
<strong>Lokation: *</strong> <input type="text" name="Place"
value="<?php echo $Placering; ?>"/><br/>
<strong>SIMKort: *</strong> <input type="radio" name="SIMCard"
value="<?php echo $SIMKort; ?>"/><br/>
<strong>Lager: *</strong> <input type="radio" name="Stock"
value="<?php echo $Stock; ?>"/><br/>
<strong>Udlånes: *</strong> <input type="radio" name="Borrow"
value="<?php echo $Udlaan; ?>"/><br/>
<strong>Kommentarer: *</strong> <input type="text" name="Comments"
value="<?php echo $Kommentarer; ?>"/><br/>
<p>* required</p>
<input type="submit" name="submit" value="Submit" />
</div>
</form>
</body>
</html>
<?php }
/*
EDIT RECORD
*/
// if the 'id' variable is set in the URL, we know that we need to edit a record
if (isset($_GET['IDNr']))
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// make sure the 'id' in the URL is valid
if (is_numeric($_POST['IDNr']))
{
// get variables from the URL/form
$IDNr = $_POST['IDNr'];
$Serienr = htmlentities($_POST['Series'], ENT_QUOTES);
$Brand = htmlentities($_POST['Brand'], ENT_QUOTES);
$Model = htmlentities($_POST['Model'], ENT_QUOTES);
$Detaljer = htmlentities($_POST['Detaljer'], ENT_QUOTES);
$Date = htmlentities($_POST['Date'], ENT_QUOTES);
$Firm = htmlentities($_POST['Firm'], ENT_QUOTES);
$Hardwarenavn = htmlentities($_POST['Hardwarename'], ENT_QUOTES);
$Barcode = htmlentities($_POST['Barcode'], ENT_QUOTES);
$Placering = htmlentities($_POST['Place'], ENT_QUOTES);
$SIMKort = htmlentities($_POST['SIMCard'], ENT_QUOTES);
$Stock = htmlentities($_POST['Stock'], ENT_QUOTES);
$Udlaan = htmlentities($_POST['Borrow'], ENT_QUOTES);
$Kommentarer = htmlentities($_POST['Comments'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($Serienr == '' || $Hardwarenavn == '')
{
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($Serienr, $Hardwarenavn, $error, $IDNr);
}
else
{
// if everything is fine, update the record in the database
if ($stmt = $conn->prepare("UPDATE registrering SET Series = ?, Hardwarename = ?
WHERE IDNr=?"))
{
$stmt->bind_param("ssi", $Serienr, $Hardwarenavn, $IDNr);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else
{
echo "ERROR: could not prepare SQL statement.";
}
// redirect the user once the form is updated
header("Location: view.php");
}
}
// if the 'id' variable is not valid, show an error message
else
{
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else
{
// make sure the 'id' value is valid
if (is_numeric($_GET['IDNr']) && $_GET['IDNr'] > 0)
{
// get 'id' from URL
$IDNr = $_GET['IDNr'];
// get the record from the database
$conn = new mysqli($server, $user, $password, $database);
if($stmt = $conn->prepare("SELECT * FROM registrering WHERE IDNr=?"))
{
$stmt->bind_param("i", $IDNr);
$stmt->execute();
$stmt->bind_result($IDNr, $Serienr, $Brand, $Model, $Detaljer, $Date, $Firm, $Hardwarenavn, $Barcode, $Placering, $SIMKort, $Stock, $Udlaan, $Kommentarer);
$stmt->fetch();
// show the form
renderForm($Serienr, $Hardwarenavn, NULL, $IDNr);
$stmt->close();
}
// show an error if the query has an error
else
{
echo "Error: could not prepare SQL statement";
}
}
// if the 'id' value is not valid, redirect the user back to the view.php page
else
{
header("Location: view.php");
}
}
}
/*
NEW RECORD:
*/
// if the 'id' variable is not set in the URL, we must be creating a new record
else
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// get the form data
$IDNr = $_POST['IDNr'];
$Serienr = htmlentities($_POST['Series'], ENT_QUOTES);
$Brand = htmlentities($_POST['Brand'], ENT_QUOTES);
$Model = htmlentities($_POST['Model'], ENT_QUOTES);
$Detaljer = htmlentities($_POST['Detaljer'], ENT_QUOTES);
$Date = htmlentities($_POST['Date'], ENT_QUOTES);
$Firm = htmlentities($_POST['Firm'], ENT_QUOTES);
$Hardwarenavn = htmlentities($_POST['Hardwarename'], ENT_QUOTES);
$Barcode = htmlentities($_POST['Barcode'], ENT_QUOTES);
$Placering = htmlentities($_POST['Place'], ENT_QUOTES);
$SIMKort = htmlentities($_POST['SIMCard'], ENT_QUOTES);
$Stock = htmlentities($_POST['Stock'], ENT_QUOTES);
$Udlaan = htmlentities($_POST['Borrow'], ENT_QUOTES);
$Kommentarer = htmlentities($_POST['Comments'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($Serienr == '' || $Hardwarenavn == '')
{
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($Serienr, $Hardwarenavn, $error);
}
else
{
// insert the new record into the database
if ($stmt = $conn->prepare("INSERT rgistrering (Series, Hardwarename) VALUES (?, ?)"))
{
$stmt->bind_param("ss", $Serienr, $Hardwarenavn);
$stmt->execute();
$stmt->close();
}
// show an error if the query has an error
else
{
echo "ERROR: Could not prepare SQL statement.";
}
// redirec the user
header("Location: view.php");
}
}
// if the form hasn't been submitted yet, show the form
else
{
renderForm();
}
}
// close the mysqli connection
$conn->close();
?>
What have I done wrong?