Simple update/edit of data not working with PHP/MySql - php

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
}

Related

My PHP Code is Not Updating Values In Database

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;

Use php/MySQL result in new query

I've searched around and haven't found anything similar, but it sounds like it should be pretty easy...
I have a search query that searches for a specific userID and displays that information for that user. However, I have one field (let's call it "favorite color" for this example) that will need to be manually updated frequently. So, I want to Search by userID, display the results, somehow re-use the original userID, and update the "favorite color" by the user entry. The part I can't figure out yet is how to store/re-use the userID.
The only way I can get it to work is ->
Search for userID, display results and also populate two new text form fields with original userID as well as "favorite color" to be submitted again by a new UPDATE query. But I don't want the userID to be a text form field, I just want to store the variable use it again.
Does that make sense? =)
Here is a sample of my current code. BTW, it works 100% this way right now, just need to figure out how to store the variable instead of using it again in a text box where I submit the UPDATE query.
<div class="searchBox">
<form method="POST" name="search" action="filter-update.php" class="form-wrapper cf">
<input type="text" name="querySearch" placeholder="User ID" required>
<button type="submit">Search</button>
</form>
</div>
<div id="results">
<?php
if (isset($_POST['querySearch'])){
$query = $_POST['querySearch'];
$min_length = 8;
if(strlen($query) >= $min_length){
$query = htmlspecialchars($query);
$query = mysqli_real_escape_string($conn, $query);
$sql = "SELECT * FROM sites WHERE userID = $query";
$raw_results = mysqli_query ($conn, $sql) or die ('error getting data from database');
if(mysqli_num_rows($raw_results) > 0){
while ($results = mysqli_fetch_array($raw_results)) {
echo "<div class='title'>User ID:</div><div class='info'>".$results['userID']."</div>";
echo "<div class='title'>Name:</div><div class='info'>".$results['name']."</div>";
echo "<div class='title'>Fav Color:</div><div class='info'>".$results['favColor']."</div>";
$userID = $results['userID'];
}
}
else { // if there is no matching rows do following
echo "No results";
}
}
else{ // if query length is less than minimum
echo "<br>Minimum length is ".$min_length;
}
}
?>
</div>
<div class="searchBox">
<form method="POST" name="filterUpdate" action="filter-update.php" class="form-wrapper cf">
<input type="text" name="UserID" value="<?php echo $userID;?>" required><br><br><br>
<input type="text" name="favColor" placeholder="New favColor here..." required>
<button type="submit">Update</button>
</form>
</div>
<div id="results">
<?php
if (isset($_POST['filterUpdate'])){
$queryFilter = $_POST['filterUpdate'];
$userID = $_POST['userID'];
$min_length = 1;
if(strlen($queryFilter) >= $min_length){
$queryFilter = htmlspecialchars($queryFilter);
$userID = htmlspecialchars($userID);
$queryFilter = mysqli_real_escape_string($conn, $queryFilter);
$userID = mysqli_real_escape_string($conn, $userID);
$sql = "UPDATE sites SET favColor = '$queryFilter' WHERE userID = '$userID'";
$raw_results = mysqli_query ($conn, $sql) or die ('error getting data from database');
}
else{ // if query length is less than minimum
echo "<br>Minimum length is ".$min_length;
}
}
?>
</div>
You can try either of this:
Hidden Field:
<input type="hidden" name="UserID" value="<?php echo $userID;?>">
Session:
$_SESSION['userID'] = $userID;
Don't know if this will work, but you can put the $userID above all the codes(like a global var).

Insert, Update, Search in MySql database using PHP

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.

Update array into sql database

I want to update my array into my database with the data from the form. Below is my form:
$query = "SELECT category FROM `$tablename`";
$result2 = mysqli_query($link, $query);
$rowcount = mysqli_num_rows($result2);
if ($rowcount > 0) {
?>
<div class="center_content">
<div id="right_wrap">
<div id="right_content">
<ul id="tabsmenu" class="tabsmenu">
<li class="active">Update Category</li>
<li class="">Add Category</li>
<li class="">View All Category</li>
</ul>
<div id="tab1" class="tabcontent">
<div style="margin:0 auto" align=center>
</div>
<div class="form">
<form action="editCatB.php" method="post">
<div class="form_row">
<label>Outlet Name:</label>
<input type="text" class="form_input" name="tablename" value="<?php echo $name; ?>"readonly/>
</div>
<div class ="form_row">
<label>Outlet Category/Stalls :</label>
</div>
<div class="form_row">
<div class="input_fields_wrap">
<?php
mysqli_data_seek($result2, 0);
while ($row2 = mysqli_fetch_array($result2, MYSQLI_ASSOC)) {
?>
<div><input class="form_input" type="text" name="mytext[]"value="<?php echo $row2['category']; ?>
"></div>
<?php
}
}
?>
And here is my sql. I want to know how to update the respectively row. Because right now it just update all of my category into the first value
$tableName = $_POST['tablename'];
$values = $_POST['mytext'];
$tableCat = $tableName . "categoryList";
$newString = preg_replace('/\s+/', '', $values);
for ($i = 0; $i < count($newString); $i++) {
$cat = $newString[$i];
$sql = "UPDATE `$tableCat` SET category = `$cat`";
$result = mysqli_query($link, $sql) or die(mysqli_error($link));
It also returns me with the error 'Unknown column 'abc' in 'field list'
1) Backticks are for table names and column names, not column values. You'll want to use regular quotes, or take advantage of mysqli's bindings, which is recommended to prevent sql injection.
2) You want to use a WHERE clause when updating. I'd suggest using the id value for the row when creating the table
<div><input class="form_input" type="text" name="mytext[<?php echo $row2['id']?>]" value="<?php echo $row2['category']; ?>"></div>
Then when you iterate through the values, you can pull out the id:
foreach($newString as $id=>$cat) {
$sql = "UPDATE `$tableCat` SET category = '$cat' WHERE id = '$id'";
$result = mysqli_query($link, $sql) or die(mysqli_error($link));
}
First,
$sql = "UPDATE `$tableCat` SET category = `$cat`";
Should be more like:
$sql = "UPDATE `$tableCat` SET category = '$cat'";
That being said, you're extremely vulnerable to SQL injection. Look into prepared statements.
If you want to update multiple rows with conditionals, you would follow a pattern similar to this:
$sql = "
UPDATE `$tableCat` SET
category = '$cat',
foo = '$foo',
bar = '$bar'
WHERE baz = '$baz'
";

