SQL Update Query not updating records - php

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."'";

Related

PHP Form array has empty values when inserting into MySQL table

I'm having an issue inserting php form array values into a MySQL table. Right now the form itself pulls worker information from another table to populate the fields and their values. Right now there are only three workers that would populate those fields, however as more workers get added, there could be as many as 40. When I add just the first worker from the form, all the information inserts normally. However, when I add more than one, the title and employeeId fields are blank and I can't figure out why. Any help would be greatly appreciated.
Here is the form:
<form method = 'POST' action = 'addworkers.php'>
<?php
$sql2 = "select * from workers where companyId = 1";
$result2 = mysqli_query($conn,$sql2);
$numRows = mysqli_num_rows($result2);
$check = 0;
while($row2 = $result2->fetch_assoc()) {
$employeeId = $row2["id"];
$name = $row2["name"];
echo '<input type="checkbox" name="employeeId[]" value="' . $employeeId . '">';
echo "$name\n";
echo '<input type = "hidden" value="' . $companyId . '" name = "companyId[]"/>';
echo '<input type = "hidden" value="' . $jobNumber . '" name = "jobNumber[]"/>';
echo 'Site Title : <input type = "text" name = "title[]"/><br/>';
}
?>
<input type="hidden" name="count" value="<?php echo "$numRows"; ?>"/>
<input type = 'submit' value = 'SEND'/>
</form>
Then the addworkers.php code
require_once("dbConfig.php");
session_start();
$timestamp = date("Y-m-d");
if (isset($_SESSION['loginname'])) {
$companyId = isset($_POST['companyId']) ? $_POST['companyId'] : "" ;
$jobNumber = isset($_POST['jobNumber']) ? $_POST['jobNumber'] : "" ;
$employeeId = isset($_POST['employeeId']) ? $_POST['employeeId'] : "" ;
$title = isset($_POST['title']) ? $_POST['title'] : "" ;
foreach($title as $key=>$value){
if (!empty($value)) {
$query = "insert into `Jobs` (id, companyId, jobId, employeeId, siteTitle, dateAdded) values (NULL,'$companyId[$key]', '$jobNumber[$key]','$employeeId[$key]','$value','$timestamp')";
$result = mysqli_query($conn,$query);
}
}
} else {
echo "Error";
}
I changed the echo "Error" line but the output was clear.
It must be a problem with how the array is counted but I'm not sure how to fix it. in the form, if I check the boxes next to each row, all the information is entered into the table properly. If I only check the second and/or third line, it doesn't include the Site Title and the employeeId is reversed.
Here is the output of the form:
<form method = 'POST' action = 'insertworkers.php'>
<input type="checkbox" name="employeeId[]" value="1">Mike
<input type = "hidden" value="1" name = "companyId"/>
<input type = "hidden" value="12345" name = "jobNumber"/>
Site Title : <input type = "text" name = "title[]"/>
<input type="checkbox" name="employeeId[]" value="2">Steve
<input type = "hidden" value="1" name = "companyId"/>
<input type = "hidden" value="12345" name = "jobNumber"/>
Site Title : <input type = "text" name = "title[]"/>
<input type="checkbox" name="employeeId[]" value="3">Roger
<input type = "hidden" value="1" name = "companyId"/>
<input type = "hidden" value="12345" name = "jobNumber"/>
Site Title : <input type = "text" name = "title[]"/>
<input type="hidden" name="count" value="3"/>
<input type = 'submit' value = 'SEND'/>
</form>
I also changed the foreach loop to a for loop since the array depth should be the same as all fields will be mandatory
require_once("dbConfig.php");
session_start();
$counter = "".$_POST["count"]."";
$timestamp = date("Y-m-d");
if ( isset( $_SESSION['loginname'] ) ) {
$companyId = isset($_POST['companyId']) ? $_POST['companyId'] : "" ;
$jobNumber = isset($_POST['jobNumber']) ? $_POST['jobNumber'] : "" ;
$employeeId = isset($_POST['employeeId']) ? $_POST['employeeId'] : "" ;
$title = isset($_POST['title']) ? $_POST['title'] : "" ;
for($i=0, $count = count($employeeId);$i<$count;$i++){
if (!empty($employeeId)) {
$query = "insert into `customerJobs` (id, companyId, jobId, employeeId, siteTitle, dateAdded) values (NULL,'$companyId', '$jobNumber','$employeeId[$i]','$title[$i]','$timestamp')";
$result = mysqli_query($conn,$query);
}
}
} else {
echo "Error";
}

