How to get information from an already populated form - php

I am trying to update a database record using a submit button, however the form that information is being taken from has itself been populated by another submit button.
The PHP is below:
if (isset($_POST['edit']))
{
$editUser = User::locate($_POST['userSelect']);
$setCompany = Company::findCompany();
$exCompanyId = $editUser->user_company_id;
$isAdmin = $editUser->user_admin;
$eUserFirstname = $editUser->user_firstname;
$eUserLastname = $editUser->user_lastname;
$eUserUsername = $editUser->user_username;
$eUserEmail = $editUser->user_email;
$eUserCompany = $editUser->user_company;
$adminArray = array("Yes","No");
if ($exCompanyId > NULL)
{
$exCompany = Company::locateId($exCompanyId);
$companyValue = $exCompany->company_name;
}
else
{
$companyValue = "";
}
if ($isAdmin > 0)
{
$userAdmin = $adminArray[0];
}
else
{
$userAdmin = $adminArray[1];
}
}
if (isset($_POST['confirm']))
{
$updateUserRecord = User::locate($eUserUsername);
$newCompanyValue = $_POST['setCompany'];
$isAdmin = $_POST['userAdmin'];
$newCompany = Company::locate($newCompanyValue);
$companyId = $newCompany->company_id;
$updateUserRecord->user_company_id = $companyId;
$updateUserRecord->user_admin = $isAdmin;
$editUser->updateUserAdmin();
$message = "You have successfully updated the user account";
echo "<script type='text/javascript'>alert('$message');</script>";
}
The HTML code is below:
<form action="" method="post">
<p>
<label>First Name:</label>
<label><?php echo $eUserFirstname ?></label>
</p>
<p>
<label>Last Name:</label>
<label><?php echo $eUserLastname ?></label>
</p>
<p>
<label>Username:</label>
<label><?php echo $eUserUsername ?></label>
</p>
<p>
<label>Email Address:</label>
<label><?php echo $eUserEmail ?></label>
</p>
<p>
<label>User Company:</label>
<label><?php echo $eUserCompany ?></label>
</p>
<p>
<label>Set Company:</label>
<select name="setCompany">
<option><?php echo $companyValue ?></option>
<?php
foreach ($setCompany as $srow)
{
?>
<option id="<?=
$srow->company_id
?>">
<?=
$srow->company_name
?>
</option>
<?php
}
?>
</select>
</p>
<p>
<label>Administrator:</label>
<select name="userAdmin">
<option><?php echo $userAdmin ?></option>
<?php
foreach ($adminArray as $arow)
{
?>
<option>
<?=
$arow
?>
</option>
<?php
}
?>
</select>
</p>
<input type="submit" name="cancel" value="Cancel">
<input type="submit" name="confirm" value="Confirm">
</br>
</form>
From my investigations so far the variables aren't transferring to the 2nd if statement, and I'm not sure how to make them available to it.

Store the first form's submission in hidden input fields alongside your echo statements. For example: <input type="hidden" name="field_name" value="<?php echo htmlspecialchars($field); ?>">
Or, alternatively, update the DB after first form posts.

Related

Populating checkboxes from database using PHP - only last option is getting checked

