Working my way though Creating, Reading, Updating & Deleting (CRUD) information from a database I have done C,R & D but for some reason I can not update.
What am trying to do:
Edit a categorizes title
My Results:
when clicking edit in the table of the cat title I want to change I can get the cat title to echo into a form, where it can be changed then when i try and change the cat title, click update the form goes away as I wanted but the cat title stays the same.
as well am not getting any query errors
What should I look for when debugging code that has no errors?
Can someone see my problem?
if (isset($_GET['edit'])) {
$cat_id = $_GET['edit'];
include "includes/update.php";
}
?>
<form action="categories.php" method="post">
<div class="form-group">
<label for="cat_title">Edit 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;} ?>" class="form-control" type="text" name="cat_title">
<?php
}
}
if(isset($_POST['edit_category'])){
$edit_cat_title = $_POST['cat_title'];
$query = "UPDATE FROM categories SET cat_title = '{$edit_cat_title}' WHERE cat_id = {$cat_id} ";
$edit_query = mysqli_query($connection,$query);
if (!$edit_query) {
die(mysqli_error($edit_query));
}
}
?>
</div>
<input class="btn btn-primary" type="submit" name="edit_category" value="Edit Category">
</form>
In the following line you have a small error:
$query = "UPDATE FROM categories SET cat_title = '{$edit_cat_title}' WHERE cat_id = {$cat_id} ";
You need to remove the "FROM" in there, will look like this:
$query = "UPDATE categories SET cat_title = '{$edit_cat_title}' WHERE cat_id = {$cat_id} ";
and it should work as expected.
you're calling the update query with
$query = "UPDATE FROM categories SET cat_title = '{$edit_cat_title}' WHERE cat_id = {$cat_id} ";
where $cat_id probably is not set,
once to get this value you're using an if condition
if (isset($_GET['edit'])) {
$cat_id = $_GET['edit'];
where the $_GET[ 'edit' ] can be empty, and the next error is to overwrite the $cat_id variable in a loop: $cat_id = $row['cat_id'];
if (isset($_GET['edit'])) {
$cat_id = $_GET['edit'];
include "includes/update.php";
}
?>
<form action="categories.php" method="post">
<div class="form-group">
<label for="cat_title">Edit Category</label>
<?php
if (isset($_GET['edit'])) {
$cat_id = $_GET['edit'];
}
if(isset($_POST['edit_category'])){
$edit_cat_title = $_POST['cat_title'];
$query = "UPDATE FROM categories SET cat_title = '{$edit_cat_title}' WHERE cat_id = {$cat_id} ";
$edit_query = mysqli_query($connection,$query);
if (!$edit_query) {
die(mysqli_error($edit_query));
}
}
Delete that FROM, it should be UPDATE categories SET ...
You realise that $edit_cat_title is from a POST value, but $cat_id is from a GET value, but your form (as far as I can see) has an action value of action = "categories.php" which will contain NO GET VARIABLES.
Add the property enctype to your <form> such as:
<form ... enctype='multipart/form-data' ... >
To be honest this last point is good practise but I'd be surprised if that was why your POST data was not being populated.
Possible solutions:
1) Use $_REQUEST['cat_id'] and insert the cat_id as a POSTed field in your form, so it can use variables given by either $_POST or $_GET [or $_COOKIE].
2) change your action to goto : action ="categories.php?edit=XXX" to submit the form to an address with a valid GET value as required.
3) Use sessions to hold data from previous pages (such as cat_id). This is my prefered option.
Extra
From question comments it becomes clear that the part if isset($_POST['edit_category']) is never true, so this means that your form is incorrect -- either you have not got a form field named name='edit_cateogry' or your form field is never filled in, or never sent with the form (perhaps the input is placed after the </form> form closing tag?
Anyhow, your issue is that your $_POST value you are looking for is never set.
Related
Can someone please tell me how I can get my $cat_id variable recognised in the SECOND PART of my code ? It works fine in the FIRST PART - I mean the $cat_id value is inserted into mysql database with :
$insert_review_command = "INSERT INTO review VALUES(NULL,'$cat_id','{$category}','$user_id', '{$name}','{$phonenumber}','{$address}', '{$comment}')";
But nothing inserts in the SECOND PART. I don't think my $cat_id is recognised. But why shouldn't it be ?Should $cat_id not be recognised throughout my whole code ? If it is defined within an If statement is it only recognised within that If statement? Thanks for any help.
<?php require('dbConnect.php');
if (isset($_POST['create'])) {
$category = ($_POST['category']);
$name = ($_POST['name']);
$phonenumber = ($_POST['phonenumber']);
$address = ($_POST['address']);
$comment = ($_POST['comment']);
//check if the category being entered is already there
$select_from_cat_table = "SELECT * FROM category WHERE cat_name = '$_POST[category]'";
$result=mysqli_query($con,$select_from_cat_table);
$num_rows = mysqli_num_rows($result);
// get the matching cat_id
$row = mysqli_fetch_assoc($result);
$cat_id = $row["cat_id"];
// ****FIRST PART**** $CAT_ID IS INSERTED INTO THE DB
//if the category name already exists in the category table, then don't add it in again
if($num_rows >= 1) {
echo "This Already Exists<br/>";
//but do add it to the review table
//for the cat_id, we want to get the cat_id of the category name that already exists, that has
//just been posted. This is $cat_id. $user_id is the user id of the person posting
$insert_review_command = "INSERT INTO review VALUES(NULL,'$cat_id','{$category}','$user_id', '{$name}','{$phonenumber}','{$address}', '{$comment}')";
$insert_into_review_table = mysqli_query($con,$insert_review_command);
}
// ****SECOND PART**** $CAT_ID IS NOT INSERTED INTO THE DB
else if ($num_rows < 1)
{
//if it's not in there, then add the category in the category table.
$insert_category_command = "INSERT INTO category VALUES(NULL, '{$category}', '$user_id')";
$insert_into_category_table = mysqli_query($con,$insert_category_command);
//****WHY IS CAT_ID NOT WORKING HERE????******
//and add it to the review table
//for the cat_id, we want to get the cat_id of the category name that already exists, that has
//just been posted. This is $cat_id. $user_id is the user id of the person posting
$insert_review_command = "INSERT INTO review VALUES(NULL,'$cat_id','{$category}','$user_id', '{$name}','{$phonenumber}','{$address}', '{$comment}')";
$insert_into_review_table = mysqli_query($con,$insert_review_command);
echo "Yes, it's been added correctly";
echo $cat_id;
}
$con->close();
header('Location:volleyLogin.php');
}
?>
<!doctype html>
<html>
<body>
<h2>Create new Contact</h2>
<form method="post" action="" name="frmAdd">
<p><input type="text" name = "category" id = "category" placeholder = "category"></p>
<p><input type="text" name = "name" id = "name" placeholder = "name"></p>
<p><input type="text" name = "phonenumber" id = "phonenumber" placeholder = "phone number"></p>
<p><input type="text" name = "address" id = "address" placeholder = "address"></p>
<p><input type="text" name = "comment" id = "comment" placeholder = "comment"></p>
<h2>Visible to :</h2>
<input type="radio" name="allmycontacts" value="All my Contacts">All my Contacts
<input type="radio" name="selectwho" value="Select Who">Select Who
<input type="radio" name="public" value="Public">Public
<input type="radio" name="justme" value="Just me">Just me
<p><input type="submit" name = "create" id = "create" value = "Create new Contact"></p>
Exit
</form>
</body>
</html>
Your logic is split into two parts, if $num_rows is greater than 0, or if it's 0. This is the result of a query, obviously. So when you do
$cat_id = $row["cat_id"];
from the first query, and $num_rows is zero, your $cat_id doesn't hold any values, because mysqli_fetch_assoc() returned no rows (mysqli_num_rows() is 0), so $row is null.
Your solution is to fetch the recent inserted ID from your category table before you insert it into your review table.
Simply add
$cat_id = mysqli_insert_id($con);
before your insert-query for the review table (but after you insert values into the category table).
I want to update data of form fields in database through foreach loop. I have two columns in test_table ID and Input. I have fetched data through while loop and also have printed the value. Now I want to update fetched value. Please give some guidance for this.
Here is my code,
$sql = "select * from test_table";
if($result = mysqli_query($conn, $sql))
{
while($row = mysqli_fetch_array($result))
{
$inputResult[]=$row;
}
} <form method="POST"> <input type="text" value=<?php
echo $inputResult[0]['Input']; ?> id="$inputResult[0]['ID']"> <input
type="submit" name="submit"> </form> <?php
if (isset($_POST['submit'])
{
$input = $inputResult[];
foreach($input as $inputs => $value)
{
$Sql = "update test_table set Input='$value' where = '$inputs'";
mysqli_query($conn, $sql);
}
} ?>
Please let me know what errors have in my code ? Thanks in advance.
Next solution is very specific to your problem. The input text is the first element in your form, so, in the PHP code, we can get the input's ID and the VALUE by accessing the first item in the array $_POST (changes are pointed by arrows ◄■■■):
<?php
$sql = "select * from test_table";
if($result = mysqli_query($conn, $sql)) {
while($row = mysqli_fetch_array($result)) {
$inputResult[]=$row;
}
}
?>
<form method="POST">
<input type="text" value="<?php echo $inputResult[0]['Input'];?>"
name="<?php echo $inputResult[0]['ID'];?>" /> ◄■■■ NAME, NOT ID.
<input type="submit" name="submit" />
</form>
<?php
if ( isset($_POST['submit']) ) {
$value = reset( $_POST ); // ◄■■■ FIRST VALUE IN $_POST (['input']).
$id = key( $_POST ); // ◄■■■ FIRST KEY IN $_POST (['ID']).
$Sql = "update test_table set Input='$value' where id='$id'"; // ◄■■■ $VALUE AND $ID.
mysqli_query($conn, $sql);
}
?>
I replaced the attribute id= by name= in the input text, because PHP needs names, not ids.
After we get the first value and the first key, we can insert them into the sql string.
Edit :
Fixed the missing tags (oops!). I think I found the error, it's so little that it's hard to see : pay attention to next line:
▼
$Sql = "update test_table set Input='$value' where id='$id'"; // ◄■■■ $VALUE AND $ID.
Do you see the variable on the left : $Sql (the first letter is uppercased). Now let's see the next line:
▼
mysqli_query($conn, $sql);
The same variable is not uppercased, once you fix that, everything works :
▼
$sql = "update test_table set Input='$value' where id='$id'"; // ◄■■■ $VALUE AND $ID.
mysqli_query($conn, $sql);
▲
This code is meant to check the submitted form values and update the table,
however it just replaces the field with a blank
Any ideas where it is gone wrong, please?
<form action = "update.php" method = "POST">
<p>
New Name: <input type "text" name="name">
<input type= "submit">
</p>
</form>
<?php
require ('/var/www/html/site1/connect_db.php');
if(!empty($_POST['name']) && !is_numeric($_POST['name']))
{
$name=$_POST['name'];
$name=mysqli_real_escape_string($dbc,$query);
$name=strip_tags($name);
#$query='update customers SET customerName = '".$name."' where customerNumber=114';
$query = "update customers ". "SET customerName = $name"."where customerNumber=114" ;
mysqli_query($dbc,$query);
}
else
{
echo $name;
}
$query = 'select * from customers where customerNumber=103';
$result = mysqli_query($dbc,$query);
while ($row=mysqli_fetch_array($result, MYSQLI_NUM))
{
echo"<p>Name : $row[1]</p>";
}
mysqli_close($dbc);
?>
You are updating customer number 114 but selecting 103 out, whose name may be blank.
Your update statement needs to have quotes around the $name bit as below:
$query = "UPDATE customers SET customerName = '$name' WHERE customerNumber=114";
Edit: please see the parameterised query advice in the question comments.
I can't seem to find a solution to this and i've looked for similar threads too but no luck
Basically here's my code, when you click Update it's meant to display your current name in the form fields then you can overwrite them and submit the changes, however sadly it will not update, it only displays the originally set first name and last name and does not update the database so therefore not displaying the new set names.
<?php
include('../connect_db.php');
$res = mysqli_query($dbconnection, "SELECT * FROM users");
$row = mysqli_fetch_array($res);
if(isset($_POST['newFirst']) && isset($_POST['newLast'])){
$newFirst = $_POST['newFirst'];
$newLast = $_POST['newLast'];
$id = $_POST['id'];
$sql = "UPDATE users SET first_name='$newFirst', last_name='$newLast' WHERE id='$id'";
$res = mysqli_query($dbconnection, $sql);
}
?>
<div id="editSection">
<h3>Edit Details</h3>
<form action="edit_profile.php" method="POST">
<input type="hidden" value="<?php echo $row[0];?>" name="id"/>
<h2>First Name</h2>
<input type="text" name="newFirst" value="<?php echo $row[1];?>">
<h2>Last Name</h2>
<input type="text" name="newLast" value="<?php echo $row[2];?>">
<input type="submit" value="Update">
</form>
</div>
Any help would be greatly appreciated :)
Kind Regards
~ Matt
You have to connect to DB before updating.so use
$con=mysqli_connect("localhost","my_user","my_password","my_db");
There are several other errors like you have to make $POST['newFirst'] as $_POST['newFirst'] like this
if(isset($_POST['newFirst']) && isset($_POST['newLast'])){
And change the query to
$sql = "UPDATE users SET first_name='$newFirst',last_name='$newLast' WHERE id= '$id'";
beacuse you have error at end of query id='first_name='$id' which is wrong
I see some error in the query
$sql = "UPDATE users SET first_name='$newFirst',
last_name='$newLast' WHERE id='first_name='$id'";
should be
$sql = "UPDATE users SET first_name='$newFirst',
last_name='$newLast' WHERE id= '$id'";
also
if(isset($POST['newFirst']) && isset($POST['newLast'])){
should be
if(isset($_POST['newFirst']) && isset($_POST['newLast'])){
You are using $POST wrong in your if-condition.
It must be called $_POST[..].
Also you should take a look at your WHERE in your update query.
I think you mean: WHERE id= '$id'
You should get your id from $_POST['id']; which is your row ID i suppose and also the update query must be where id=$id.
$id = $_POST['id'];
$sql = "UPDATE users SET first_name='$newFirst', last_name='$newLast' WHERE id=$id";
Also have you checked in DB after the update? the row[0], row[1], row[2] used will have old set of values used during select before the update happened. can you have the mysqli_fetch_array($res) after the update call?
I've a problem when updating multiple Mysql rows when using an array, Lets start with the following submit form :
$n = array(); //Supplier Name
$s = array(); //Short Name
$o = array(); //Shipment No.
$id = array(); //Supplier ID
<form action="editing_supplier.php" method="post">
<input type="hidden" value="<?php echo $row['id'] ?>" name="id[]">
<input type="text" value="<?php echo $row['name']?>" required name="n[]">
<input type="text" value="<?php echo $row['short_name']?>" required name="s[]">
<input type="text" value="<?php echo $row['shipment_no']?>" required name="o[]">
<input type="submit" value="Confirm Editing" >
</form>
Now when clicking Submit, which directly opens up "editing_supplier.php" page- The following codes are bellow :
if((isset($_POST['n'])) && (isset($_POST['s'])) && (isset($_POST['o']))){
//Shows up the ID for each Supplier Name
if(is_array($_POST['id'])) {
foreach($_POST['id'] as $id){
//Updates Supplier Name
if(is_array($_POST['n'])) {
foreach($_POST['n'] as $value){
$query = "UPDATE suppliers SET name = '".$value."' where id ='".$id."'";
$result = mysql_query($query);
}
}
//Updates Short_Name
if(is_array($_POST['s'])) {
foreach($_POST['s'] as $value1){
$query = "UPDATE suppliers SET short_name = '".$value1."' where id ='".$id."'";
$result = mysql_query($query);
}
}
//Updates Shipment No.
if(is_array($_POST['o'])) {
foreach($_POST['o'] as $value2){
$query = "UPDATE suppliers SET shipment_no = '".$value2."' where id ='".$id."'";
$result = mysql_query($query);
}
}
//End of for Each id
}
}
What actually Does, When Selecting a single row to update..It works perfectly ! But when doing a multiple selection in-order to make an update for them, it messes up all the values..As if copying the last id,supplier name, short name and shipment no. to all the selected rows.
I think this is due to the series of foreach within the foreach($id). I would write :
foreach($_POST['id'] as $index=>$id) {
to keep track of the index of your record, and then do not do any other foreach but rather :
$query = "UPDATE suppliers SET name = '".$_POST['n'][$index]."' where id ='".$id."'";
so you keep the link between the $id value and the other variables.