How can I pull in field data by ID from MySQL database? - php

I have two PHP files: itemTransaction.php and recordItemTransaction.php. I can select which row I would like to record a transaction for from a table in itemTransaction, and it links to the correct row in the database in recordItemTransaction.php, leading to a form allowing me to edit the itemQuantity. I have a form that has a hidden ID field and a textbox for the user to enter in an updated itemQuantity, which will be submitted to the database upon submission. I would like to display the current itemQuantity to the user, so when they edit the itemQuantity, they know what the current quantity is before they edit it and record the transaction.
My issue is that in recordItemTransaction.php, I cannot figure out how to pull in both the values for ID and itemQuantity in the same file.
This links to recordItemTransaction.php. Since I am referencing ID here, I can retrieve it in the next file. But I cannot retrieve itemQuantity along with the ID. Only one or the other. So, when I switch it to...
...I can retrieve the itemQuantity value in the textbox, but when I submit the form, it cannot tell which row to update.
itemTransaction.php
$query = "SELECT * FROM `Items` WHERE `isActive` = 'Active'";
$result = mysqli_query($con, $query);
echo "<h1>Record Transaction | Items</h1>";
echo "<a href='../inventoryIndex.php'><button class='button'>Back</button></a>";
//Display Data
echo "<table class='applyFont' cellspacing='0' cellpadding='0'>";
echo "<tr>";
echo "<th></th>";
echo "<th>ITEM</th>";
echo "<th>COST</th>";
echo "<th>RECORD TRANSACTION</th>";
echo "</tr>";
while($row=mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td align='center' width='9%'><img src='/InventoryManager/InventoryManagerImages/Items/{$row['itemImage']}' width='115' height='125' style='display:block'></td>";
echo "<td align='center' width='30%'>{$row['description']}</td>";
echo "<td align='center' width='30%'>$ {$row['unitCost']}</td>";
echo "<td align='center'><a href='recordItemTransaction.php?ID={$row['ID']}'><img src='/InventoryManager/InventoryManagerImages/Icons/couple-of-arrows-changing-places.png' title='Record an update to inventory'></td>";
echo "</tr>";
}
?>
</body>
</html>
recordItemTransaction.php
>
>
<?php
if(isset($_POST['updateQuantity'])) {
//Connect to DB
$hostname = "******";
$username = "******";
$password = "******";
$dbName = "******";
$con = mysqli_connect($hostname, $username, $password, $dbName);
//Get Value From User
$itemQuantity = $_POST["itemQuantity"];
$ID = $_POST["ID"];
//Query to Update Data
$query = "UPDATE `Items` SET `itemQuantity`='$itemQuantity' WHERE ID='$ID'";
$result = mysqli_query($con, $query);
//Check if Query Was Successful
if($result) {
echo "<p style=font-family:'Roboto Condensed', sans-serif>Item quantity has been updated</p>";
} else {;
echo "<p style=font-family:'Roboto Condensed', sans-serif>Error updating the quantity of the item.</p>" . mysqli_error();
}
//Disconnect From DB
mysqli_close($con);
}
?>
<body>
</body>
</html>

Related

Fetching Multiple Rows from Table and Adding Them into Another Table and then Remove from Previous Table, Using Checkboxes