I am trying to populate checkboxes with the data from my mysql database but for some reason only the last checkbox is being checked (for example if automotive, carpentry and hand tools should be checked, only hand tools is being checked) and I can't figure out why. The mysql statement is running correctly and giving me the correct information. Here is the relevant code.
<?php
require_once('../../private/initialize.php');
require_login();
if(!isset($_GET['id'])) {
redirect_to(url_for('/members/show_member_tools.php'));
}
$id = $_GET['id'];
if(is_post_request()) {
// Handle form values sent by new.php
$tool = [];
$tool['tool_ID'] = $id;
$tool['serial_number'] = $_POST['serial_number'] ?? '';
$tool['tool_name'] = $_POST['tool_name'] ?? '';
$tool['tool_description'] = $_POST['tool_description'] ?? '';
$tool['tool_picture'] = $_POST['tool_picture'] ?? '';
$category =[];
$category = $_POST['category_ID'];
$result = update_tool($tool, $category);
//get info for checkboxes
global $db;
if($result === true) {
$_SESSION['message'] = "The tool has been updated sucessfully";
redirect_to(url_for('/members/show_tool.php?id=' . $id));
} else {
$errors = $result;
}
} else {
$tool = find_tool_by_id($id);
if(isset($_GET['id'])){
$id=$_GET['id'];
$sql = "select category_name from category INNER JOIN tool_category ON category.category_ID = tool_category.category_ID where tool_category.tool_id=$id";
$query = mysqli_query($db, $sql);
while($row=mysqli_fetch_array($query)) {
// $str = "";
$str = $row['category_name'];
echo $str;
if (strpos($str , "automotive")!== false){
$checked1 ="checked";
echo "made it to automotive";
} else {
$checked1 ="";
}
if (strpos($str , "carpentry")!== false){
$checked2 ="checked";
echo "made it to carpentry";
} else {
$checked2 ="";
}
if (strpos($str , "home maintenance")!== false){
$checked3 ="checked";
echo "made it to home maintenance";
} else {
$checked3 ="";
}
if (strpos($str , "plumbing")!== false){
$checked4 ="checked";
} else {
$checked4 ="";
}
if (strpos($str , "yard and garden")!== false){
$checked5 ="checked";
} else {
$checked5 ="";
}
if (strpos($str , "hand tools")!== false){
$checked6 ="checked";
} else {
$checked6 ="";
}
}//end while loop
} //end if
} //end else
$tool_set = find_all_tools();
$tool_count = mysqli_num_rows($tool_set);
mysqli_free_result($tool_set);
?>
<?php $page_title = 'Edit Tool'; ?>
<?php include(SHARED_PATH . '/header.php'); ?>
<div id="content">
<div class="center">
« Back to My Tools
<h2>Edit Tool</h2>
</div>
<?php echo display_errors($errors); ?>
<form action="<?php echo url_for('/members/edit_tool.php?id=' . h(u($id))); ?>" method="post">
<fieldset class="form">
<img src ="<?php echo h($tool['tool_picture']); ?>" alt="<?php echo h($tool['tool_picture']); ?>"width="150"><br>
<label for="serial_number">Serial Number</label><br>
<input type="text" name="serial_number" value="<?php echo h($tool['serial_number']); ?>" ><br>
<label for="tool_name">Tool Name</label><br>
<input type="text" name="tool_name" value="<?php echo h($tool['tool_name']); ?>" ><br>
<label for="tool_description">Tool Description</label><br>
<input type="text" name="tool_description" value="<?php echo h($tool['tool_description']); ?>" ><br>
<label for="category_ID">Tool Category: </label><br>
<input type="checkbox" name="category_ID[]" value="1" <?php echo $checked1; ?>> <label for="1">Automotive</label> <br>
<input type="checkbox" name="category_ID[]" value="2" <?php echo $checked2; ?>> <label for="2">Carpentry</label> <br>
<input type="checkbox" name="category_ID[]" value="3" <?php echo $checked3; ?>> <label for="3">Home Maintenance</label> <br>
<input type="checkbox" name="category_ID[]" value="4" <?php echo $checked4; ?>> <label for="4">Plumbing </label><br>
<input type="checkbox" name="category_ID[]" value="5" <?php echo $checked5; ?>> <label for="5">Yard and Garden</label> <br>
<input type="checkbox" name="category_ID[]" value="6" <?php echo $checked6; ?>> <label for="6">Hand Tools</label> <br>
<input type="submit" value="Edit Tool" >
<a class="block" href="<?php echo url_for('/members/delete_tool.php?id=' . $id); ?>">Delete Tool</a>
</fieldset>
</form>
<div class="push"></div>
</div>
<?php include(SHARED_PATH . '/footer.php'); ?>
You're looping over your results. This means with every loop you're setting one variable to "checked" and the rest to an empty string. So only the last one will be checked. The band-aid fix is to set unchecked as the default outside of the loop, and then change to checked only when it's needed.
But the real fix is to be pulling this info from the database and working with it instead of manually mapping database IDs to labels. By moving your condition into the join, you pull all the categories. The rows that have a tool ID are checked, and the others are not. You're also pulling the category names and IDs so you can programmatically build your checkboxes.
See here for DB sample: http://sqlfiddle.com/#!9/20b223/14/0
$tool = find_tool_by_id($id);
$tool["categories"] = [];
$sql = "SELECT c.category_name, c.category_ID, tc.tool_id
FROM category c
LEFT JOIN tool_category tc ON c.category_ID = tc.category_id
AND tc.tool_id = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param("i", $_GET["id"]);
$result = $stmt->execute();
while($row = $stmt->fetch_assoc()) {
$id = $row["category_ID"];
$name = $row["category_name"];
$checked = $row["tool_id"] ? "checked" : "";
$tool["categories"][$id] = ["name" => $name, "checked" => $checked];
}
Now later on you can do this to automatically build all your checkbox inputs:
<?php foreach ($tool["categories"] as $id=>$category): ?>
<input type="checkbox" name="category_ID[]" id="category_<?=$id?>" value="<?=$id?>" <?=$category["checked"]?>>
<label for="category_<?=$id?>">
<?=htmlspecialchars($category["name"])?>
</label><br/>
<?php endforeach ?>

