Updating products in a mysqli database using PHP - php

Trying to update 1 row at a time using php.
I want to enable users to update products they have already added to a database, I have a simple form with the relevant fields:
<fieldset><legend><span> Update a product in the database! </span></legend>
<form id ="productsform" method="post" onsubmit="return false;" enctype="multipart/form-data">
<label> Product name: <input type="text" id="name" name="name"/> </label>
<label> Product quantity: <input type="number" id="quantity" name="quantity"/> </label>
<label> Product description: <input type="text" id="description" name="description"/> </label>
<label> Product price: <input type="text" id="price" name="price"/> </label>
</br>
<input id="submit" name="submit" type="button" class="reg" value="Update Product">
<div id="update"></div>
</form>
I am using ajax which is working correctly according the console, but im struggling with the php side of updating the rows:
<?php
include("dbase/config_database.php");
$id = $_POST["id"];
$name = $_POST['name'];
$quantity = $_POST['quantity'];
$description = $_POST['description'];
$price = $_POST['price'];
$query = "UPDATE products SET name = '{$name}', quantity = '{$quantity}', description = '{$description}', price = '{$price}'
WHERE id = {$id}";
mysqli_query($mysqli, $query);
?>
Here is the initial file I use to add the products to the database:
<?php
include("dbase/config_database.php");
//Stores all information passed through AJAX into the query
$name = $_POST['name'];
$quantity = $_POST['quantity'];
$description = $_POST['description'];
$price = $_POST['price'];
//Adds information to database
$query = "INSERT INTO products (name, quantity, description, price) VALUES ('$name','$quantity','$description','$price')";
//Runs the query
$result = $mysqli->query($query) OR die("Failed query $query");
echo $mysqli->error."<p>";
echo "Product Added";
$querynew = ("SELECT id as 'collectid' from products WHERE name = '$name'and quantity = '$quantity'and description ='$description'and price = '$price'");
$resultnew = $mysqli->query($querynew) OR die("Failed query $querynew");
while($info = mysqli_fetch_array( $resultnew)){
$productid = $info['collectid'];
}
$image = $_FILES['file1']['name'];
$type = $_FILES['file1']['type'];
$size = $_FILES['file1']['size'];
$tmp_name = $_FILES['file1']['tmp_name'];
$imgpath = "images/".$productid.".jpg";
// Run the move_uploaded_file() function here
$moveResult = move_uploaded_file($tmp_name, $imgpath);
// Evaluate the value returned from the function if needed
$querytwo = ("SELECT * FROM products WHERE name = '$name' and quantity = '$quantity' and description = '$description' and price = '$price'");
$resulttwo = $mysqli ->query($querytwo) OR die ("Failed query $querynew");
$info = array();
while($row = mysqli_fetch_assoc($resulttwo)){
$product = array("id" => $row ['id'],
"name" => $row ['name'],
"quantity" => $row ['quantity'],
"description" => $row ['description'],
"price" => $row ['price'],
);
array_push($info,$product);
}
$json_output = json_encode($info);
echo $json_output;
?>
Any help is much appreciated! I have messed around with the update php because im sure the problem is in there but cant find it.

You are not getting the $_POST["id"] from the form,because there is no input element with name id.
when you get all the data from the table then put the id in the form as a hidden field
like
<input type="hidden" name="id" value="<?=$row['id']?>">
then after submitting the form you'll get the id value in $_POST['id']
Always try to debug your code thoroughly try to print the query then you can easily know what is happening actually.All the best

Related

Using POST to update values through HTML form retrieves old values