Change a specific mysql column

So I've got this code, which changes my type column from a to d in my mysql database. But sadly, it changes even all the other type columns of all the other user ALTHOUGH I specified it with WHERE id_user = X(in the other codes, only the WHERE id_user = X varies like WHERE id_user = 1, WHERE id_user = 2 etc.):
<td><?php
if(isset($_POST['d'])){
$var2 = $_POST['d'];
$sql = "UPDATE users SET `type`= '$var2' WHERE id_user = 2 ";
$mysqli->query($sql) or die($mysqli->error);
}
if(isset($_POST['a'])){
$var2 = $_POST['a'];
$sql = "UPDATE users SET `type`= '$var2' WHERE id_user = 2 ";
$mysqli->query($sql) or die($mysqli->error);
}
?>
<?php
if ($result = $mysqli->query("SELECT `type` FROM users WHERE id_user = 2 ")) {
$r = mysqli_fetch_assoc($result);
}
echo implode($r);
echo implode($_POST);
?>
</td>
<td>
<form action="#" method="POST">
<input type="hidden" value="d" name="d"/>
<input type="submit" value="--Inaktiv--"/>
</form>
<form action="#" method="POST">
<input type="hidden" value="a" name="a"/>
<input type="submit" value=" --Aktiv-- "/>
</form>
Why does this happen and how do I change it the way, only the column of the right user changes? How do I determine the submit button to the specific $sql = "UPDATE users SETtype= '$var2' WHERE id_user = X "; ?

how to use the current value of a select option inside input field

I'm using phpmyadmin in Xampp, where I have made two tables;
Table 1: Category with its attributes as cat_id and cat_name (where cat_id is a Primary Key)
Table 2: Item with its attributes as item_id, item_name, item_price ... cat_id (where item_id is a Primary Key and cat_id is a Foreign Key)
I have also made the correct relationship in phpmyadmin.
The problem is to use the value i.e. cat_id of the selected cat_name in a select tag inside php.
ps. Im aware of being a subject to SQL Injection.
PHP
<?php
require ('config.php');
if(isset($_POST['check']))
{
if(isset($_POST['button']))
{
$catname = $_POST['cat'];
$que1 = "SELECT * FROM category WHERE cat_name = '$catname'";
$res1 = mysql_query($que1);
$row = mysql_fetch_array($res1);
$cat_db = $row['cat_name'];
if($catname == $cat_db || $catname == "")
{
echo "Catergory: $catname already exits. Failed to be inserted.";
}
else
{
$que = "INSERT INTO category (cat_name) VALUES('$catname')";
$res = mysql_query($que);
echo "Catergory: $catname inserted successfully.";
}
die();
}
if(isset($_POST['item_name']))
{
$i_id = $_POST['item_id'];
$i_name = $_POST['item_name'];
$i_quan = $_POST['item_quantity'];
$i_size = $_POST['item_size'];
$i_price = $_POST['item_price'];
$cat_id = $_POST['cat_id'];
$que = "INSERT INTO item(item_name, item_quantity, item_size, item_price, cat_id) VALUES('$i_name','$i_quan','$i_size','$i_price', '$cat_id')";
$run = mysql_query($que);
if(!$run)
echo "Item Details failed to Update.";
}
}
?>
HTML
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" href = "login.css">
</head>
<body>
<form action = "" method = "POST">
<p><label class = "field">Add Category:</label></p>
<input type = "text" name = "cat" class = "textbox-300" pattern = "[a-zA-Z0-9\. ]+" title = "Please enter your Category Name">
<button type= "submit" onclick = "location.href = '';" id = "savebutton" name = "button">Add Now</button>
<p><label class = "field">Add Item:</label></p>
<select name="cate">
<?php
$que1 = "SELECT * FROM category";
$res1 = mysql_query($que1);
while($row = mysql_fetch_array($res1))
{
$cat_id_db = $row['cat_id']; //use array over here
$cat_db = $row['cat_name']; //use array over here
?>
<option value="<?php echo $cat_id_db; ?>" ><?php echo $cat_db;?></option>
<?php } ?>
</select>
<?php
$que1 = "SELECT * FROM category WHERE cat_name = '$cat_db'"; //yahan masla hai bhai, how do i set '$cat_db' into a static variable?
$res1 = mysql_query($que1);
$row = mysql_fetch_array($res1);
$cat_db_id = $row['cat_id'];
?>
<p><label class = "field">Category ID:</label></p>
<input type = "text" name = "cat_id" value = "<?php echo $cat_id_db; ?>" class = "textbox-300" pattern = "[a-zA-Z0-9\. ]+"> <!-- this is the PROBLEM how do i use the value of a selected option ONLY? -->
<p><label class = "field">Item ID:</label></p>
<input type = "text" name = "item_id" class = "textbox-300" pattern = "[a-zA-Z0-9\. ]+"title = "Please enter your Item ID">
<p><label class = "field">Item Name:</label></p>
<input type = "text" name = "item_name" class = "textbox-300" pattern = "[a-zA-Z ]+"title = "Please enter your Item Name">
<p><label class = "field">Item Quantity:</label></p>
<input type = "text" name = "item_quantity" class = "textbox-300" pattern = "[a-zA-Z0-9\. ]+"title = "Please enter your Item Quantity">
<p><label class = "field">Item Size:</label></p>
<input type = "text" name = "item_size" class = "textbox-300" pattern = "[a-zA-Z0-9\.\, ]+"title = "Please enter your Item Size">
<p><label class = "field">Item Price:</label></p>
<input type = "text" name = "item_price" class = "textbox-300" pattern = "[a-zA-Z0-9\.\, ]+"title = "Please enter your Item Price">
<input type = "hidden" name = "check">
<input type = "submit" class = "button" name = "sub" value = "Save">
</form>
</body>
</html>
You will have the id of selected sub cat. so write a query to fetch the cat_id.
select * from sub_category where item_id = "posted id" and you will get the main category id.
Thanks to a member here i found the answer so im posting it here, in case anyone comes here looking for the same thing.
<select name="cate" onchange="changeInput(this.value);">
<?php //your php code here ?>
</select>
<p><label class = "field">Category ID:</label></p>
<input type = "text" name = "cat_id" id="cat_id" value = "change select to see me change" class = "textbox-300" pattern = "[a-zA-Z0-9\. ]+" title = "Please enter your Item Price">
</form>
<script>
var changeInput = function (val){
var input = document.getElementById("cat_id");
input.value = val;
}
</script>