How to post only variable with values and ignore blank inputs in PHP?

Forms input value variables are the same changing only labels for it from DB. When form selected other ones is hidden with "style.display = "none".
The problem that I face how to prevent sending empty values from none visible input fields?
Tried a trim function but didn't work for me. Maybe didn't use it correctly.
I'm trying to accomplish that input value would stay the same regardless of what user would select and only labels would change.
dump output
<?php
if (isset($_POST["save"])) {
if (empty($_POST['price'])) {
$error["price"] = "Price Required";
} else {
$price = $_POST["price"];
}
if (array_filter($error)) {
echo "Input error";
} else {
$price = ($_POST['price']);
$value1 = ($_POST['value1']) ?? null;
$value2 = $_POST['value2'] ?? null;
$value3 = $_POST['value3'] ?? null;
}
}
// insert size
$sql = "INSERT INTO valueSize(value1, value2, value3) values('$value1', '$value2, '$value3')";
$stmt = $pdo->prepare($sql);
$stmt->execute();
?>
<!DOCTYPE html>
<html lang="en">
<form action="">
<?php foreach ($categoriesTypeId as $key): ?>
<div class="dropItem invisible" id="<?php echo $key['id'] ?>">
<label for="value1"><?php echo $key['value1Type'] ?>:</label>
<input type="text" name="value1[]" value="<?php echo $value1 ?>">
<div class="error"><?php echo $error['value1'] ?></div>
<?php if (isset($key['value2Type'])) {?>
<div class="inputCheck">
<label for="value2"><?php echo $key['value2Type'] ?>
:</label>
<input type="text" name="value2" value="<?php echo $value2 ?>">
<div class="error"><?php echo $error['value2'] ?></div>
</div>
<?php
}
;
?>
<?php if (isset($key['value3Type'])) {?>
<div class="inputCheck">
<label for="value3"><?php echo $key['value3Type'] ?>
:</label>
<input type="text" name="value3" value="<?php echo $value3 ?>">
<div class="error"><?php echo $error['value3'] ?></div>
</div>
<?php
} else {
}
?>
<?php endforeach;?>
</form>
</html>

multiple checkbox check if value in database?

