I have tried to write a code that update category in the database using admin panel but whenever i try to do that it won't work and i don't get any errors to look into it, please help guys; thanks a lot
PHP Code:
<?php
if (isset($_GET['edit'])) {
$edit_id = $_GET['edit'];
$query = "SELECT * FROM categories WHERE category_id = $edit_id ";
$edit_get_result = mysqli_query($connection,$query);
if (!$edit_get_result) {
die("Edit Get Result Query FAILED");
}
while ($category_name_row=mysqli_fetch_assoc($edit_get_result)) {
$category_name = $category_name_row['category_name'];
}
?>
<center>
<form action="category.php" method="POST">
<div class="form-group">
<label for="update_category">Update Category</label>
<input type="text" class="form-control" id="update_category" value="<?php if(isset($category_name)){echo $category_name; } ?>" name="update_category" aria-describedby="emailHelp" placeholder="Enter Category Name">
</div>
<button type="submit" name="update_category_submit" class="btn btn-primary">Update</button>
</form>
</center>
<?php
if (isset($_POST['update_category_submit'])) {
$category_name = $_POST['update_category'];
$query = "UPDATE categories SET category_name = '$category_name' WHERE category_id = $edit_id ";
$final_update_query_result = mysqli_query($connection,$query);
if (!$final_update_query_result) {
die("Final Update Query Result FAILED");
}
}
}
?>
Please check below code. You need to pass edit_id in your form POST. I have put it in a hidden input and set it's value according to the GET parameter from top of your php part.
<?php
if (isset($_GET['edit'])) {
$edit_id = mysqli_real_escape_string($connection,$_GET['edit']);
$query = "SELECT * FROM categories WHERE category_id = '$edit_id' ";
$result = mysqli_query($connection,$query);
if(!$result) {
die("Edit Get Result Query FAILED");
}
while ($row=mysqli_fetch_assoc($result)) {
$category_name = $row['category_name'];
}
?>
<center>
<form action="category.php" method="POST">
<div class="form-group">
<label for="update_category">Update Category</label>
<input type="text" class="form-control" id="update_category" value="<?php if(isset($category_name)){echo $category_name; } ?>" name="update_category" aria-describedby="emailHelp" placeholder="Enter Category Name">
</div>
<input type="hidden" name="edit_id" value="<?php if(isset($edit_id)) echo $edit_id;?>">
<button type="submit" name="update_category_submit" class="btn btn-primary">Update</button>
</form>
</center>
<?php
if (isset($_POST['update_category_submit']) && isset($_POST['edit_id'])) {
$category_name = mysqli_real_escape_string($connection,$_POST['update_category']);
$edit_id = mysqli_real_escape_string($connection,$_POST['edit_id']);
$query = "UPDATE categories SET category_name = '$category_name' WHERE category_id = $edit_id ";
$result = mysqli_query($connection,$query);
if (!$result) {
die("Final Update Query Result FAILED");
}
else echo "Final Update Query Result Success";
}
?>
Hi have noticed that you have used raw inputs. try avoiding it. Also noticed your code had extra curly braces at the end.
Please try using the following code after replacing your end page section php script.
if (isset($_POST['update_category_submit'])) {
$category_name = $_POST['update_category'];
$query = "UPDATE categories SET category_name = '$category_name' WHERE category_id = $edit_id ";
$final_update_query_result = mysqli_query($connection,$query);
if (!$final_update_query_result) {
die("Final Update Query Result FAILED");
}
}
And Change your query variable to the following:
$query = "SELECT * FROM categories WHERE category_id = ".$edit_id;
Related
This is my first post in this forum, despite being a devoted follower for years now.
I have built a simple system that registers lot numbers and their locations within a MySQL database through a PHP form.
Then i have this other form called "Errata Corrige" that I use to find and edit eventual mistaken entries.
It's search criteria is an (UNSIGNED INT UNIQUE) value named "lotto" and everything works (worked) like a charm under this circumstances.
Now the thing got a little tricky.
I found out that lot numbers (lotto) for work purposes are not always unique values, there might be more than one entry with the same number.
No problem making the "Insert" form or various counters work under this new circumstances, but it got really tricky within the EDIT functions.
This is my PHP code: `
<?php
$id = "";
$settore = "";
$ubicazione = "";
$numero = "";
$lotto="";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
echo 'Error';
}
// get values from the form
function getPosts()
{
$posts = array();
$posts[0] = $_POST['id'];
$posts[1] = $_POST['settore'];
$posts[2] = $_POST['ubicazione'];
$posts[3] = $_POST['numero'];
$posts[4] = $_POST['lotto'];
return $posts;
}
// Search
if(isset($_POST['search']))
{
$data = getPosts();
$search_Query = "SELECT * FROM mappa WHERE lotto = $data[4]";
$search_Result = mysqli_query($connect, $search_Query);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($row = mysqli_fetch_array($search_Result))
{
$id = $row['id'];
$settore = $row['settore'];
$ubicazione = $row['ubicazione'];
$numero = $row['numero'];
$lotto = $row ['lotto'];
}
}else{
echo 'Lotto non presente in archivio';
}
}else{
echo 'Error';
}
}
// Insert
if(isset($_POST['insert']))
{
$data = getPosts();
$insert_Query = "INSERT INTO `mappa`(`settore`, `ubicazione`, `numero`, `lotto` ) VALUES ('$data[1]','$data[2]',$data[3], $data[4])";
try{
$insert_Result = mysqli_query($connect, $insert_Query);
if($insert_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
$resInsert = "1 nuovo dato inserito correttamente!";
}else{
$resInsert = "Nessun dato inserito";
}
}
} catch (Exception $ex) {
echo 'Errore '.$ex->getMessage();
}
}
// Edit
if(isset($_POST['update']))
{
$data = getPosts();
$update_Query = "UPDATE `mappa` SET `settore`='$data[1]',`ubicazione`='$data[2]',`numero`=$data[3],`lotto`=$data[4] WHERE `id` = $data[0]";
try{
$update_Result = mysqli_query($connect, $update_Query);
if($update_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
$resAgg = "1 dato aggiornato correttamente!";
}else{
$resAgg = "Nessun dato aggiornato!";
}
}
} catch (Exception $ex) {
echo 'Error Update '.$ex->getMessage();
}
} ?>
`
HTML:
<form action="mod.php" method="post" class="form-horizontal form-bordered" style="text-align:center">
<div class="form-group has-error" style="padding-top:30px">
<label class="col-xs-3 control-label" for="state-normal">ID</label>
<div class="col-lg-3">
<input type="text" name="id" placeholder="ID" class="form-control" value="<?php echo $id;?>"> </div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="state-normal">Settore</label>
<div class="col-md-6">
<input type="text" name="settore" placeholder="Settore" class="form-control" value="<?php echo $settore;?>"> </div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="state-normal">Ubicazione</label>
<div class="col-md-6">
<input type="text" name="ubicazione" placeholder="Ubicazione" class="form-control" value="<?php echo $ubicazione;?>"> </div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="state-normal">Numero</label>
<div class="col-md-6">
<input type="text" name="numero" placeholder="Numero" class="form-control" value="<?php echo $numero;?>"> </div>
</div>
<div class="form-group has-success">
<label class="col-md-3 control-label" for="state-normal">Lotto</label>
<div class="col-md-6">
<input type="text" name="lotto" placeholder="Lotto" class="form-control" value="<?php echo $lotto;?>"> </div>
</div>
<div style="padding-top:16px">
<!-- Insert-->
<button type="submit" name="insert" value="Add" class="btn btn-effect-ripple btn-primary">Inserisci</button>
<!-- Update-->
<button type="submit" name="update" value="Update" class="btn btn-effect-ripple btn-info">Aggiorna</button>
<a> </a>
<!-- Search-->
<button type="submit" name="search" value="Find" class="btn btn-effect-ripple btn-success">Cerca</button>
</div>
</form>
While the lot number was unique everything worked like a charm.
Now that there are multiple data with the same lot number the code became obsolete since the "search" function only shows the last (greatest ID) data.
I have tried to work around a loop and tell the function to search every ID where lotto = lotto but it didn't work.
A simple solution would be obviously searching through ID instead of lotto but that is a pretty crapy one, since the user only knows (and is interested in) Lot Numbers not the ID it was assigned during data insertion.
Then I tried to put two php functions into one page, the first that fetches data from Mysql into a PHP dropdown menu, telling it to show every ID that matches the search criteria (lotto):
<?php if (isset($_POST['submitted'])){
include ('../mysql_connect.php'); // connessione al database
$category = 'lotto';
$criteria = $_POST['criteria'];
$query = "SELECT * FROM mappa WHERE $category = '$criteria'";
$result = mysqli_query($dbcon, $query) or die('Impossibile reperire i dati');
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$idTab = $row['id'];
echo "<option>
$idTab </option>";
}
} // FINE if ?>
</select>
Fetching data from MySQL into the dropdown worked just fine, but I got stucked in the syntax trying to use this dropdown as a search criteria for my first function.
Every help would really be appreciated! Thank you in advance for your answers.
You said that lotto is unique. So how come you are able to insert multiple rows with the same lotto?
Remove the unique constraint from the lotto column.
Try the following:
$query = select lotto, group_concat(id) as ID numbers from mappa where lotto = 'user search number' group by lotto;
$result = $conn->query($query);
$rows = $result->num_rows;
$result->data_seek(0); //move to first row (which is the only one)
$row = $result->fetch_array(MYSQLI_NUM); //fetch array
$id_numbers_string = $row[1]; //store the values of the row's second column (which is number 1)
$id_numbers_separated_array = explode(",", $id_numbers_string); //create an array with the values in the string
for($i = 0; $i < count($id_numbers_separated_array); $i++){ //loop through created array
echo "ID: " . $id_numbers_separated_array[$i];
echo "<br>";
}
Also try to run the query in your database management system to see the results.
i am not getting any result ..tried a lot ...but didnt know what is the problem.
no results after editing...nothing changed ...and is also not showing any error..please help..i need to submit a project.'
Thankyou.
<form action="acat.php" method="post"> <!--Edit cat form-->
<div class ="form-group">
<label for ="title">Edit Category</label>
<?php
if(isset($_GET['edit'])) {
$editid = $_GET['edit'];
if (!$editid) {
echo "CANNOT BE EDITED";
} else {
$query = "SELECT * FROM categories WHERE cat_id = '$editid'";
$edit_query = mysqli_query($con,$query);
}
while($row=mysqli_fetch_assoc($edit_query)) {
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
?>
<input value="<?php if(isset($editid)) {echo $cat_title;} ?>"
class="form-control" type="text" name="update">
<?php } } ?>
<?php
if(isset($_POST['update_submit']) && isset($_GET['edit'])) {
$editid = $_GET['edit'];
$updatetitle = $_POST['update'];
$query = "UPDATE categories SET cat_title='$updatetitle' where
cat_id='$editid'";
$update_query = mysqli_query($con,$query);
if (!$update_query) {
die('QUERY FAILED' . mysqli_error($con));
}
}
?>
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit"
name="update_submit" value="Update Category">
</div>
</form>
</div>
In the POST condition, it's unable to identify $editid
Change this line:
if(isset($_POST['update_submit'])) {
To this:
if(isset($_POST['update_submit']) && isset($_GET['edit'])) {
$editid = $_GET['edit']; // Add this line
$updatetitle = $_POST['update'];
$query = "SELECT * FROM categories SET cat_title='$updatetitle' WHERE
cat_id = '$editid'"; //error line
$update_query = mysqli_query($con,$query);
I have multiple fields on admin panel user can add field and delete the fields as well while adding it I placed simple insert query with foreach loop but it is difficult to understand the concept for updating that fields if user deletes a field or updates it is not working if I delete 1 field and update it it deletes 2 or more then 2 fields and when I try to update it is not updating well update issue is due i would be making some mistake with query. But main thing is about logic which I am unable to build it properly need help.
Update query
$video_link = $_POST['video_link'];
$old_links = count($video_link);
if(isset($_POST['video_id'])) {
$video_id = $_POST['video_id'];
$total_id = count($video_id);
} else {
$video_id = '';
}
$video_links = mysqli_query($connect, "SELECT * FROM video_slides WHERE model_id = '$model_id'");
$total_links = mysqli_num_rows($video_links);
$video_link = sizeof($video_link) - 1;
if($total_links >= 1) {
for($i = 0; $i<=$video_link; $i++) {
if(empty($video_id[$i])) {
mysqli_query($connect, "INSERT INTO `video_slides`(`embeded_link``, `model_id`) VALUES ('$video_link[$i]', '$model_id')");
}
$query2 = mysqli_query($connect, "UPDATE `video_slides` SET `embeded_link`='$video_link[$i]' WHERE id='$video_id[$i]'");
if($video_link < $total_links) {
$new_total = $total_links-sizeof($video_link);
for($j = 0; $j<=$new_total; $j++) {
mysqli_query($connect, "DELETE FROM video_slides WHERE id='$video_id[$j]'");
}
}
}
} else {
for($i = 0; $i<=$video_link; $i++) {
if(empty($video_id[$i])) {
mysqli_query($connect, "INSERT INTO `video_slides`(`embeded_link``, `model_id`) VALUES ('$video_link[$i]', '$model_id')");
}
}
}
And here is my form fields
<div class="form-group">
<label>Video Slides <input type="button" class="add_field_button btn blue" value="Add Field" /></label>
<div class="input_fields_wrap">
<?php
$sql3 = mysqli_query($connection, "SELECT * FROM video_slides WHERE model_id = '".$data['id']."'");
if(mysqli_num_rows($sql3) == 0) {
?>
<div class="new">
<input type="text" id="video_link" size="20" name="video_link[]" placeholder="Embeded Video Link" class="form-control" />
</div>
<?php
} else {
while($video = mysqli_fetch_assoc($sql3)) {
?>
<div class="new">
<input type="text" id="video_link" size="20" name="video_link[]" placeholder="Embeded Video Link" class="form-control" value="<?php echo $video['embeded_link']; ?>" />
<input type="hidden" value="<?php echo $video['id']; ?>" name="video_id[]" />
<a class="remove_field"><i class="fa fa-times"></i></a>
</div>
<?php } } ?>
</div>
</div>
As per my understanding you need only these thing why you making complex coding
$video_link = $_POST['video_link'];
//First Remove All ID
mysqli_query($connect, "DELETE FROM video_slides WHERE model_id='$model_id'");
//Then After insert updated data
foreach($video_link as $key=>$val){
mysqli_query($connect, "INSERT INTO `video_slides`(`embeded_link`, `model_id`) VALUES ('$val', '$model_id')");
}
you should try to outsource your db connections in a separate class - this will lead to better readable code. An ORM like Doctrine can definitely help you to better understand your own code.
I am trying to do a simple edit/update of my data in the database. But somehow it will not work.
So I am able to read out the saved data into the form. I also don't have any errors
I have stared at my code and googled for hours but I don't see where I might have made a mistake with my code.
The printed echo gives the following output which seems to be right:
HTML code:
<form id="formAddCategory" class="FrmCat" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div class="form-group">
<!-- hidden id from tbl -->
<input type="hidden" name="hiddenId" value="<?php echo $hiddenID ?>" />
<label for="recipient-name" class="control-label">Category Name:</label>
<input type="text" class="form-control" id="recipient-name1" name="category" required="" value="<?php echo $category ?>" />
</div>
<button type="submit" id="btnEditCat" class="btn btn-danger" name="editCategory">Save Category</button>
</form>
Part of my php code to edit/update:
<?php
//edit/update data to db
if(isset($_POST['editCategory'])){
$categoryUpdate = mysqli_real_escape_string($con, $_POST['category']);
$categoryID = mysqli_real_escape_string($con, $_POST['hiddenId']);
$qry = "UPDATE tbl_Category SET category = $categoryUpdate WHERE category_id = $categoryID";
$result = mysqli_query($con, $qry);
echo $qry;
if($result){
header("Location: category.php");
}
}
?>
You need single quote ' to wrap your parameter:
$qry = "UPDATE tbl_Category SET category = '$categoryUpdate' WHERE category_id = '$categoryID'";
You should use single quotes (') for values
$qry = "UPDATE tbl_Category SET category = '$categoryUpdate' WHERE category_id = '$categoryID'";
Also you can use like this to avoid SQL injection (See here)
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
I can't seem to find the error. This form is supposed to update a category in the database.
When I try to update the category it gives me this error
Notice: Undefined variable: cat_id in C:\xampp\htdocs\CMS_project\admin\categories.php on line 90
QUERY FAILED!You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
This is the code below, i've commented where is the line 90.
<form action="categories.php" method="post">
<div class="form-group">
<label for="cat_title">Update Category</label>
<?php
if(isset($_GET['edit']))
{
$cat_id = $_GET['edit'];
$query = "SELECT * FROM categories WHERE cat_id = {$cat_id} ";
$select_categories_id = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($select_categories_id))
{
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
?>
<input value="<?php if(isset($cat_title)){echo $cat_title;} ?>" type="text" name="cat_title" class="form-control">
<?php } } ?>
<?php
if(isset($_POST['update_category']))
{
$the_cat_title = $_POST['cat_title'];
//Below is line 90
$query = "UPDATE categories SET cat_title = '{$the_cat_title}' WHERE cat_id = {$cat_id} ";
$update_query = mysqli_query($connection, $query);
if(!$update_query)
{
die("QUERY FAILED!" . mysqli_error($connection));
}
}
?>
</div>
<div class="form-group">
<input type="submit" name="update_category" value="Update Category" class="btn btn-primary">
</div>
</form>
This is where the form gets the ID
<?php
while($row = mysqli_fetch_assoc($select_categories))
{
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
echo "<tr>
<td>{$cat_id}</td>
<td>{$cat_title}</td>
<td><a href='categories.php?delete={$cat_id}'>Delete</a></td>
<td><a href='categories.php?edit={$cat_id}'>Edit</a></td>
</tr>";
}
?>
The $cat_id variable is simply not defined in the scope of your query. This means, that the $cat_id variable is only declared inside if statement where you check if $_GET['edit'] is set.
To fix it, add a hidden field with category id to your form, and then in PHP add:
$cat_id = $_POST['cat_id'];
just before the 90th line.
By the way remember to use mysqli_real_escape_string to prevent SQL-incjection issues.
I figured it out.
I had to delete the categories.php from the action in form, if I leave it blank it works fine. :)