I'm relatively new to php and mysql. What I'm trying to do in this section of code is update 2 columns of information in a database based on the inputs of 2 text boxes. Whenever I try and update the values in the database they update to 0. I placed echo statements after I declared the $ variables and the values of both variables was the same as what I had typed into the boxes. But when I run the sql_query the new values in the database are 0 rather than the values of the 2 $ variables. Any help would be much appreciated! Thanks in advance!
<?php
$result = mysql_query("SELECT * from place_order ORDER BY item_name;");
echo "<form action='' method='POST'>Select an item:<select name='selection'><option>Select...</option>";
while ($row = mysql_fetch_assoc($result))
{
$item_name = $row["item_name"];
echo "<option>$item_name</option>";
}
echo "</select>
<input type='submit' value='Select Item' style='float:right;'/>";
$selection = $_POST['selection'];
echo "<br><br>Type the updated information into the text fields<br><br>";
echo "
<table width='300'>
<tr>
<td align='left'>Item Cost(€): </td>
<td align='left'><input type='text' name='cost'></td>
</tr>
<tr>
<td align='left'>Item Quantity: </td>
<td align='left'><input type='text' name='quantity'></td>
</tr>
<tr>
<td align='left'></td>
<td align='left'><input type='submit' name='button' value='Submit'></td>
</tr>
</table>
";
$cost = $_POST['cost'];
$quantity = $_POST['quantity'];
$selection = $_POST['selection'];
$sql = "UPDATE place_order SET item_cost='$cost', quantity='$quantity' WHERE item_name='$selection' ORDER BY item_name;;";
$query_update = mysql_query($sql);
if($query_update)
{
echo "Table updated! Click View Stock in the menu to view the updated table";
}
echo"</form>";
?>
There are two forms in this script:
one with the select box
another with the input boxes
each of these forms post individually.
Let's have some kind of state transition table:
forms are showing first time initially, all values are either empty
or default.
you select an item name and submit the first form.
option list is posted and $_POST['select'] has a value which then
is properly populated in the second form
the script runs til the end and immediately inserts an empty row to
your database with the selected item name
you make your inputs in the second form and submit it
this has two input variables: cost and quantity which get posted
due to the fact that the option list is in the other form, it will
not be posted and $select is empty at that state
the update statement will run but with no result since there is no
empty item_name in the db - useless update.
simple solution: make just one form out of that and you're done (except error handling which is missing entirely ...)
second solution: if only $_POST['select'] is set, put the value of $select in a hidden field and exit the script after echo-ing the second form.
Related
The following code is in tag_show.php.I have to show all the data from the database and I am trying to edit the database from php code so i form the edit button at the end of all row in html table.
echo"<br><br><br><br>
<table border='6' style= 'background-color: #FFFFE0; color: #761a9b; margin: 2 auto;'>
<thead>
<tr>
<th>tag_title</th>
<th>description</th>
<th>show_in_welcome</th>
<th>status</th>
</tr>
</thread>
<tbody>";
while($row = mysqli_fetch_assoc($get_detail))
{
$_SESSION['tag_title'] =$row['tag_title'];
$_SESSION['description'] =$row['description'];
$_SESSION['show_in_welcome'] =$row['show_in_welcome'];
$_SESSION['status']=$row['status'];
echo
"<tr>
<td>{$_SESSION['tag_title']}</td>
<td>{$_SESSION['description']}</td>
<td>{$_SESSION['show_in_welcome']}</td>
<td>{$row['status']}</td>
<td><form action='edit.php' method='POST'><input type='hidden' name='tag_title' value='".$row["tag_title"]."'/><input type='submit' name='submit-btn' value='edit' /></form></td>
</tr>\n";
}
and the edit.php is
<?php
session_start();
echo"<form action='tag_show.php' method='post'>
<br><br><br>
Tag Title<br><input name='tag_title' type='text' value='{$_SESSION['tag_title']}'><br><br>
Description <br><input name='description' type='text' value='{$_SESSION['description']}'><br><br>
Show in welcome<br><input name='show_in_welcome' type='text' value='{$_SESSION['show_in_welcome']}'><br><br>
Status<br><input name='status' type='text' value='{$_SESSION['status']}'> <br><br>
<input name='submit1' type='submit' value='Update'>
</form>";
?>
but the $_SESSION returns the last row value in HTML table. But i want the receptive row value when i click on edit button.
You don't need a session variable to pass the value to edit.php file.
Hope there is a unique key to identify the record from database. I assume it as recordid. Pass this value to edit.php as a query string
tag_show.php
$output = '';
while($row = mysqli_fetch_assoc($get_detail)){
$output '<tr>
<td>'.$row['tag_title'].'</td>
<td>'.$row['description'].'</td>
<td>'.$row['show_in_welcome'].'</td>
<td>'.$row['status'].'</td>
<td>edit</td>
</tr>';
}
In edit.php, you can get the recordid from query string and retrieve the data from database to populate the form
<?php
if($_GET['editid']!=''){
//get record corresponding to the 'editid' from database
//I assume the record is for and store in a variable $editdata
?>
<form action="tag_show.php" method="post">
<br><br><br>
Tag Title<br><input name="tag_title" type="text" value="<?=$editdata['tag_title']?>"><br><br>
Description <br><input name="description" type="text" value="<?=$editdata['description']?>"><br><br>
Show in welcome<br><input name="show_in_welcome" type="text" value="<?=$editdata['show_in_welcome']?>"><br><br>
Status<br><input name="status" type="text" value="<?=$editdata['status']?>"> <br><br>
<input name="submit1" type="submit" value="Update">
</form>
<?php
}
?>
Looks like you are never updating the session data with the information received from the form. You will need something like this somewhere in your code.
$_SESSION['tag_title'] = $_POST['tag_title'];
$_SESSION['description'] = $_POST['description'];
$_SESSION['show_in_welcome'] = $_POST['show_in_welcome'];
$_SESSION['status']= $_POST['status'];
A few things to consider.
Make sure your db info does not overwrite the values after user submits form.
Always sanitize/validate user input before using it (unlike the above code, since it's just an example).
here session make no sense. each time loop runs previous value replaced therefore you are getting last value. Instead of you can use the concept of query strings. Instead of Printing Form print a anchor tag
<a href='file.php?id='.$row["tag_title"]>Edit</a>
Being your tag_title unique.
if(isset($_GET['id))
{
$id = $_['id']
// Your code based on id
}
Now using id run mysql query and select desired data and display in form
Certainly your code will return the last row as the session array overwrites the previous row's value after every iteration.
Make the session array as multi dimensional like $_SESSION[$id]["tag_title"] and then in your edit.php refer to the session array using the id value.
$_SESSION[$id] = array('tag_title' => $row['tag_title'], 'description' => $row['description'], 'show_in_welcome' => $row['show_in_welcome'], 'status' => $row['status'])
Then increment the $id after each iteration.
So, I have a basic PHP site that brings up a list of salespeople from a MySQL server when a selection from a drop-down box is submitted. I've set up a button to appear next to each result, and I want a php script to run when the button is clicked using MySQL data from that specific result. Everything works except the button that runs the second MySQL query. Here's an example of the table after the first query:
<table border="1">
<tr>
<td>Last name</td>
<td>First Name</td>
<td>Job Title</td>
<td>City</td>
<td>Client List</td>
</tr>
<tr>
<td>Bondur</td>
<td>Gerard</td>
<td>Sale Manager (EMEA)</td>
<td>Paris</td>
<td>
<form method="POST" action="empLookup.php">
<input type="submit" name="empLookup" value="Look up clients"
</td>
</tr>
</table>
By clicking on the button I would run a MySQL command like 'SELECT clients FROM blah WHERE employeeNumber = ?'
I don't have a problem with any of this except passing the value from the button to the PHP script.
This is what my PHP code looks like for handling the form submission and display of results. The button(s) in question are in the HTML table in the foreach loop.
<?php #this is the default php file for looking up Employees
$page_title = 'Our Associates by City';
require ('./pdoConn.php');
$sql = "SELECT DISTINCT city from Offices";
echo '<h1>Our Associates by City</h1>';
Type in a Name to view Years</a><br>';
//create the form
echo 'Please select a year: <br>';
echo '<form action="index.php" method="post">';
echo '<select name= "city">';
foreach($conn->query($sql) as $row)
{
//each option in the drop down menu is each and every year
//brought up by the query
echo '<option value ="'. $row['city'].' ">'. $row['city']. '</option>';
} //end of foreach
echo '</select>'; //end drop down menu
//now to create the submit button
echo '<br><input type="submit" name="submit" value="List"><br>';
echo '</form>'; //end of form
//This if statement runs when the submit button is clicked
if ($_SERVER[REQUEST_METHOD] == 'POST')
{
$flit = $_POST[city]; //the city variable from the HTML form will be used
echo '<br><br>';
$sql2 = "SELECT employeeNumber,lastName,firstName,jobTitle,city
FROM Employees,Offices
WHERE Employees.officeCode = Offices.officeCode AND city = ?";
$stmt = $conn->prepare($sql2);
$stmt->execute(array($flit));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo 'Contact any of our local staff: <br>';
//create a table of employees
echo '<table border="1"><tr><td>Last name</td><td>First Name</td>';
echo '<td>Job Title</td><td>City</td></tr>';
//time to populate the table, this loop runs for each entry
foreach($rows as $r)
{
echo '<tr><td>'.$r[lastName].'</td><td>'.$r[firstName].'</td><td>';
echo $r[jobTitle].'</td><td>'.$r[city].'</td><td>';
echo '<form method="POST" action="empLookup.php">';
//now to make the button which will search the employee's client list
echo '<input type="submit" name="empLookup" value="Look up clients"</td></tr>';
} //end foreach
echo '</table>';
} //end if server request post thing
?>
I does not completely understood your exact requirement but I think you want employee number into your button if this is your requirement then you can simply check this code
`echo '<input type="submit" name="empLookup" value="'.$r['emp_id_from_database'].'"</td></tr>';`
From your html code, your form looks empty.
You need to add the data to your html form. If you want to avoid the user to see you can use fields. Like it was in the comments said, use $variableName instead of ? in your query. Don't forget use \"$variableName\" to avoid mysql injections.
I took a second reading of your code: You realy should read a php book completly before you program stuff for productive company websites. There are beginner mistakes in your code. And some beginner mistakes leads to insecure websites. I hope this doesn't look an offense, but like an advise.
I am generating a dynamic order form in php based on varying search criteria from data in a MySQL database.
The order form is in effect a line-item list and could have several hundred line-items.
Each line-item will have the following data (simulated names) :
Row# ItemID ItemName Units/Pack Price/Unit.
In addition to the above data extracted from the database, I am adding 2 dynamic fields :
1. a check box to identify items to order
2. a text box to enter the qty ordered
<?php
$row=0;
while($item = mysqli_fetch_array($result))
{
$row++;
$id = "$item[ProductID]";
$name = "$item[Name]";
$units = "$item[PerPack]";
$price = "$item[Price]";
echo "<tr>
<td align='center'>$row</td>
<td align='center'>$id</td>
<td>$name</td>
<td align='center'>$units</td>
<td align='center'>$price</td>
<td align='center'><input type=checkbox id=$row name=ReviewID[] value='$id' /></td>
<td align='center'><input type=text size=3 maxlength=3 id=$row name=ReviewQty[] /></td>
</tr>";
}
?>
The order form is then processed by an order review script.
After much searching and experimenting I have come up with the following script.
<?php
$keys_array = $_POST['ReviewID'];
$keys_count = count($keys_array);
$values_array = array_filter($_POST['ReviewQty']);
$values_count = count($values_array);
$order_array = array_combine($keys_array, $values_array);
if($keys_count != $values_count){
$status = 'Error';
$error_message = "ORDER Quatities Mismatch";}
// html code omitted
if($status == 'Error') echo $error_message;
//html code omitted
if($keys_count != $values_count) exit();
//html code omitted
while (list ($key, $val) = each ($order_array))
{
echo "<tr>
<td align='center'>...</td>
<td align='center'>$key</td>
<td>...</td>
<td>...</td>
<td align='center'>...</td>
<td align='center'>...</td>
<td align='center'>...</td>
<td align='center'>$val</td>
</tr>";
}
?>
The problem with my solution is that is does not check that each selected checkbox has a corresponding qty value in the same row.
In other words if I check any 5 boxes and enter values in any 5 text boxes, it will pass the test.
I need a check which verifies the checkbox is in the same row (line-item) as the qty value.
It would also be great if I could parse all the line-item data for a selected checkbox, otherwise I would need to do another MySQL query in the review script.
I am having trouble getting an array with 2 values per key to work.
Any help/improvements would be appreciated.
TIA.
FWIW by experimentation I found that by using the row number as the key, I can match keys and do a cross-check the arrays that both have the same keys.
<td align='center'><input type=checkbox name=ReviewID[$row] value='$id' /></td>
<td align='center'><input type=text size=3 maxlength=3 name=ReviewQty[$row] /></td>
I can also parse the other data via hidden fields in separate arrays once again with the row number as keys.
<td align='center'>$price</td><input type=hidden name=ReviewPrice[$row] value='$price' />
All I have to do now is match key values, then I can pull up only the data I need.
I am still interested in any better solutions, o/wise I hope someone else finds this useful - I know I really struggled to get to this point.
i have one html table with all the rows value from a specific database table.
I created a html table column to eliminate a specific row from the database, inside this column exists a checkbox to check and eliminate multiple table rows from the database.
But i'm having some problems, i can only delete the last row, example: Lets imagine that you check the second row, and you click at submit button and nothing happens.
But if you check the last inserted row, and you click submit, it deletes the row from the database.
I just can delete the last row, i can't delete multiple rows by checking a specific number of checkboxes.
I did this:
I'm using the MVC structure:
View:
<form method='POST'>
<?php
echo "<td><input style='width: 50px;' class='delete' value='delete' type='submit' name='del[]' /></td>";
foreach($editjoarray as $key){
echo "
<table>
<tr>
<td> ".$key['id']."</td>
<td><input type='checkbox' name='delete[]' value=".$key['id']." /></td>
</tr>
</table>
</form>";
}
Model:
function fname(){
if(isset($_POST['del']) && !empty($_POST['delete'])) {
{
$checkbox = $_POST['delete'];
$countCheck = count($_POST['delete']);
for($i=0;$i<$countCheck;$i++) {
$del_id = $checkbox[$i];
echo $del_id;
$sql = "DELETE FROM mytable WHERE id=$del_id";
$exe = mysql_query($sql) or die(mysql_error());
}
}
}
printFunction();
}
You are closing the form tag inside the loop so there will always be only one delete checkbox (as post values). You need to move the closing tag of the form </form> outside the loop so that all the checkboxes lies in the same form.
<form method='POST'>
<?php foreach($editjoarray as $key){
/*
delete checkboxes
input fields
*/
} ?>
</form>
I have a list of 'orders' being pulled out, which consist of product name, description etc, one of the fields is quantity which is in an editable text box, next to that is an update button (which has an unique ID for that row pulled from the DB). Now when the update button is pressed, I want the quantity for that product to be updated. However i'm having problems getting the correct updated quantity to be matched with the ID of that row.
I can see that the problem is me setting the $quantity1 variable with just the last result pulled out inside the IF statement, but I can't think how to get it to relate the row i'm clicking on. Here is part of the code:
echo "<td>".$row['uName']."</td>";
echo "<td>".$row['prodID']."</td>";?>
<form method="post" action="reserved.php">
<td><input name="quantity1" type="text" id="quantity1" size="1" value='<?= $qty ?>' />
<td><input name="order2" id="order2" type="submit" class="button_add" value='<?= $row['ID']?>' /></td><?
echo "</tr>";
}
}elseif(!empty($studyDir) && $rowCount == 0){
?>
<?
}
}
if (isset($_POST['order2'])){
$order2 = $_POST['order2'];
$quantity1 = $_POST['quantity1'];
\\echo $quantity1;
$link3 = mysql_connect('localhost', '******', '******');
$SQL1 = "UPDATE ybsinter_stock.reservedStock SET qty = $quantity1 WHERE ID = '$order2'";
$result1 = mysql_query($SQL1);
mysql_close($link3);
unset($quantity1);
unset($order2);
header("Location:reserved.php");
}
?>
I can't see your form ending i.e. there is no <\form>.
Also note that declaring forms in tables (except entirely enclosed in a td) is bad HTML, run your code through the W3C validator.
Also try PHP heredocs for outputting blocks of HTML with embedded data....
echo <<<EOF
<tr>
<td>{$row['uName']}</td>
<td>{$row['prodID']}</td>
<td>
<form method="post" action="reserved.php">
<input name="quantity1" type="text" id="quantity1" size="1" value="{$qty}" />
// style this button right with CSS if you want ...
<input name="order2" id="order2" type="submit" class="button_add" value="{$row['ID']}" />
</form>
</td>
</tr>
EOF;
The above form will only submit data to your script with the id that you're interested in..
Your SQL query seems roughly correct, but beware of SQL injection - please bind your variables into your queries instead of inserting them. Use the mysqli or PDO libraries instead of the outdated basic mysql functions.
$mysqli = new mysqli( /* your connection params here */ );
$sql1 = 'UPDATE ybsinter_stock.reservedStock SET qty = ? WHERE ID = ?';
$stmt = $mysqli->query( $sql1);
$stmt->bind_param( 'sd', $quantity1, $order2);
$result = $stmt->execute();