code:
<?php
$id = $_GET['id'];
$sql = "select * from admin_menu where id = '$id'";
$result = mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($result))
{
$menu_name = $row['menu_name'];
$menu_link = $row['menu_link'];
$priority = $row['priority'];
$admin_id = explode(",", $row['admin_id']);
}
if(isset($_POST['update']))
{
$admin_id = $_POST['admin_id'];
$chk="";
foreach($admin_id as $chk1)
{
$chk .= $chk1.",";
}
$menu_name = $_POST['menu_name'];
$menu_link = $_POST['menu_link'];
$priority = $_POST['priority'];
$sql = "update admin_menu set menu_name = '$menu_name', menu_link = '$menu_link', priority = '$priority', admin_id = '$chk' where id = '$id'";
$result = mysqli_query($link,$sql);
if($result == true)
{
$msg .= "<h3 style='color:green;'>update</h3>";
}
else
{
$msg .= "<h3 style='color:red;'>Error!</h3>";
}
}
?>
<form name="myform" method="post" >
<div class="row">
<label for="Producer_firstname">Admin Name</label>
<?php
foreach ($admin_id as $admin_id)
{
$chk = "";
if (in_array($chk, $admin_id))
{
$chk = 'checked="checked" ';
}
echo '<input type="checkbox" name="admin_id[]" value="'.$admin_id.'" '.$chk.'/><br/>';
}
?>
</div>
<div class="row">
<label for="Producer_firstname">Menu Name </label>
<input size="60" maxlength="255" name="menu_name" id="menu_name" value="<?php echo $menu_name; ?>" type="text" />
</div>
<div class="row">
<label for="Producer_lastname" >Menu Link </label>
<input size="60" maxlength="255" name="menu_link" id="menu_link" type="text" value="<?php echo $menu_link; ?>" />
</div>
<div class="row">
<label for="Producer_lastname" >Priority</label>
<select name="priority" id="priority">
<option value="<?php echo $priority; ?>"><?php echo $priority; ?></option>
<option value="">choose any one</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
</div>
<div class="row buttons">
<button type="submit" name='update' id='update'>update Menu</button>
</div>
</form>
In this code I am fetching multiple checkbox value from table admin2 and I want when I update form value checkbox check if the value of checkbox is exist into database. How can I fix it ?
Thank You
Your code has few issues,
1. Update should be done before select query
2. List of admin not managed separately
3. Priority radio buttons not managed properly
Additional Suggestions,
1. Use prepare query statements
2. use implode for appending multiple values instead of foreach
3. print admin names before checkboxes
<?php
$id = $_GET['id'];
if(isset($_POST['update']))
{
$chk = implode(',', $_POST['admin_id']);
$menu_name = $_POST['menu_name'];
$menu_link = $_POST['menu_link'];
$priority = $_POST['priority'];
$sql = "update admin_menu set menu_name = '$menu_name', menu_link = '$menu_link', priority = '$priority', admin_id = '$chk' where id = '$id'";
$result = mysqli_query($link,$sql);
$msg = "";
if($result == true)
{
$msg .= "<h3 style='color:green;'>update</h3>";
}
else
{
$msg .= "<h3 style='color:red;'>Error!</h3>";
}
echo $msg;
}
$sql = "select * from admin_menu where id = '$id'";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
$menu_name = $row['menu_name'];
$menu_link = $row['menu_link'];
$priority = $row['priority'];
$admin_id = explode(",", $row['admin_id']);
$admins = array('admin1', 'admin2', 'admin3', 'admin4', 'admin5', 'admin6', 'admin7', 'admin8');
?>
<form name="myform" method="post" >
<div class="row">
<label for="Producer_firstname">Admin Name</label>
<?php
foreach ($admins as $admin)
{
$chk = "";
if (in_array($admin, $admin_id))
{
$chk = 'checked="checked" ';
}
echo $admin.' <input type="checkbox" name="admin_id[]" value="'.$admin.'" '.$chk.'/><br/>';
}
?>
</div>
<div class="row">
<label for="Producer_firstname">Menu Name </label>
<input size="60" maxlength="255" name="menu_name" id="menu_name" value="<?php echo $menu_name; ?>" type="text" />
</div>
<div class="row">
<label for="Producer_lastname" >Menu Link </label>
<input size="60" maxlength="255" name="menu_link" id="menu_link" type="text" value="<?php echo $menu_link; ?>" />
</div>
<div class="row">
<label for="Producer_lastname" >Priority</label>
<select name="priority" id="priority">
<option value="1" <?php if($priority == 1) echo "selected='selected'"; ?>>1</option>
<option value="0" <?php if($priority == 0) echo "selected='selected'"; ?>>0</option>
</select>
</div>
<div class="row buttons">
<button type="submit" name='update' id='update'>update Menu</button>
</div>
</form>

How to create a selection dropdown in php form