I'm working on a CRUD system and currently, I am in the Update section. I have old values from users that need to be updated to new ones through an HTML form.
Right now I am trying to retrieve the POST values from the HTML form set to the post method. After that, I update the user info with the new values gained from the POST request.
<?php
$oldId = $_GET['id'];
$conn = mysqli_connect('localhost', 'root', '')
or die('Verbinding met database server is mislukt.');
mysqli_select_db($conn, 'crudopdracht')
or die('De database is niet beschikbaar');
$query = "SELECT * FROM gebruikers WHERE id = $oldId";
$result = mysqli_query($conn, $query)
or die (mysqli_error($conn));
while ($row = mysqli_fetch_assoc($result)){
$naam = $row['naam'];
$leeftijd = $row['leeftijd'];
$gender = $row['gender'];
$locatie = $row['locatie'];
};
?>
<form action="" method="post">
<label for="id">ID:</label><br>
<input type="text" id="id" name="id" <?php echo 'placeholder="' . $oldId . '"><br>';?>
<label for="naam">Naam:</label><br>
<input type="text" id="naam" name="naam" <?php echo 'placeholder="' . $naam . '"><br>';?>
<label for="leeftijd">Leeftijd:</label><br>
<input type="text" id="leeftijd" name = "leeftijd" <?php echo 'placeholder="' . $leeftijd . '"><br>';?>
<label for="gender">Geslacht:</label><br>
<input type="text" id="gender" name="gender" <?php echo '[placeholder="' . $gender . '"><br>';?>
<label for="locatie">Locatie:</label><br>
<input type="text" id="locatie" name = "locatie" <?php echo 'placeholder="' . $locatie . '"><br><br>';?>
<input type="submit" value="Verstuur" id="submit" name="submit">
</form>
</div>
<?php
if(isset($_POST["submit"])){
echo 'hello';
$id = $_POST["id"];
$naam = $_POST["naam"];
$leeftijd = $_POST["leeftijd"];
$gender = $_POST["gender"];
$locatie = $_POST["locatie"];
$query2 = "UPDATE gebruikers SET id = $id, naam = $naam, leeftijd = $leeftijd, gender = $gender, locatie = $locatie WHERE id = $oldId";
mysqli_query($conn,$query2);
}
?>
In my opinion, I expect the values to change to the new ones set in the HTML form, but they always return the old values.
SQL injection issues aside (as you've stated it isn't in scope of the particular issue), you need to correctly format your SQL query for any non-integer values, so that they are encapsulated with quotes ('[value]').
Your query would current run as:
UPDATE gebruikers ( id = somevalue, naam = somevalue, leeftijd = somevalue, gender = somevalue, locatie = somevalue WHERE id = 12345`
In this query, SQL would attempt to interpret your values as entities (columns, tables), which is obviously not what you want.
So, although you should never inject user input values into a query, the following should fix your issue:
Change
$query2 = "UPDATE gebruikers SET id = $id, naam = $naam, leeftijd = $leeftijd, gender = $gender, locatie = $locatie WHERE id = $oldId";
to
$query2 = "UPDATE gebruikers SET id = $id, naam = '$naam', leeftijd = '$leeftijd', gender = '$gender', locatie = '$locatie' WHERE id = $oldId";`
Assuming id is an INT field, and the others are strings.

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

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
}

Select values from SQL db and display in dropdown, submit form