In my administrator page, a list of people that wanted to register to the website will be shown.
Requests are inserted to my membersneedreg table. When a user has been accepted, user's row will then be move to the members table.
While fetching data from membersneedreg, I've added a checkbox on each row and decided to have $num variable as its value, which increments on every loop.
My problem is how will the system confirm that my checkbox is selected, wherein when submitted, the selected data row will then be move from membersneedreg table into members table?
Help will gladly be appreciated. If you have any questions or alterations needed on my post, don't hesitate to comment.
<?php
$result_set = mysql_query("SELECT * FROM membersneedreg");
$num_messages = mysql_num_rows($result_set);
// Create connection
echo "<table border=1 align='center'>";
echo "<tr><th>MemberID</th><td>FirstName</td><td>LastName</td><td>Date of birth</td><td>Email</td><td>Address</td><td>PostCode</td><td>UserName</td><td>Password</td><td>Annadale Relationship</td></tr> ";
// Loop over all the posts and print them out
$num=0;
while( $row = mysql_fetch_assoc( $result_set ) ) {
$memberid1 = $row['MemberID'];
$fname1 = $row['FirstName'];
$lastn1 = $row['LastName'];
$DOB1 = $row['Date_of_Birth'];
$Email1 = $row['Email'];
$Address1 = $row['Address'];
$Postcode1 = $row['PostCode'];
$UserName1 = $row['UserName'];
$Password1 = $row['Password'];
$relationship1 = $row['Annadale_Relationship'];
$num++; //allows me to give each checkbox a different value.
echo "<form action='confirm_mem.php'>";
echo "<tr align='center'><th>$memberid1</th>";
echo "<td>$fname1</td>";
echo "<td>$lastn1</td>";
echo "<td>$DOB1</td>";
echo "<td>$Email1</td>";
echo "<td>$Address1</td>";
echo "<td>$Postcode1</td>";
echo "<td>$UserName1</td>";
echo "<td>$Password1</td>";
echo "<td>$relationship1</td>";
echo "<td><input type='checkbox' name='member' value='$num'></td></tr>";
}
echo "</table>";
echo "<input type='submit' name='submit' value='Add Member'>";
echo "</form>";
?>
Lets first convert your MySQL to MySQLi. I'll put some explanations inside the comments /* */ as I move forward to the code. IF you want to hear my advice, you should have just created 2 tables instead of 2 database. (Based on your explanation, you call membersneedreg and members as database).
Assume your membersneedreg and members are table, AND they both have the same columns.
You can save this, for example, as form.php:
<?php
/* ESTABLISH THE CONNECTION */
$con=mysqli_connect("YourHost","YourUsername","YourPassword","YourDatabase"); /* REPLACE THE NECESSARY HOST, USERNAME, PASSWORD, AND DATABASE */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
$result_set = mysqli_query($con,"SELECT * FROM membersneedreg");
$num_messages = mysqli_num_rows($result_set);
echo "<table border='1' align='center'>";
echo "<tr><th>MemberID</th><td>FirstName</td><td>LastName</td><td>Date of birth</td><td>Email</td><td>Address</td><td>PostCode</td><td>UserName</td><td>Password</td><td>Annadale Relationship</td></tr>";
/* FETCH THE DATA BASED ON THE QUERY RESULT_GET */
$num=0; /* THIS WILL BE SET AS YOUR COUNTER */
while($row = mysqli_fetch_array($result_set)){
$memberid1 = $row['MemberID'];
$fname1 = $row['FirstName'];
$lastn1 = $row['LastName'];
$DOB1 = $row['Date_of_Birth'];
$Email1 = $row['Email'];
$Address1 = $row['Address'];
$Postcode1 = $row['PostCode'];
$UserName1 = $row['UserName'];
$Password1 = $row['Password'];
$relationship1 = $row['Annadale_Relationship'];
$num++; /* INCREMENT NUM */
echo "<form action='confirm_mem.php' method='POST'>";
echo "<tr align='center'><th>$memberid1</th>";
echo "<td>$fname1</td>";
echo "<td>$lastn1</td>";
echo "<td>$DOB1</td>";
echo "<td>$Email1</td>";
echo "<td>$Address1</td>";
echo "<td>$Postcode1</td>";
echo "<td>$UserName1</td>";
echo "<td>$Password1</td>";
echo "<td>$relationship1</td>";
echo "<td><input type='checkbox' name='member[$num]' value='$memberid1'></td></tr>";
/* THIS IS IMPORTANT, YOU SHOULD PUT TO AN ARRAY THE VALUE OF THIS CHECKBOX, AND THE VALUE WILL BE BASED ON THE FETCH ARRAY. IN MY EXAMPLE, THE $memberid1 VARIABLE */
}
echo "</table>";
echo "<input type='hidden' name='hiddencounter' value='$num'>"; /* THIS IS FOR THE COUNTING PURPOSES */
echo "<input type='submit' name='submit' value='Add Member'>";
echo "</form>";
?>
confirm_mem.php
<html>
<body>
<?php
/* ESTABLISH THE CONNECTION */
$con=mysqli_connect("YourHost","YourUsername","YourPassword","YourDatabase"); /* REPLACE THE NECESSARY HOST, USERNAME, PASSWORD, AND DATABASE */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
if(isset($_POST['submit'])){
$counter=$_POST['hiddencounter'];
$member=$_POST['member'];
echo $counter." submitted checkboxes"; /* TO CHECK HOW MANY CHECKBOX HAS BEEN GENERATED */
for($x=0;$x<=$counter;$x++){
if(empty($member[$x])){ /* IF MEMBER IS EMPTY, DO NOTHING */
}
else {
/* GET THE DATA FROM MEMBERSNEEDREG TABLE */
$result=mysqli_query($con,"SELECT * FROM membersneedreg WHERE MemberID='$member[$x]'");
while($row=mysqli_fetch_array($result)){
$memberid1 = $row['MemberID'];
$fname1 = $row['FirstName'];
$lastn1 = $row['LastName'];
$DOB1 = $row['Date_of_Birth'];
$Email1 = $row['Email'];
$Address1 = $row['Address'];
$Postcode1 = $row['PostCode'];
$UserName1 = $row['UserName'];
$Password1 = $row['Password'];
$relationship1 = $row['Annadale_Relationship'];
}
/* THEN INSERT THE FETCHED DATA TO MEMBERS TABLE */
mysqli_query($con,"INSERT INTO members (MemberID, FirstName, LastName, Email, Address, PostCode, UserName, Password, Annadale_Relationship)
VALUES ('$memberid1','$fname1','$lastn1','DOB1','Email1','$address1','$Postcode1','$UserName1','$Password1','$relationship1')");
/* THEN DELETE FROM membersneedreg THE INSERTED DATA */
mysqli_query($con,"DELETE FROM membersneedreg WHERE MemberID='$member[$x]'");
} /* END OF ELSE */
} /* END OF FOR LOOP */
} /* END OF ISSET SUBMIT */
else {
header("LOCATION:form.php"); /* REDIRECT TO form.php IF DIRECTED TO THIS PAGE */
}
?>
</body>
</html>

Issue with Deleting rows from my second Table in my page

I have a Reports page with 2 tables, one show items in stock the other shows Items sold.
I made a delete option for them which provides a button at the right end side of the table to delete rows out of my table.
The Issue that I am having is that the Code works perfectly for the 1st table but for the second table, the code will execute but the data does not get deleted from the DB.
I think what is happening is that due to me using the same Code to delete from both tables, that only 1 works. ( I think I am not sure)
After looking at it for a while trying to find potential errors I made and trying to see what else might be the issue, I decided to ask u for help!
Here the code:
<?php
$config['conn'] = array(
'host' => 'localhost',
'username' => 'root',
'password' => '',
'dbname' => 'inventarisdb'
);
$conn = new PDO('mysql:host=' . $config['conn']['host'] . ';dbname=' . $config['conn']['dbname'], $config['conn']['username'], $config['conn']['password']);
$action = isset($_GET['action']) ? $_GET['action']: "";
if($action=='delete'){ //if the user clicked ok, run our delete query
try {
$query = "DELETE FROM BCD WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $_GET['id']);
$result = $stmt->execute();
echo "<div>Record was deleted.</div>";
}catch(PDOException $exception){ //to handle error
echo "Error: " . $exception->getMessage();
}
}
//select all data
$query = "SELECT ID, Categorie, SerieNummer, MacAdress, ProductCode, Prijs, RekNummer, PaletNummer, Hoeveelheid, Aantekeningen FROM BCD";
$stmt = $conn->prepare( $query );
$stmt->execute();
//this is how to get number of rows returned
$num = $stmt->rowCount();
if($num>0){ //check if more than 0 record found
echo "<table border='1'>";//start table
//creating our table heading
echo "<tr>";
echo "<th>Categorie</th>";
echo "<th>SerieNummer</th>";
echo "<th>MacAdress</th>";
echo "<th>ProductCode</th>";
echo "<th>Prijs</th>";
echo "<th>RekNummer</th>";
echo "<th>PaletNummer</th>";
echo "<th>Hoeveelheid</th>";
echo "<th>Aantekeningen</th>";
echo "</tr>";
//retrieve our table contents
//fetch() is faster than fetchAll()
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$Categorie}</td>";
echo "<td>{$SerieNummer}</td>";
echo "<td>{$MacAdress}</td>";
echo "<td>{$ProductCode}</td>";
echo "<td>{$Prijs}</td>";
echo "<td>{$RekNummer}</td>";
echo "<td>{$PaletNummer}</td>";
echo "<td>{$Hoeveelheid}</td>";
echo "<td>{$Aantekeningen}</td>";
echo "<td>";
//we will use this links on next part of this post
echo "<a href='#' onclick='delete_user( {$ID} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{ //if no records found
echo "No records found.";
}
?>
<script type='text/javascript'>
function delete_user( id ){
var answer = confirm('Are you sure?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id to the record to be deleted
window.location = 'Remove.php?action=delete&id=' + id;
}
}
</script>
<br/><br/><br/><br/><br/><br/><br/><br/><br/>
<?php
$config['conn'] = array(
'host' => 'localhost',
'username' => 'root',
'password' => '',
'dbname' => 'inventarisdb2'
);
$conn = new PDO('mysql:host=' . $config['conn']['host'] . ';dbname=' . $config['conn']['dbname'], $config['conn']['username'], $config['conn']['password']);
$action = isset($_GET['action']) ? $_GET['action']: "";
if($action=='delete'){ //if the user clicked ok, run our delete query
try {
$query = "DELETE FROM CDE WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $_GET['id']);
$result = $stmt->execute();
echo "<div>Record was deleted.</div>";
}catch(PDOException $exception){ //to handle error
echo "Error: " . $exception->getMessage();
}
}
//select all data
$query = "SELECT ID2, Klant, Categorie1, SerieNummer1, MacAdress1, ProductCode1, Prijs1, Hoeveelheid1, Aantekeningen1 FROM CDE";
$stmt = $conn->prepare( $query );
$stmt->execute();
//this is how to get number of rows returned
$num = $stmt->rowCount();
if($num>0){ //check if more than 0 record found
echo "<table border='1'>";//start table
//creating our table heading
echo "<tr>";
echo "<th>Klant</th>";
echo "<th>Categorie1</th>";
echo "<th>SerieNummer1</th>";
echo "<th>MacAdress1</th>";
echo "<th>ProductCode1</th>";
echo "<th>Prijs1</th>";
echo "<th>Hoeveelheid1</th>";
echo "<th>Aantekeningen1</th>";
echo "</tr>";
//retrieve our table contents
//fetch() is faster than fetchAll()
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$Klant}</td>";
echo "<td>{$Categorie1}</td>";
echo "<td>{$SerieNummer1}</td>";
echo "<td>{$MacAdress1}</td>";
echo "<td>{$ProductCode1}</td>";
echo "<td>{$Prijs1}</td>";
echo "<td>{$Hoeveelheid1}</td>";
echo "<td>{$Aantekeningen1}</td>";
echo "<td>";
//we will use this links on next part of this post
echo "<a href='#' onclick='delete_user( {$ID2} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{ //if no records found
echo "No records found.";
}
?>
<script type='text/javascript'>
function delete_user( id ){
var answer = confirm('Are you sure?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id to the record to be deleted
window.location = 'Remove.php?action=delete&id=' + id;
}
}
</script>
So in short: 1st Table: everything works, all data gets deleted
2nd Table: Appears to be working but after confirming the Delete, the data is still there and didn't get removed from my DB.
The Code for Table 2 is exactly the same as the code for Table 1 exepct for the Names of DB and Table etc.
I am hoping you can go over my code see if you notice anything that might be causing this.
Maybe if u agree with what I was thinking, that the same code will not work for both tables on the same page, that you can give an example or a link to how I can tackle this issue?
Sorry for the Long code!
Thank you in advanced!
You shouldn't mix the delete's because you might have an instance when one id be the same as the other, so you'll delete the wrong thing. But I don't believe that is your primary problem:
Your select is
SELECT ID2, Klant, Categorie1, SerieNummer1, MacAdress1, ProductCode1, Prijs1, Hoeveelheid1, Aantekeningen1 FROM CDE
But your delete is:
DELETE FROM CDE WHERE id = ?";
You're delete should probably be:
DELETE FROM CDE WHERE ID2 = ?";
To Prevent Deleting the wrong thing:
The easiest thing to do here, is change you're delete user JavaScript to accept an action parameter and specify which delete you want to perform, because both delete attempts are running right now.
JavaScript
You don't need the JavaScript twice on the same page. Just have it one time in your HEAD or right before the end of the body.
<script type='text/javascript'>
function delete_user( action, id ){
var answer = confirm('Are you sure?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id to the record to be deleted
window.location = 'Remove.php?action=' + action + '&id=' + id;
}
}
</script>
Checking Action
if ($action=='delete_BCD') {
// or
if ($action=='delete_CDE') {
Rendering Rows
echo "<a href='#' onclick='delete_user( \"delete_BCD\", {$ID2} );'>Delete</a>";
// or
echo "<a href='#' onclick='delete_user( \"delete_CDE\", {$ID2} );'>Delete</a>";

Function prepare() on a non-object error

I have looked up the error for this and I think I am calling the statement before for it to be initialized. I have made a simple connection class that I can include into all of my files that will be talking to the mysql server. Knowing how I am with things, I am most likely over thinking things. I cant seem to find what I am doing wrong.....
Top part of the code is cut off as it only contains the HTML head and php starting code that is non-important for this.
//include database connection
include('connection.php');
$action = isset($_GET['action']) ? $_GET['action']: "";
if($action=='delete'){ //if the user clicked ok, run our delete query
try {
$query = "DELETE FROM sc_steamgames WHERE appid = ?";
$stmt = $con->prepare($query);
$stmt->bindParam(1, $_GET['appid']);
$result = $stmt->execute();
echo "<div>Record was deleted.</div>";
}catch(PDOException $exception){ //to handle error
echo "Error: " . $exception->getMessage();
}
}
//select all data
$query = "SELECT * FROM sc_steamgames";
$stmt = $con->prepare( $query );
$stmt->execute();
//this is how to get number of rows returned
$num = $stmt->rowCount();
echo "<a href='add.php'>Create New Record</a>";
if($num>0){ //check if more than 0 record found
echo "<table border='1'>";//start table
//creating our table heading
echo "<tr>";
echo "<th>AppID</th>";
echo "<th>Title</th>";
echo "<th>Release Date</th>";
echo "<th>Last Updated</th>";
echo "</tr>";
//retrieve our table contents
//fetch() is faster than fetchAll()
//http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$appid}</td>";
echo "<td>{$title}</td>";
echo "<td>{$releasedate}</td>";
echo "<td>{$lastupdate}</td>";
echo "<td>";
//we will use this links on next part of this post
echo "<a href='edit.php?id={$appid}'>Edit</a>";
echo " / ";
//we will use this links on next part of this post
echo "<a href='#' onclick='delete_user( {$appid} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{ //if no records found
echo "No records found.";
}
?>
<script type='text/javascript'>
function delete_user( appid ){
//this script helps us to
var answer = confirm('Are you sure?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id to the record to be deleted
window.location = 'index.php?action=delete&id=' + appid;
}
}
</script>
</body>
</html>
connection.php
/* Database Info */
// Host/IP
$host = "localhost";
// Database Name
$db_name = "**";
// Username
$username = "**";
//Password
$password = "**";
/* End Database Info */
try {
$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
echo "Connection error: " . $exception->getMessage();
}

Send individual array results to printer based on id table

I'm working on a simple PHP script that stores user details in a MySQL database. I can run a query and have it return the individual records as long as the query matches the last name (pre-defined). Once I have the records, I want to be able to echo a print button next to each record so that the user can individually print each record.
The code is a mashup of several snippets of code and is working great, except the "print user data" part. I'm not a newbie in PHP, but I also know enough to navigate around a script. Here's what I've got so far.
<?php
//capture search term and remove spaces at its both ends if the is any
$searchTerm = trim($_GET['keyname']);
//check whether the name parsed is empty
if($searchTerm == "")
{
echo "Enter name you are searching for.";
exit();
}
//database connection info
$host = "localhost"; //server
$db = "users"; //database name
$user = "root"; //dabases user name
$pwd = "password1"; //password
//connecting to server and creating link to database
$link = mysqli_connect($host, $user, $pwd, $db);
//MYSQL search statement
$query = "SELECT * FROM details WHERE lastname LIKE '%$searchTerm%'";
$results = mysqli_query($link, $query);
/* check whether there were matching records in the table
by counting the number of results returned */
if(mysqli_num_rows($results) >= 1)
{
$output = "";
while($row = mysqli_fetch_array($results))
{
echo "<tr valign=bottom>";
echo "<td bgcolor=#ffffff background='img/dots.gif' colspan=6><img src=img/blank.gif width=1 height=1></td>";
echo "</tr>";
echo "<tr valign=center>";
echo "<td class=tabval><img src=img/blank.gif width=10 height=20></td>";
echo "<td class=tabval><b>".htmlspecialchars($row['firstname'])."</b> </td>";
echo "<td class=tabval>".htmlspecialchars($row['lastname'])." </td>";
echo "<td class=tabval>".htmlspecialchars($row['address'])."</td> ";
echo "<td class=tabval>".htmlspecialchars($row['phone'])." </td>";
echo "<button type=\"button\" class=\"formbutton\" onclick=\"printpage('" . $lastname . "'); \">Print User Data</button>";
echo "<td class=tabval></td>";
echo "</tr>";
$i++;
}
echo "<tr valign=bottom>";
echo "<td bgcolor=#fb7922 colspan=6><img src=img/blank.gif width=1 height=8></td>";
echo "</tr>";
echo $output;
}
else
echo "There was no matching record for the name " . $searchTerm;
?>
<br />
Done
echo "<button type=\"button\" class=\"formbutton\" onclick=\"printpage('" . $lastname . "'); \">Print User Data</button>";
This line is calling a javascript function called "printpage". Once you have that javascript function on the page, you'll be closer to your expected result.

How to pass multiple values using onChange to update a database in a php table

Purpose: To update an inventory database by using the onchange function by modifying the data displayed in a PHP table.
I am pulling my data from a database and displaying it in a table. I have the data displayed in text fields so they are editable. Once the data is edited my function uses the data provided by POST, preferably the item ID and the value, will be used to update the inventory.
Here is my 'inventory.php' code:
$db = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$inventory = mysqli_query($db, "SELECT item_id, item_name, item_quantity, item_cost, item_price FROM inventory");
$num_rows = mysqli_num_rows($inventory);
mysqli_close($db);
echo "<form id=\"update_add_inventory\" action=\"\" method=\"post\">";
echo "<table>";
echo "<tr>";
echo "<th>Item ID</th>";
echo "<th>Item Name</th>";
echo "<th>Item Quantity</th>";
echo "<th>Item Cost</th>";
echo "<th>Item Price</th>";
echo "</tr>";
$i = 1;
while($row = mysqli_fetch_array($inventory))
{
echo "<tr>";
echo "<td>".$row['item_id']."</td>";
echo "<td><input type=\"text\" name=\"item_".$i."_name\" onchange=\"updateInventory('update_inventory.php')\" value='".$row['item_name']."' /></td>";
echo "<td><input type=\"text\" name=\"item_".$i."_quantity\" onchange=\"updateInventory('update_inventory.php')\" value='".$row['item_quantity']."' /></td>";
echo "<td><input type=\"text\" name=\"item_".$i."_cost\" onchange=\"updateInventory('update_inventory.php')\" value='".$row['item_cost']."' /></td>";
echo "<td><input type=\"text\" name=\"item_".$i."_price\" onchange=\"updateInventory('update_inventory.php')\" value='".$row['item_price']."' /></td>";
echo "</td></tr>";
$i++;
}
echo "</table><br>";
echo "</form>";
Here is my 'onchange function':
function updateInventory(action)
{
document.getElementById('update_add_inventory').action = action;
document.getElementById('update_add_inventory').submit();
}
Here is my 'update_inventory.php' code:
$db = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$inventory = mysqli_query($db, "SELECT item_id, item_name, item_quantity, item_cost, item_price FROM inventory");
$num_rows = mysqli_num_rows($inventory);
$i = 1;
for ($n=1; $n<=$num_rows; $n++) {
if (isset($_POST['item_'.$i.'_name'])) {
$item_id = $_POST['item_'.$i.'_id'];
$item_name = $_POST['item_'.$i.'_name'];
$result = mysqli_query($db, "UPDATE inventory SET item_name='".$item_name."' WHERE item_id='".$item_id."'");
} else if (isset($_POST['item_'.$i.'_quantity'])) {
$item_id = $_POST['item_'.$i.'_id'];
$item_name = $_POST['item_'.$i.'_quantity'];
$result = mysqli_query($db, "UPDATE inventory SET item_quantity='".$item_quantity."' WHERE item_id='".$item_id."'");
} else if (isset($_POST['item_'.$i.'_cost'])) {
$item_id = $_POST['item_'.$i.'_id'];
$item_name = $_POST['item_'.$i.'_cost'];
$result = mysqli_query($db, "UPDATE inventory SET item_cost='".$item_cost."' WHERE item_id='".$item_id."'");
} else if (isset($_POST['item_'.$i.'_price'])) {
$item_id = $_POST['item_'.$i.'_id'];
$item_name = $_POST['item_'.$i.'_price'];
$result = mysqli_query($db, "UPDATE inventory SET item_price='".$item_price."' WHERE item_id='".$item_id."'");
}
$i++;
}
mysqli_close($db);
header('Location: inventory.php');
What I'm having trouble with is that I have been unable to find a way to pass the 'item ID' and the value being modified to the update script. I can do it by passing the data of what I need through the value and then using list and explode to separate them but by doing that I'm displaying the item ID in each text field, which is not good.
If you know of a way to pass both pieces of data to the script, using the onchange function, I'd appreciate the assistance.
You can add it as a parameter to your onChange function, then update a hidden field on your form with this value before it is submitted.
PHP
updateInventory('update_inventory.php', ".$row['item_id'].")
JavaScript
function updateInventory(action, item_id){
// update hidden form value with item_id
document.getElementById('item_id').value = item_id;
document.getElementById('update_add_inventory').action = action;
document.getElementById('update_add_inventory').submit();
}

Categories