Form edit is blanking out my entries

So I've got a form to edit entries which is populating with what has already been entered from the database. When I make an edit, it is saving and redirecting me back to the listing page with no errors, but it's not changing anything. I'm guessing it's getting confused as to where to pull the values from.
This is the the SQL Query to populate the form with the values (this part works):
<?php
// query db
$gigid = $_GET['gigid'];
$con = mysqli_connect("***********","***********","***********","***********");
$result = mysqli_query($con, "SELECT * FROM gigs WHERE gigid=$gigid") or die(mysqli_error());
$row = mysqli_fetch_array($result);
mysqli_close($con);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$gig_name = $row['gig_name'];
$gig_type = $row['gig_type'];
$gig_date = $row['gig_date'];
$gig_customer = $row['gig_customer'];
$gig_venue = $row['venue_name'];
$gig_fee = $row['gig_fee'];
$gig_status = $row['gig_status'];
}
?>
This is an excerpt from the form:
<form class="form-horizontal" id="create-ticket" method='post' action='edit_gig_process.php? gigid=<?php echo $_GET['gigid']; ?>'>
<fieldset>
<legend>Edit Gig Information</legend>
<input type="hidden" class="input-xxlarge" id="gig_date_created" name="gig_date_created">
<input type="hidden" class="input-xxlarge" id="userid" name="userid">
<div class="control-group">
<label class="control-label" for="gigid">Gig ID</label>
<div class="controls">
<input type="text" name="gigid" disabled="disabled" value="<?php echo $_GET['gigid']; ?>" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="gig_name">Gig Name (Required)</label>
<div class="controls">
<input type="text" class="input-xxlarge" id="gig_name" value="<?php echo $row['gig_name']; ?>" name="gig_name">
</div>
</div>
This is an excerpt from the update query:
$gigid = $_GET['gigid'];
$sql= "UPDATE gigs set
gig_name='$gig_name',
gig_type='$gig_type',
gig_customer='$gig_customer',
gig_date='$gig_date_created',
gig_start_time='$gig_start_time',
gig_end_time='$gig_end_time',
gig_fee='$gig_fee',
gig_status='$gig_status',
venue_name='$venue_name',
venue_address='$venue_address',
venue_contact='$venue_contact',
WHERE
gigid='$gigid'";
header('Location: http://managegigs.com/cp/my-gigs.php');
mysqli_close($con);
You are not running a update query, your update is just a string.
After
$sql= "UPDATE gigs set
gig_name='$gig_name',
gig_type='$gig_type',
gig_customer='$gig_customer',
gig_date='$gig_date_created',
gig_start_time='$gig_start_time',
gig_end_time='$gig_end_time',
gig_fee='$gig_fee',
gig_status='$gig_status',
venue_name='$venue_name',
venue_address='$venue_address',
venue_contact='$venue_contact'
WHERE
gigid='$gigid'";
add:
mysqli_query($con,$sql);
also, at least change this:
$gigid = $_GET['gigid'];
add:
$gigid = mysqli_real_escape_string($gigid);
directly after to have it a little secured. Putting $_GET directly to DB is dangerous.
Uploadpart in complete:
$gig_name = $_POST['gig_name'];
// fetch all $_POST(ed) data
// and secure with
$gig_name = mysqli_real_escape_string($con,$gig_name);
$gigid = $_GET['gigid'];
$gigid = mysqli_real_escape_string($con,$gigid);
$sql= "UPDATE gigs set
gig_name='$gig_name',
gig_type='$gig_type',
gig_customer='$gig_customer',
gig_date='$gig_date_created',
gig_start_time='$gig_start_time',
gig_end_time='$gig_end_time',
gig_fee='$gig_fee',
gig_status='$gig_status',
venue_name='$venue_name',
venue_address='$venue_address',
venue_contact='$venue_contact'
WHERE
gigid='$gigid'";
mysqli_query($con,$sql);
header('Location: http://managegigs.com/cp/my-gigs.php');
mysqli_close($con);

Categories