I am working on a project and would like to give the user per-determined values when updating a record.
Here is my code so far.
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>School Name:</strong> <input type="text" name="Name" value="<?php echo $Name; ?>"/><br/><br>
<strong>Status:</strong> <input type="text" name="Status" value="<?php echo $Status; ?>"/><br/><br>
<strong>Comments:</strong> <input type="text" name="Comments" value="<?php echo $Comments; ?>"/><br/><br>
<strong>Type:</strong> <input type="text" name="Type" value="<?php echo $Type; ?>"/><br/><br>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$Name = mysql_real_escape_string(htmlspecialchars($_POST['Name']));
$Status = mysql_real_escape_string(htmlspecialchars($_POST['Status']));
$Comments = mysql_real_escape_string(htmlspecialchars($_POST['Comments']));
$Type = mysql_real_escape_string(htmlspecialchars($_POST['Type']));
// check that firstname/lastname fields are both filled in
if ($Name == '' || $Type == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $Name, $Status, $Comments, $Type, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE Schools SET Name='$Name', Status='$Status', Comments='$Comments', Type='$Type' WHERE id='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM Schools WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$Name = $row['Name'];
$Status = $row['Status'];
$Comments = $row['Comments'];
$Type = $row['Type'];
// show form
renderForm($id, $Name, $Status, $Comments, $Type, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
I am wanting to replace the status text filed with a drop down list of options.
Replace your <input by <select :
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>School Name:</strong> <input type="text" name="Name" value="<?php echo $Name; ?>"/><br/><br>
<!-- <strong>Status:</strong> <input type="text" name="Status" value="<?php echo $Status; ?>"/><br/><br>-->
<strong>Status:</strong> <select name="Status">
<option value="1">Status 1</option>
<option value="2">Status 2</option>
</select>
<strong>Comments:</strong> <input type="text" name="Comments" value="<?php echo $Comments; ?>"/><br/><br>
<strong>Type:</strong> <input type="text" name="Type" value="<?php echo $Type; ?>"/><br/><br>
<input type="submit" name="submit" value="Submit">
</div>
</form>
If your statuses are in a table, fill the <select> with a query :
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>School Name:</strong> <input type="text" name="Name" value="<?php echo $Name; ?>"/><br/><br>
<!-- <strong>Status:</strong> <input type="text" name="Status" value="<?php echo $Status; ?>"/><br/><br>-->
<strong>Status:</strong> <select name="Status">
<?php
$result = mysql_query("SELECT * FROM tbl_status",$cnx);
while ( $row = mysql_fetch_array($result) )
echo "<option value='" . $row["id"] . "'>" . $row["text"] . "</option>";
?>
</select>
<strong>Comments:</strong> <input type="text" name="Comments" value="<?php echo $Comments; ?>"/><br/><br>
<strong>Type:</strong> <input type="text" name="Type" value="<?php echo $Type; ?>"/><br/><br>
<input type="submit" name="submit" value="Submit">
</div>
</form>
You could use the html <datalist> or the <select> tag.
I hope I could help.
First of all you need to switch from mysql_* to mysqli_* as it going to get removed in php 7.0 I'm using this function i created and it might help you
here is the php code
function GetOptions($request)
{
global $con;
$sql = "SELECT * FROM data GROUP BY $request ORDER BY $request";
$sql_result = mysqli_query($con, $sql) or die('request "Could not execute SQL query" ' . $sql);
while ($row = mysqli_fetch_assoc($sql_result)) {
echo "<option value='" . $row["$request"] . "'" . ($row["$request"] == $_REQUEST["$request"] ? " selected" : "") . ">" . $row["$request"] . "$x</option>";
}
}
and the html code goes like
<label>genre</label>
<select name="genre">
<option value="all">all</option>
<?php
GetOptions("genre");
?>
</select>

Updating Post not working

I recently made a code that updates my posts on my blog. It worked perfectly on localhost. But when i uploaded it online it did not work any more. The weird thing is it doesn't even display a error so i have no idea where to look. Can someone please help me ?
require('config.php');
$query = "SELECT * FROM project ORDER BY idproject DESC";
$result = mysqli_query($verbinding, $query ) or die (mysqli_error('kan geen verbinding maken met de database'));
if(isset($_POST['editBut'])){
$editTitle = $_POST['editName'];
$editThis = mysqli_query($verbinding, "SELECT * FROM project WHERE title = '".$editTitle."'");
$values = mysqli_fetch_assoc($editThis);
}
if(isset($_POST['update'])){
$editedTitle = $_POST['newTitle'];
$editedText = $_POST['newTekst'];
$oldTitle = $_POST['oldTitle'];
$date = $_POST['datum'];
$updater = mysqli_query($verbinding, "UPDATE Project SET title='".$editedTitle."', content='".$editedText."' WHERE title='".$oldTitle."' AND datum='".$date."'");
echo $updater;
header('location:editPost.php?id=1');
}
if(isset($_GET['id'])){
echo 'post has been succesfully updated';
}
<?php if(isset($_POST['editBut'])){ ?>
<form action="" method="post">
Title: <input type="text" name="newTitle" value="<?php echo $values['title'] ?>"><br>
Text: <textarea type="text" name="newTekst" id="newTekst"><?php echo $values['content'] ?></textarea><br>
<input type="hidden" value="<?php echo $values['title'] ?>" name="oldTitle">
<input type="hidden" value="<?php echo $values['datum'] ?>" name="datum">
<input type="submit" name="update" value="Edit post">
</form>
<?php } else { ?>
<p>Find the post you want to edit:</p>
<form action="" method="post">
<select name="editName">
<?php
while ($row = mysqli_fetch_assoc($result)) {
?> <option value="<?php echo $row['title'] ?>"><?php echo $row['title'] ?></option>
<?php } ?>
</select>
<input type="submit" name="editBut" value="Choose">
</form>
<?php } ?>
In update query replace your table name with small letter.
replace Project with project

Categories