Undefined Index PHP

I've done some searching but can't seem to work out the answer. I'm new to PHP.
Here is my HTML form;
<form id = "getGame" action="Form.php" method = "get">
<label> Serial
<input type = "search" name = "serial" />
</label>
<label> Title
<input type = "search" name = "title" />
</label>
<label> Year
<select name="gameYear">
<option value="1998">1998</option>
<option value="1999">1999</option>
<option value="2000">2000</option>
</select>
</label>
<label> Price
<input type = "search" name = "price" />
</label>
<input type = "submit" name="search" value = "Search">
</form>
Here is my PHP page;
include 'db_Conn.php';
$gameYear = $_GET ['gameYear'];
$sql = "SELECT serialNo, gameTitle, gameYear gamePrice FROM games WHERE gameYear = '$gameYear'";
$Games = mysqli_query($conn, $sql)
or die(mysqli_error($conn));
while ($row = mysqli_fetch_assoc($Games)) {
$serial = $row['serialNo'];
$title = $row['gameTitle'];
$gameYear = $row['gameYear'];
$gamePrice = $row['gamePrice'];
echo "<div>$serial, $title, $gameYear, $gamePrice</div>\n";
}
mysqli_free_result($Books);
mysqli_close($conn);
?>
My problem is when I run the form I get the following message "Notice: Undefined index: gameYear". However, on the line below it displays all the records from the game year I selected. Example of what displays below;
Notice: Undefined index: gameYear in ____ on line 40
493928, Test Drive, 2002, $12.95
Thanks, any point in the right direction is appreciated.
You missed one ,. Change it to:
$sql = "SELECT serialNo, gameTitle, gameYear, gamePrice FROM games WHERE gameYear = '$gameYear'";
if no data found in the database it will produce 4 errors . so first of all check any data found or not by mysqli_num_rows() function.
if (mysqli_num_rows($Games) > 0) {
while ($row = mysqli_fetch_assoc($Games)) {
$serial = $row['serialNo'];
$title = $row['gameTitle'];
$gameYear = $row['gameYear'];
$gamePrice = $row['gamePrice'];
echo "<div>$serial, $title, $gameYear, $gamePrice</div>\n";
}
}
Yes of course you missed one comma so sql should be like this
$sql = "SELECT serialNo, gameTitle, gameYear, gamePrice FROM games WHERE gameYear = '$gameYear'";

Updating products in a mysqli database using 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

Categories