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>
Related
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 ?>
I have a table where I want to update data in 2 rows.
Heres my code:
<?php
include("includes/conn.php");
session_start();
if(!isset($_SESSION['username']))
{
header('Location: login.php');
}
else{
?>
<?php
$page_title = 'Update Order';
include("includes/header.inc.php");
?>
<?php if( $_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update-order']) ){
if( !empty($_POST['productname']) && !empty($_POST['quantity']) && !empty($_POST['price']) && !empty($_POST['amount']) ){
$total = 0;
$pid = mysqli_real_escape_string($db,$_POST['pid']);
$advance = mysqli_real_escape_string($db,$_POST['advance_paid']);
$dod = mysqli_real_escape_string($db,$_POST['dod']);
$dod = date('Y-m-d', strtotime($dod));
$mop = mysqli_real_escape_string($db,$_POST['mop']);
for($i = 0; $i<count($_POST['productname']); $i++)
{
$total = $total + $_POST['amount'][$i];
$query = "UPDATE `invoice` SET product_name = (select name from item where id = '{$_POST['productname'][$i]}'), quantity = '{$_POST['quantity'][$i]}', price = '{$_POST['price'][$i]}', discount = '{$_POST['discount'][$i]}', amount = '{$_POST['amount'][$i]}', dod = '{$dod}', added_by = '{$_SESSION['id']}' WHERE id = '{$pid}' ";
mysqli_query($db, $query);
$update_stock = "UPDATE `item` SET added_by = '{$_SESSION['id']}', total_stock = total_stock + '{$_SESSION['quant']}' - '{$_POST['quantity'][$i]}' WHERE id = '{$_POST['productname'][$i]}'";
mysqli_query($db, $update_stock);
}
$query_orders = "UPDATE `orders` SET amount = '{$total}', dod = '{$dod}', mop = '{$mop}', advance = '{$advance}', added_by = '{$_SESSION['id']}' WHERE order_id = '{$_POST['orderid']}' ";
mysqli_query($db, $query_orders);
}
}
?>
<div id="alteration-form">
<div style="width: 90%; margin: 0 auto;">
<form method="GET" action="">
<label for="update_orderno" >Order NO.</label>
<input type="text" name="orderno" class="input-field" id="update_orderno" />
<input type="submit" name="find-order" value="Search Order" class="btn-all-submit" id="btn-order" />
</form>
</div>
</div>
<?php if( $_SERVER["REQUEST_METHOD"] == "GET" ){ ?>
<?php
if( !empty($_GET['orderno']) ){
$orderno = $_GET['orderno'];
$sql_cust = "SELECT cust_id FROM `orders` where order_id = '$orderno' ";
$result_cust = mysqli_query($db, $sql_cust);
if( mysqli_num_rows($result_cust) > 0 ){
while( $row_cust = mysqli_fetch_array($result_cust, MYSQLI_ASSOC) ){
$cust_id = $row_cust['cust_id'];
}
$sql_name = "SELECT * FROM `users` WHERE id = '$cust_id' ";
$result_name = mysqli_query($db, $sql_name);
if( mysqli_num_rows($result_name) > 0 ){
while( $row_name = mysqli_fetch_array($result_name, MYSQLI_ASSOC) ){
$name = $row_name['name'];
$phone = $row_name['phone'];
$address = $row_name['address'];
$city = $row_name['city'];
$state = $row_name['state'];
}
}
}
?>
<div class="result-table-div">
<div class="divRow">
<div class="divCell" ><strong>Name:</strong></div>
<div class="divCell" ><?php echo $name; ?></div>
<?php if(!empty($phone)){ ?>
<div class="divCell" ><strong>Phone:</strong></div>
<div class="divCell" ><?php echo $phone; ?></div>
<?php } ?>
</div>
<div class="divRow">
<?php if(!empty($address)){ ?>
<div class="divCell" ><strong>Address:</strong></div>
<div class="divCell" ><?php echo $address; ?></div>
<?php } ?>
<?php if(!empty($city)){ ?>
<div class="divCell" ><strong>City:</strong></div>
<div class="divCell" ><?php echo $city; ?></div>
<?php } ?>
</div>
<div class="divRow">
<?php if(!empty($state)){ ?>
<div class="divCell" ><strong>State:</strong></div>
<div class="divCell" ><?php echo $state; ?></div>
<?php } ?>
</div>
</div>
<div class="result-table-div">
<form method="POST" action="">
<div class="divRow">
<div class="divCell" ><strong>Date of Delivery:</strong></div>
<div class="divCell" ><input type="text" name="dod" id="dod" value="<?php echo date("m/d/Y"); ?>"/></div>
<div class="divCell" ><strong>Mode of Payment:</strong></div>
<div class="divCell" >
<select name="mop">
<option value="cash">Cash</option>
<option value="card/cheque/online banking">Card/Cheque/Online Banking</option>
</select>
</div>
</div>
<table id="invoice-table">
<thead>
<tr>
<th>S No.</th>
<th>Item</th>
<th>Quantity</th>
<th>Price</th>
<th>Discount</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * FROM invoice where order_id = '$orderno' ";
$result = mysqli_query($db, $sql);
if( mysqli_num_rows($result) > 0 ){
$count = 1;
while( $row = mysqli_fetch_array($result,MYSQLI_ASSOC) ){
$id = $row['id'];
$product_name = $row['product_name'];
$quantity = $row['quantity'];
$price = $row['price'];
$discount = $row['discount'];
$amount = $row['amount'];
$_SESSION['cust_id'] = $row['cust_id'];
$_SESSION['quant'] = $quantity;
?>
<tr>
<input type="hidden" name="pid" value="<?php echo $id; ?>" />
<td><?php echo $count++; ?></td>
<!--<td><input type="text" name="productname[]" value="?php echo $product_name ?>"></td>-->
<td>
<select name="productname[]">
<option value="1" <?php if( isset($product_name) && strtolower($product_name) == "bags" ) echo "selected"; ?> >Bags</option>
<option value="2" <?php if( isset($product_name) && strtolower($product_name) == "shoes" ) echo "selected"; ?> >Shoes</option>
<option value="3" <?php if( isset($product_name) && strtolower($product_name) == "suit" ) echo "selected"; ?> >Suit</option>
<option value="4" <?php if( isset($product_name) && strtolower($product_name) == "belts" ) echo "selected"; ?> >Belts</option>
<option value="5" <?php if( isset($product_name) && strtolower($product_name) == "t-shirts" ) echo "selected"; ?> >T-shirts</option>
<option value="6" <?php if( isset($product_name) && strtolower($product_name) == "others" ) echo "selected"; ?> >Others</option>
</select>
</td>
<td><input type="text" class="quantity" name="quantity[]" value="<?php echo $quantity ?>"></td>
<td><input type="text" class="price" name="price[]" value="<?php echo $price ?>"></td>
<td><input type="text" class="discount" name="discount[]" value="<?php echo $discount ?>"></td>
<td><input type="text" class="amount" name="amount[]" value="<?php echo $amount ?>"></td>
</tr>
<?php
}
?>
<input type="hidden" name="orderid" value="<?php echo $orderno; ?>">
<?php
}
?>
</tbody>
</table>
<p style="text-align: center;">Advanced Paid: <input type="text" name="advance_paid" /></p>
<div class="btn-div">
<input type="submit" class="btn-all-submit" name="update-order" value="Update Order">
</div>
</form>
</div>
<?php } } ?>
<script>
$('body').delegate('.quantity,.price,.discount','keyup',function()
{
var tr=$(this).parent().parent();
var qty=tr.find('.quantity').val();
var price=tr.find('.price').val();
var dis=tr.find('.discount').val();
var amt =(qty * price)-(qty * price *dis)/100;
tr.find('.amount').val(amt);
});
</script>
<?php include("includes/footer.inc.php"); ?>
<?php } ?>
I am using for loop to update the data but if I have 2 items to update, it is only updating second item and not the first one. Can someone please help me with this.
Problem occurs while updating invoice table.
I found the solution for my problem.
Query should be
$query = "UPDATE `invoice` SET product_name = (select name from item where id = '{$_POST['productname'][$i]}'), quantity = '{$_POST['quantity'][$i]}', price = '{$_POST['price'][$i]}', discount = '{$_POST['discount'][$i]}', amount = '{$_POST['amount'][$i]}', dod = '{$dod}', added_by = '{$_SESSION['id']}' WHERE id = '{$_POST['pid'][$i]}' ";
mysqli_query($db, $query);
Okay i have this SQL statement for update which works find but I want to add locations which is in te_venue table after adding the location into sql i want for locations to be a drop down list which user can pick one location from list and when clicked on update it should update.
This is the php code that I have already (I need to add location into this)
<?php
$eventID = $_GET['id'];
if(isset($_POST['submit']))
{
$title = $_POST['title'];
$startdate = $_POST['startdate'];
$enddate = $_POST['enddate'];
$price = $_POST['price'];
$description = $_POST['description'];
$sql = "UPDATE te_events SET eventTitle='$title',eventStartDate='$startdate',eventEndDate='$enddate',eventPrice='$price',eventDescription='$description' WHERE eventID=$eventID";
if ($conn->query($sql) === TRUE)
{
header('Location:edit.php');
}
else
{
echo "Error updating record";
}
}
$sql = "SELECT * FROM te_events where eventID='$eventID'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
$eventTitle = $row['eventTitle'];
$eventDescription = $row['eventDescription'];
$eventStartDate = $row['eventStartDate'];
$eventEndDate = $row['eventEndDate'];
$eventPrice = $row['eventPrice'];
}
?>
And this is where i want to have a drop down list for location.
<form method="post" action="">
<label for="title">Title</label><br/>
<input type="text" name="title" required/ value="<?php echo $eventTitle; ?>"><br/>
<label for="startdate">Start Date</label><br/>
<input type="date" name="startdate" required/ value="<?php echo $eventStartDate; ?>"><br/>
<label for="enddate">End Date</label><br/>
<input type="date" name="enddate" required/ value="<?php echo $eventEndDate; ?>"><br/>
<label for="price">Price (£)</label><br/>
<input type="number" step="any" name="price" required/ value="<?php echo $eventPrice; ?>"><br/>
<label for="description">Description</label><br/>
<textarea name="description" cols="55" rows="5"><?php echo $eventDescription; ?></textarea><br/>
<input type="submit" name="submit" value="Update" class="button">
</form>
Here is a screenshot of my tables too it might help.
https://postimg.org/image/6ui8nsi55/
Do you want something like this? Getting the location from te_venue and adding the results to a select?
<select>
<?php
$sql = "SELECT location FROM te_venue";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
}
?>
<option value="<?php echo $row['location'];?>"><?php echo $row['location'];?> </option>
<?php
}
?>
</select>
<label for="location">Choose a location: </label>
<select class="form-control" name="location">
<option value="London">London</option>
<option value="Paris">Paris</option>
<option value="Rome">Rome</option>
<option value="Berlin">Berlin</option>
<option value="Moscow">Moscow</option>
</select>
I'm working on a project and I'm suppose to update the another user's details using the $_GET method. My problem is that when user clicks on the id, it does go to edit page but when i change something and press the update button, it does not update. I'm not sure what am i doing wrong here.. I would really appreciate f someone can help me.
//Edit
My code is working now guys, I just changed the $_POST to $_REQUEST now and my form is updated.. Thank you all for helping me.. Thank you.. Here is my edited code.. I've taken out the oassword field, but i have a doubt.. Is using request safe?
<?php
include '../../connection.php';
$sid = $_REQUEST['sid'];
$query = "SELECT * FROM STUDENT WHERE STU_ID='$sid'";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
$unm = $row["STU_UNAME"];
$fnm = $row["STU_FNAME"];
$lnm = $row["STU_LNAME"];
$dob = $row["STU_DOB"];
$add = $row["STU_ADD"];
$tlp = $row["STU_PHONE"];
$sem = $row["STU_SEM"];
$img = $row["STU_IMG"];
$sts = $row["STU_STATUS"];
$cid = $row["CRS_ID"];
}
}
else{
$no = "0 result!";
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
//insert details in data
$sid = $_POST["sid"]; $snm = $_POST["snm"]; $fst = $_POST["fnm"]; $lst = $_POST["lnm"]; $sdb = $_POST["dob"];
$sad = $_POST["add"]; $shp = $_POST["tlp"]; $stt = $_POST["sts"]; $sem = $_POST["sem"]; $cid = $_POST["cid"];
$sql = "UPDATE STUDENT SET
STU_ID='$sid', STU_UNAME='$snm', STU_FNAME= '$fst', STU_LNAME='$lst', STU_DOB='$sdb', STU_ADD='$sad', STU_PHONE='$shp',
STU_STATUS='$stt', STU_SEM='$sem', CRS_ID = '$cid' WHERE STU_ID='$sid'";
//check if data is updated
if (mysqli_query($connection, $sql)) {
header("Location: searchStudent.php");
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
}
?>
Here's my form code:
<form class="contact_form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<ul>
<li>
<h2>Edit Students Details</h2>
<span class="required_notification">* Denotes Required Field</span>
</li>
<li>
<label for="id">Student ID: </label>
<input type="text" name="sid" value="<?php echo $sid;?>"/>
</li>
<li>
<label for="name">Username: </label>
<input type="text" name="snm" value="<?php echo $unm;?>"/>
</li>
<li>
<label for="name">First Name: </label>
<input type="text" name="fnm" value="<?php echo $fnm;?>"/>
</li>
<li>
<label for="name">Last Name: </label>
<input type="text" name="lnm" value="<?php echo $lnm;?>"/>
</li>
<li>
<label for="dob">Date of Birth: </label>
<input type="date" name="dob" value="<?php echo $dob;?>"/>
</li>
<li>
<label for="add">Address: </label>
<textarea name="add" rows="4" cols="50"><?php echo $add;?></textarea>
</li>
<li>
<label for="tlp">Phone: </label>
<input type="text" name="tlp" value="<?php echo $tlp;?>"/>
</li>
<li>
<label for="sts">Status: </label>
<select name="sts">
<option selected><?php echo $sts;?></option>
<option value="FULLTIME">FULL TIME</option>
<option value="PARTTIME">PART TIME</option>
</select>
</li>
<li>
<label for="sem">Semester: </label>
<select name="sem">
<option selected><?php echo $sem;?></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
</li>
<li>
<label for="crs">Course: </label>
<select name="cid">
<option selected><?php echo $cid;?></option>
<option value="AL">AL</option>
<option value="DBM">DBM</option>
<option value="DIT">DIT</option>
<option value="DTM">DTM</option>
<option value="FIS">FIS</option>
</select>
</li>
<li>
<button class="submit" type="submit" name="update">Update</button>
</li>
Make sure your form method is POST
Try this code:
<?php
include '../../connection.php';
//
$id = $_POST['id'];
$query = "SELECT * FROM STUDENT WHERE STU_ID='$id'";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
$unm = $row["STU_UNAME"];
$fnm = $row["STU_FNAME"];
$lnm = $row["STU_LNAME"];
$pwd = $row["STU_PWD"];
$dob = $row["STU_DOB"];
$add = $row["STU_ADD"];
$tlp = $row["STU_PHONE"];
$sem = $row["STU_SEM"];
$img = $row["STU_IMG"];
$sts = $row["STU_STATUS"];
$cid = $row["CRS_ID"];
}
}
else{
$no = "0 result!";
}
$pwdErr = $cpwdErr= "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if($_POST["pwd"] == $_POST["cpwd"]){
if(strlen($_POST["pwd"])>8){
//insert details in data
$sid = $_POST["sid"]; $pwd = $_POST["pwd"]; $snm = $_POST["snm"]; $fst = $_POST["fnm"]; $lst = $_POST["lnm"];
$sdb = $_POST["dob"]; $sad = $_POST["add"]; $shp = $_POST["tlp"]; $stt = $_POST["sts"]; $sem = $_POST["sem"];
$cid = $_POST["cid"];
$sql = "UPDATE STUDENT SET
STU_ID='$sid', STU_PWD='$pwd', STU_UNAME='$snm', STU_FNAME= '$fst', STU_LNAME='$lst', STU_DOB='$sdb', STU_ADD='$sad', STU_PHONE='$shp',
STU_STATUS='$stt', STU_SEM='$sem', CRS_ID = '$cid' WHERE STU_ID='$id'";
//check if data is updated
if (mysqli_query($connection, $sql)) {
header("Location: searchStudent.php");
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
}
else{
$pwdErr = "Invalid/Password must be more than 8 characters!";
}
}
else{
$cpwdErr = "Password not same!";
}
}
?>
Get ride for how to use prepare statement with example here.
Hope this help you well!
Your error is your are using POST in your form but getting its value with get change $_get with $_POST
$id = $_POST['id'];
well problem is that id you are posting is "sid" but you are using just "id" like $_POST['id'] instead of $_POST['sid']. so use this -
$id = $_POST['sid'];
instead of -
$id = $_POST['id']
I have built a database named "artStore" and a table within that database named "inventory". I've been able to figure out how to create a new entry to the database, but I'm trying to create a page that can edit those entries.
Here is "inventory" the table I created:
$sql = "CREATE TABLE inventory (
id INT(6) AUTO_INCREMENT PRIMARY KEY,
product VARCHAR(30),
category VARCHAR(30),
seller VARCHAR(30)
)";
Here is what I'm currently trying:
<?php
$resultProduct = "product";
$resultCategory = "category";
$resultSeller = "seller";
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$resultProduct = $row["product"];
$resultCategory = $row["category"];
$resultSeller = $row["seller"];
}
} else {
echo "No Results";
}
?>
<form action="update.php" method="POST">
<label for="product">Product</label>
<input id="product" type="text" name="product" value="<?php echo $resultProduct; ?>">
<br>
<label for="category">Category:</label>
<input id="category" type="text" name="category" value="<?php echo $resultCategory; ?>">
<br>
<label for="seller">Seller:</label>
<input id="seller" type="text" name="seller" value="<?php echo $resultSeller; ?>">
<br>
<input id="id" type="text" name="id" value="<?php echo $resultId; ?>" style="display:none;">
<input type="submit" value="Update My Record">
</form>
What I'm trying in update.php
$product = $_POST['product'];
$category = $_POST['category'];
$seller = $_POST['seller'];
$sql = "INSERT INTO inventory (product, category, seller) VALUES ('$product', '$category', '$seller')";
if ($connection->query($sql) === true) {
echo "Inserted Successfully";
} else {
echo "Error occured in the insert: " . $connection->error;
}
$connection->close();
Try the below code I added hidden field on form and changes on your sql query
<?php
$resultProduct = "product";
$resultCategory = "category";
$resultSeller = "seller";
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$resultProduct = $row["product"];
$resultCategory = $row["category"];
$resultSeller = $row["seller"];
$resultId = $row["id"];
}
} else {
echo "No Results";
}
?>
<form action="update.php" method="POST">
<input type="text" name="update_id" value="<?php echo $resultId; ?>">
<label for="product">Product</label>
<input id="product" type="text" name="product" value="<?php echo $resultProduct; ?>">
<br>
<label for="category">Category:</label>
<input id="category" type="text" name="category" value="<?php echo $resultCategory; ?>">
<br>
<label for="seller">Seller:</label>
<input id="seller" type="text" name="seller" value="<?php echo $resultSeller; ?>">
<br>
<input id="id" type="text" name="id" value="<?php echo $resultId; ?>" style="display:none;">
<input type="submit" value="Update My Record">
</form>
In update.php
$product = $_POST['product'];
$category = $_POST['category'];
$seller = $_POST['seller'];
$updateId = $_POST['update_id'];
$sql = "UPDATE inventory set product = '$product',category='$category',seller='$seller' WHERE id = '$updateId'";
<?php
$resultProduct = "product";
$resultCategory = "category";
$resultSeller = "seller";
$resultId = "product_id";
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$resultProduct = $row["product"];
$resultCategory = $row["category"];
$resultSeller = $row["seller"];
$resultid = $row["id"];
}
} else {
echo "No Results";
}
?>
You were using $resultId in the form but you have not declared and assigned a value to it in the loop.
<form action="update.php" method="POST">
<input id="id" type="hidden" name="id" value="<?php echo $resultId; ?>">
<label for="product">Product</label>
<input id="product" type="text" name="product" value="<?php echo $resultProduct; ?>">
<br>
<label for="category">Category:</label>
<input id="category" type="text" name="category" value="<?php echo $resultCategory; ?>">
<br>
<label for="seller">Seller:</label>
<input id="seller" type="text" name="seller" value="<?php echo $resultSeller; ?>">
<br>
<input type="submit" value="Update My Record">
</form>
<!-- Instead of passing the ID in textbox with display: none you can pass it directly in hidden -->
<?php
$product = $_POST['product'];
$category = $_POST['category'];
$seller = $_POST['seller'];
$product_id = $_POST['id'];
if($product_id!='')//MEANS WE HAVE TO UPDATE THE RECORD
{
// UPDATE QUERY WILL UPDATE THE SAME RECORD ONLY MATCHING THE UNIQUE PRODUCT ID
$sql = "UPDATE inventory SET product = '$product', category = '$category', seller = '$seller' WHERE id = '$product_id' LIMIT 1";
if ($connection->query($sql) === true) {
echo "Updated Successfully";
} else {
echo "Error occured in the insert: " . $connection->error;
}
}
else// If id is blank it means you have a new record
{
$sql = "INSERT INTO inventory (product, category, seller) VALUES ('$product', '$category', '$seller')";
if ($connection->query($sql) === true) {
echo "Inserted Successfully";
} else {
echo "Error occured in the insert: " . $connection->error;
}
}
$connection->close();
?>