The values from the db are displaying in the dropdown and I've gotten it to work with text values that weren't pulled from the db, but when I try it with values from the db and click 'Submit' the page reloads and nothing happens.
My code:
<form action="test.php" method="post">
<br />
<label for="name">Choose a name</label><br />
<select name="selected_value">
$query = "SELECT * FROM items WHERE user_id = $user_id";
$select_items = mysqli_query($connection, $query);
confirmQuery($select_items);
while($row = mysqli_fetch_assoc($select_items)) {
$item_id = $row['item_id'];
$item_name = $row['item_name'];
echo "<option value='$item_name'>{$item_name}</option>";
</select>
<button type="submit" name="submit_form">Submit</button>
</form>
if(isset($_POST['submit_form'])){
$selected_value = $_POST['selected_value'];
echo $selected_value;
}
Don't you have this the wrong way around?
$_POST['selected_value'] = $selected_value;
should be
$selected_value = $_POST['selected_value'];

PDO form add to database: Array number is added rather than the text it represents

I'm new to PHP and PDO. I've managed to get the PDO to add the form data to a mysql database when the submit button is clicked.
The problem I am having is drop down box which selects and displays the data from another database table. When this is added to the databases rather than displaying the selected option 'Top, Hat or Coat' it instead displays '0, 1, 2'.
HTML Code (with some PHP):
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<?PHP include_once("addProduct.php");?>
<form method="post" action="">
Product Name: <input type="text" id="productName" name="productName" /><br />
Catagory:
<?php
mysql_connect("localhost", "root","") or die(mysql_error());
mysql_select_db("web_scripting") or die(mysql_error());
$query = "SELECT id,category FROM catagory_table";
$result = mysql_query($query) or die(mysql_error()."[".$query."]");
?>
<select type="text" id="category" name="category">
<?php
while ($row = mysql_fetch_array($result))
{
echo "<option value='".$row['id']."'>'".$row['category']."'</option>";
}
?> </select><br />
Stock: <input type="number" id="stock" name="stock" /><br />
Cost: <input type="number" id="cost" name="cost" /><br />
<input type="submit" value="add"> <br />
<?PHP
$query = "SELECT * FROM product_table";
$result = $odb->query($query);
if($result->rowCount() > 0) {
foreach($result as $item) {
echo($item['name'] . " , " . $item['category'] . " , " . $item['stock'] . " , " . $item['cost'] . "<br />");
}
}
?>
</form>
</div>
</body>
PHP Code:
$host = "localhost";
$user = "root";
$db = "web_scripting";
$pass = "";
$odb = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
if(isset($_POST['productName'])) {
$productName = $_POST['productName'];
$category = $_POST['category'];
$stock = $_POST['stock'];
$cost = $_POST['cost'];
$q = "INSERT INTO product_table(name, category, stock, cost) VALUES(:name, :category, :stock, :cost);";
$query = $odb->prepare($q);
$results = $query->execute(array(
":name" => $productName,
":category" => $category,
":stock" => $stock,
":cost" => $cost
));
}
?>
I would say this is correct, your database is saving the id of the category which is what you want. The name of the category can be found by querying the category table for that id. This is relational database design. Consider if you did store the name of the category on the product table. Later down the line you then decided to change the name of the category, you would need to update all products records rather than just one category record.

SQL Update Query not updating records

I have a list of games that when clicked lead to a form that allows users to edit records before updating them.
Here is the Edit Games page;
<?php
$gameID = isset($_GET['gameID']) ? $_GET['gameID'] : '';
$gameYear = isset($_GET['gameYear']) ? $_GET['gameYear'] : '';
$gamePrice = isset($_GET['gamePrice']) ? $_GET['gamePrice'] : '';
$gameName = isset($_GET['gameName']) ? $_GET['gameName'] : '';
$sql = "SELECT * FROM game WHERE gameName = $gameName";
$queryresult = mysqli_query($conn, $sql)
or die (mysqli_error($conn));
$row = mysqli_fetch_assoc($queryresult);
$gameID = $row['gameID'];
$gameYear = $row['gameYear'];
$gamePrice = $row['gamePrice'];
$gameName = $row['gameName'];
?>
<div id="form">
<form action="updateGame.php" id="Update" method="get">
<label> Game ID
<input id="text" name="id" value = "<?php echo $gameID; ?>" />
</label>
<label> Year
<input type = "text" name = "year" value = "<?php echo $gameYear; ?>" />
</label>
<label> Price
<input type = "text" name = "price" value = "<?php echo $gamePrice; ?>" />
</label>
<label> Name
<input type = "text" name = "name" value = "<?php echo $gameName; ?>" />
</label>
<input type = "submit" value = "Update">
Here is the update page that runs when the submit button is clicked;
<?php
$gameID = isset($_GET['gameID']) ? $_GET['gameID'] : '';
$gameYear = isset($_GET['gameYear']) ? $_GET['gameYear'] : '';
$gamePrice = isset($_GET['gamePrice']) ? $_GET['gamePrice'] : '';
$gameName = isset($_GET['gameName']) ? $_GET['gameName'] : '';
$sql = "UPDATE game SET gameYear = '$gameYear', gamePrice = '$gamePrice', gameName = '$gameName' WHERE gameID = '$gameID'";
mysqli_query($conn, $sql)
or die (mysqli_error($conn));
mysqli_close($conn);
echo "Updated";
?>
The edit games page works and I can edit the records, when I press the submit button it comes up with the echo statement saying the record was updated, however, no changes happen and I'm not sure why.
Your form uses name="id", not name="gameID", so your $_GET['gameID'] variable is not set on any of your requests, but $_GET['id'] is. Update your form or your GET page, so that the names match.
You've forgot to append the variables in your query. I should be like this:
$sql = "UPDATE game SET gameYear = '".$gameYear."', gamePrice = '".$gamePrice."', gameName = '".$gameName."' WHERE gameID = '".$gameID."'";

Categories