send table row to next page - php

Im trying to make a simpel webshop where I list some items (to order) on each row there is a form field for tell how many the costumer wants of the item. Then she submit a button and the action is another page where the item will be added to an MYSQL table to be processed later Im thinkking that when user hit the submit there is a hidden field that send the itemid.
I need to get a way to make the itemid with me to the other side but I cant make the variable specific for the row. the ArtikelNR variable $row["ArtikelNr"] shoudld be assigned to the hidden form and be accessable on next page as ArtikelNr = $_REQUEST['ArtikelNr']; and it works so far but it always the laast item number not the itemnumber that i specific for the choosen row. How do I make $form4 = ' '; row speciific so i can catch it on next page and add it to the basket.
<?php include 'databas_connect.inc'; ?>
<?php
$sql = "SELECT `ArtikelNr`, `ArtikelNamn`, `Storlek`, `ArtikelPris`,
`artikelbild`FROM `artiklar` ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
echo "<table><tr><th>Antal</th><th>ArtikelNr</th><th> ArtikelNamn</th>
<th>Storlek</th><th>ArtikelPris</th><th>Artikelbild</th></tr>";
// output data of each row
while($row = $result->fetch_assoc())
{
$number =1;
$artnr = $row["ArtikelNr"];
$prefix = "pre_";
$sufix = 1;
${$prefix .$sufix} =$row["ArtikelNr"] ;
$form1 = '<form action="sida61.php" method="post">';
$form2 = '<label for="antal"></label>';
$form3 = '<input type="text" name="antal" size="2" maxlength="2"value="1" id="antal">';
$form4 = '<input type="hidden" name="ArtikelNr" value="'.${$prefix .$sufix}.'"/> ';
$form5 = '<input type="submit" name="btn_submit" value="KÖP" />';
$form6 = '</form>';
$form = $form1 . $form2 . $form3 . $form4 . $form5 ;
$img = "<img src=./img/>";
$image=$row['artikelbild'];
$path ="<img src='./img/".$image."' />";
echo "<tr><td>" .$form. "</td><td>" . $row["ArtikelNr"]. "</td><td>" .
$row["ArtikelNamn"]. " </td><td> " . $row["Storlek"]. " </td><td>" .
$row["ArtikelPris"]. " </td><td>".$path."</td></tr>";
++$sufix;
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
here is code for sida61.php
<?php include 'databas_connect.inc'; ?>
<?php
session_start();
$ArtikelNr = $_REQUEST['ArtikelNr'];
$antal = $_REQUEST['antal'];
//$KundNr = $_SESSION["Kund"];
// attempt insert query execution
$sql = "INSERT INTO `kundkorg`( `ArtikelNr`, `antal`, `KundNr`)
VALUES (1,$antal, 2)";
if(mysqli_query($conn, $sql)){
print_r($_REQUEST); // I just do this to se value of $_REQUEST it is always 8 since I have 8 items i dont know why
}
else
{
echo "ERROR: Could not able to execute $sql. " .
mysqli_error($conn);
}
// close connection
mysqli_close($conn);
//header("Location: 6.php");
?>

Not sure why you were attempting to add a prefix and a suffix as you say you want to pass just the $row["ArtikelNr"] in your hidden field.
You also missed concatenating your </form> closing tag into your $form variable.
So this code should achieve what you want.
while($row = $result->fetch_assoc()) {
$form .= '<form action="sida61.php" method="post">';
$form .= '<label for="antal"></label>';
$form .= '<input type="text" name="antal" size="2" maxlength="2"value="1" id="antal">';
$form .= "<input type='hidden' name='ArtikelNr' value='{$row['ArtikelNr']}'/>";
$form .= '<input type="submit" name="btn_submit" value="KÖP" />';
$form .= '</form>';
$img = "<img src='./img/{$row['artikelbild']}'/>";
echo "<tr><td>$form</td><td>{$row['ArtikelNr']}</td><td>
{$row['ArtikelNamn']}</td><td>{$row['Storlek']}</td><td>
{$row['ArtikelPris']</td><td>$path</td></tr>";
}

Yes I se now I missed to missed concatenating your closing tag into $form variable. the correct code is
$form1 = '<form action="sida61.php" method="post">';
$form2 = '<label for="antal"></label>';
$form3 = '<input type="text" name="antal" size="2" maxlength="2"value="1"
id="antal">';
$form4 = '<input type="hidden" name="ArtikelNr" value="'.
$row["ArtikelNr"].'"/> ';
$form5 = '<input type="submit" name="btn_submit" value="KÖP" />';
$form6 = '</form>';
$form = $form1 . $form2 . $form3 . $form4 . $form5 . $form6 ;
Thanks so much #RiggsFolly
When I tried your code it added a new form on each row making me have 9 input fields on row 9. but You helped me anyway!!

Related

Trying to update a single item's quantity when an item is "purchased" from my store, but every item in my table is updated. Why?

Please understand- I am not experienced with PHP. But I know I am close to figuring this out.
I have a table, generated by a while loop (getting data from a MySQL database), that gives the customer a list of albums from an artist. I want the customer to be able to input the quantity of the album they wish to purchase, and have the database update appropriately. I can get the code to loop through and update every album in my table (based on user input), but that is obviously not what I want. How can I make it so only ONE album is updated at a time??
Here is my code:
<div id = "MusicSearch"><h4>Search For Music</h4></div>
<div id="search">
<form method="post" action="get-records.php?go" id="searchform">
<input type="text" name="artistName">
<input type="submit" name="submit-form" value="Search">
</div>
<?php
if(isset($_POST['submit-form'])){
$artistName = $_POST['artistName'];
if(isset($_GET['go'])){
if(preg_match("/^[A-Za-z]+/", $_POST['artistName'])){
include 'include/connect.php';
$sql = "
SELECT y.artistName
, x.albumName
, x.albumID
, x.cost
, x.stock
FROM album x
JOIN artist y
ON x.artistID = y.artistID
WHERE y.artistName LIKE '%" .$artistName. "%'
";
$result = $con->query($sql);
echo '<table><tr><th>Artist</th><th>Album</th><th>Cost</th><th>Stock</th><th>Quantity</th></tr>';
?>
<?php
while ($row = $result->fetch_array()) {
$albumName=$row['albumName'];
$cost=$row['cost'];
//$albumID=$row['albumID'];
$stock=$row['stock'];
echo '<tr>';
echo '<td>' . $artistName . '</td>';
echo '<td>' . $albumName . '</td>';
echo '<td>' . $cost . '</td>';
echo '<td>' . $stock . '</td>';
?>
<td><form method="post" action="get-records.php">
<input type="hidden" name="albumID[<?php echo $row['albumID']; ?>]" value="<? echo $row['albumID']; ?>"></input>
<input type="number" name="quantity[<?php echo $row['albumID']; ?>]" value="<?php echo $row['quantity']; ?>"></input>
<input type="submit" name="purchase-form" value="Purchase"/></form></td>
<?php
}
echo "</table>";
}
}
}
if(isset($_POST['quantity'])){
foreach($_POST['albumID'] as $key => $id){
$quan = mysqli_real_escape_string($con, $_POST['quantity'][$key]);
$q = "UPDATE album SET stock = stock-$quan WHERE albumID = albumID";
try{
$result = $con->query($q);
if (!$result)
echo "Error, try again " . mysqli_error($con);
if(is_null('id'))
throw new Exception('Error. Try again');
}
catch (Exception $ex) {
echo '<div class="error">' . $ex->getMessage() . '</div>';
}
}
}
?>
replace your update query with this UPDATE album SET stock = 'stock-".$quan."' WHERE albumID = '".$id."'
May you need to use $_POST['albumID']'s value Instead of albumID, here
$q = "UPDATE album SET stock = stock-$quan WHERE albumID = $id";
albumID = albumID is true for all rows that's why its updating all records

Adding css to a form

I am trying to add CSS to my form but not sure how to do this. The form is created in php and MySQL, in browser it looks like: http://gyazo.com/5d099ead9bd6ea83859a5114b2438748
I need to allign the text and drop downs so they are in the equal throughout and add some spacing. Anyone help with CSS for this?
html currently:
<div class="wrap">
<img src="/images/logo.png" alt="Highdown logo" />
<h1>Entry form</h1>
</div>
css currently:
.wrap {
position: relative;
}
The form is produced with this:
if ($event_result = $con->query("SELECT Event.Name FROM event")) {
echo "<form method =\"POST\" action=\"save.php\"> ";
while ($row = $event_result->fetch_assoc()) {
echo $row['Name']. ' ';
if ($student_result = $con->query("SELECT Student.Form, Teacher.Form, Student.Forename, Student.Surname, Student_ID " .
"FROM Student, Teacher " .
"WHERE Student.Form = Teacher.Form AND Teacher.Username = '" . $_SESSION['Username'] . "'")) {
if ($student_result->num_rows) {
echo "<select name ='". $row['Name']."'>";
while ($row1 = $student_result->fetch_assoc()) {
echo '<option value="" style="display:none;"></option>';
echo "<option value ='" . $row1['Student_ID'] . "'>" . $row1['Forename'] . ' ' . $row1['Surname'] . "</option>";
}
echo "</select> <br />";
}
}
}
echo '<input type="submit" value ="Submit">';
echo '<input type="reset" value ="Reset">';
echo '<input type="button" value = "Add student" onclick="location.href=\'http://localhost/sportsday/addstudent.php\'">';
echo '<input type="button" value = "Delete student">';
echo "</form>";
}
Use
<form>
<table>
<tr> //1st Table row
<td></td> //Table column data
<td></td> //table column data
</tr> //1st row ends
<tr> // 2nd Table row
<td></td> //Table column data
<td></td> //table column data
</tr> //2nd row ends
</table>
</form>
This will give you a better layout of the form.
This should work i did not try as i dont have the database
//Query to display all events
if ($event_result = $con->query("SELECT Event.Name FROM event")) {
echo "<form method =\"POST\" action=\"save.php\"> ";
echo '<table>';
echo '<tr>';
echo '<td>';
while ($row = $event_result->fetch_assoc()) {
echo $row['Name']. ' ';
echo '</td>';
if ($student_result = $con->query("SELECT Student.Form, Teacher.Form, Student.Forename, Student.Surname, Student_ID " .
"FROM Student, Teacher " .
"WHERE Student.Form = Teacher.Form AND Teacher.Username = '" . $_SESSION['Username'] . "'")) {
if ($student_result->num_rows) {
echo '<td>';
echo "<select name ='". $row['Name']."'>";
while ($row1 = $student_result->fetch_assoc()) {
echo "<option value ='" . $row1['Student_ID'] . "'>" . $row1['Forename'] . ' ' . $row1['Surname'] . "</option>";
}
echo "</select> <br />";
echo '</td>';
echo '</tr>';
}
}
}
echo '</table>';
echo '<input type="submit" value ="Submit">';
echo '<input type="reset" value ="Reset">';
echo '<input type="button" value = "Add student" onclick="location.href=\'http://localhost/sportsday/addstudent.php\'">';
echo '<input type="button" value = "Delete student">';
echo "</form>";
}
?>
you can directly write in css
form {
⋮ declare css
}
or give name to form
form[name="value"]{
⋮ declare css
}
or add any class or id on form
#formid{
⋮ declare css
}
.formclass{
⋮ declare css
}
First , check your database...
May be there is Another Issue not related to Tabular Output.
So , First remove Table Tag..and check whether its working ?
Then try in HTML TABLE TAG
Otherwise give me sample database .sql File and complete PHP code in google drive or on shared drive.
So that I can check and identify where is problem ?

Use Delete Button to Delete Record from Database

I have a database containing books. On a page, I have loop that prints each record in the database which each book's title, author, publisher, date, and rating. I want to use a delete button at the bottom of each record in order to delete it.
When I click on the delete button, the page is updated, but the record is not deleted.
I have tried to find solutions to this problem, but have yet to. I tried to use the book_id category in my database table as my index, in order to identify each record and delete it but it does not work.
Here is the code for my button form, as it appears with html code:
while ($row = mysqli_fetch_array($result))
{
echo '<div id="forminput">';
$timestamp = strtotime($row['date']);
echo '<div id = "bookpicture">';
echo '<img src="images/Book Cover 8crop.jpg" alt="Book Cover">';
echo '</div>';
echo '<div id = "bookinfo">';
echo '<div id = "titleauthor">';
echo '<h3>' . htmlspecialchars($row['title'], ENT_QUOTES, 'UTF-8') . '</h3>';
echo '<p>' . htmlspecialchars($row['author'], ENT_QUOTES, 'UTF-8') . '</p>';
echo '</div>';
echo '</div>';
$id = htmlspecialchars($row['book_id'], ENT_QUOTES, 'UTF-8');
echo '</div>' ;
echo '<div id = "publisher">' ;
echo '<p>' . 'Published on' . " " . htmlspecialchars(date('F j, Y,', $timestamp),
ENT_QUOTES, 'UTF-8') .
" " . 'by' . " " . htmlspecialchars($row['publisher'], ENT_QUOTES, 'UTF-8') . '</p>';
echo '</div>';
echo '<div id = "formDelete">';
echo '<form name="deleteForm" method="post" id="deleteForm" action="index.php">';
echo '<input type="submit" value="Update" name="myAdd" id="myAdd" style = "width:
100px" required>';
echo '<input type="submit" value="Delete" name="myDelete" id="$id" style = "width:
100px" required>';
echo '</form>';
echo '</div>';
echo '</div>';
echo '<hr>' ;
echo '</div>';
}
?>
Here is the code from my index.php file.
else if (isset($_POST['myDelete']))
{
$ids = mysqli_real_escape_string($link, $_POST['$id']);
$sql="DELETE FROM readbooks WHERE book_id = '$ids'";
if (!mysqli_query($link, $sql))
{
$error = 'Error with submission: ' . mysqli_error($link);
include 'php/error.html.php';
exit();
}
}
Here is the updated code.
The Problem is you are not trying to send the row ID from the form.
In Form try sending row id from the form
echo '<input type="hidden" name="id" value="$id">'
try receiving that parameter
$id = $_POST['id'];
$con = mysql_connect("host address","mysql_user","mysql_pwd");
$query = "DELETE FROM readbooks WHERE id = $id";
mysql_query($query,$con);
Moving from comment, you're not actually getting the $id anywhere. Add a field to your form:
<input type='hidden' name='id' value='$id'>
and then refer to it in your php:
$ids = mysqli_real_escape_string($link, $_POST['id']);
Since your using mysqli now, use prepared statements. Do not directly use your user input to the query! Example:
$books = array();
// connection
$con = new mysqli('localhost', 'your_username', 'password_of_username', 'your_database');
if(isset($_POST['myDelete'])) {
$book_id = $_POST['myDelete']; // get the variable id
$stmt = $con->prepare('DELETE FROM readbooks WHERE book_id = ?');
$stmt->bind_param('i', $book_id);
$stmt->execute();
}
$result = mysqli_query($con, 'SELECT * FROM readbooks');
while($row = $result->fetch_assoc()) {
$books[] = $row;
}
?>
<form method="POST">
<table border="1" cellpadding="10">
<tr>
<th>Title</th>
<th>Author</th>
<th>Publisher</th>
<th></th>
</tr>
<?php foreach($books as $book): ?>
<tr>
<td><?php echo $book['title']; ?></td>
<td><?php echo $book['author']; ?></td>
<td><?php echo $book['publisher']; ?></td>
<td><button type="submit" name="myDelete" value="<?php echo $book['book_id']; ?>">Delete</button></td>
</tr>
<?php endforeach; ?>
</table>
</form>
I think you're having problem with the id that you are passing to your PHP code. Try to use var_dump($_POST) to see what is the content of your $_POST variable. As I can see, the index of $_POST is wrong.
<input type="submit" value="Delete" name="myDelete" id="$id" style = "width:100px" required>';
Try to change this to
<input type="submit" name="book_id" value="$id" style = "width:100px" required>';
In your php use this $_POST["book_id"] to get the value of book_id you posted.
Note : The attribute "name" of the input tags will be the index of your $_POST variable
I understand that you want to have a delete and update button at the same time. The problem is your logic behind the situation. You need to have a hidden field and put the id inside it. Try to use this.
echo '<form name="deleteForm" method="post" id="deleteForm" action="index.php">';
echo '<input type="hidden" value="$id" name="book_id" id="myAdd" required>';
echo '<input type="submit" value="Update" name="action" id="myAdd" required>';
echo '<input type="submit" value="Delete" name="action" id="$id" required>';
echo '</form>';
In your php code use try to have a condition like this :
$book_id = $_POST["book_id"];
if($_POST["action"] == "delete")
{
//do your deletion code here. use the variable $book_id
}
else{
//do your update code here.use the variable $book_id
}

values from form not being passed php html mysqli

I can't figure out why my values aren't being passed from the form. I can't spot an error.
The Form Code:
$table = $_POST['table'];
$id = $_POST['id'];
$count = 0;
$query = "SELECT * FROM `" . $table . "` WHERE id = " . $id;
$result1 = mysqli_query($link, $query);
echo '<center><table style="text-align:center">';
echo '<form action="edit-process.php" method="post">';
while($row = mysqli_fetch_assoc($result1)){
foreach($row as $key => $val){
if ($count > 0){
echo "<tr>";
echo "<td>" . $key . "</td>";
echo '<td><input type="text" name="' . $key . '" value="' . $val . '"></td>';
echo "</tr>";
$count++;
}
else $count++;
}
}
echo '<input type="hidden" name="table" value="' . $table . '" />';
echo '<input type="hidden" name="id" value="' . $id . '" />';
echo '<tr><td><input type="submit" value="Save Changes" /></td></tr>';
echo "</form>";
echo "</table>";
The php file:
$table = $_POST['table'];
$id = $_POST['id'];
$count1 = 0;
$count2 = 0;
$result = mysqli_query($link, "SHOW COLUMNS FROM `" . $table . "`");
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$keyNames[$count2] = $row['Field'];
$count2++;
}
}
while ($count1 < $count2){
if ($count1 > 0) {
$value = mysqli_real_escape_string($_POST[$keyNames[$count1]]);
$query2 = "UPDATE `" . $table . "` SET `" . $keyNames[$count1] . "` = '" . $value . "' WHERE id = " . $id;
echo $query2 . "<br>";
$result2 = mysqli_query($link, $query2);
$count1++;
}
else $count1++;
}
I am avoiding displaying the id column with all the counts. The output of the echo-ed queries are:
Any ideas?
EDIT
I'll take care of changing everything over to procedural style once I figure out this issue. If I get rid of the mysqli_real_escape_string, it passes all the data except those columns with spaces in them. I thought that's what backticks were for? Is there something else I can do to make the columns with two words pass data like those with one word?
You need to switch these rows -
echo '<center><table style="text-align:center">';
echo '<form action="edit-process.php" method="post">';
....
echo "</form>";
echo "</table>";
to
echo '<form action="edit-process.php" method="post">';
echo '<center><table style="text-align:center">';
....
echo "</table>";
echo "</form>";
Having the <form> inside the <table> is invalid code. It either needs to wrap the <table> or be inside <td></td>.
see also -
form inside table
Form inside a table
Update #1-
On your Edit
Spaces in <input name=""> will be replaced with _ so your $_POST[] name will not match your <input name="">. from the manual - http://www.php.net/manual/en/language.variables.external.php
Note:
Dots and spaces in variable names are converted to underscores. For example <input name="a.b" /> becomes $_REQUEST["a_b"].
see also -
Can <input> elements have capital letters and spaces in PHP

Values from dynamically produced checkboxes

I am trying to get the values of a dynamically created set of checkboxes in PHP but apparently I couldn't get it. The source codes are below.
The "managestaff.php" page would allow searching for staff via their names and throws out a list of names with checkboxes for the admin to check them and click on a "delete" button at the bottom to delete the staff whom are being checked.
The deletion would be done on "deletestaff.php" as the "delete" button on "managestaff.php" simply forwards these values to "deletestaff.php" to do deletion work of the staff.
"managestaff.php" page codes:
<b><h3>Manage Staff</h3></b><br/>
<form action="managestaff.php" method="POST">
<input name="form" type="hidden" id="form" value="true">
<table width=300>
<tr>
<td width=112>Staff Name: </td>
<td width=188><input type="text" class="textfield" name="sname" /><br/></td>
</tr>
</table><br/>
<input type="submit" value="submit" />
</form>
<?php
if (isset($_POST['form']) && (isset($_POST['sname'])) && $_POST['form'] == 'true') {
$space = ' ';
$staffname = mysql_real_escape_string($_POST['sname']);
$query = 'SELECT * from staff where staffname like \'%' . $staffname . '%\'';
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) != 0) {
echo '<br><br>';
echo '<table>';
echo '<tr><th>Staff ID' . $space . '</th><th>Staff Name' . $space . '</th></tr>';
echo '<form action="deletestaff.php" method="POST">';
echo '<input name="delstaffform" type="hidden">';
while ($row = mysql_fetch_array($result)) {
echo '<tr>';
echo '<td>' . $row['staffid'] . '</td><td>' . $row['staffname'] . '</td>';
// :Begin - dynamic checkbox generation for deleting staff
echo '<td>';
echo '<input type="checkbox" name="delstaff" value="' . $row['staffid'] . '" />';
echo '</td>';
// :End
echo '</tr>';
}
echo '<tr align="right"><td colspan="3"><input type="submit" value="delete"/></td></tr>';
echo '</form>';
echo '</table>';
}
}
?>
"deletestaff.php" page codes:
<?php
print_r('POST: ' . $_POST);
echo '<br>';
if (isset($_POST['delstaffform']) && isset($HTTP_POST_VARS)) {
echo 'Submission of delstaffform FOUND !';
echo 'Staff to delete' . $HTTP_POST_VARS['delstaff'];
}
else{
echo 'Submission of delstaffform NOT FOUND !';
}
?>
The "deletestaff.php" doesn't do delete for now as it's a test page.
The current output I get is "Submission of delstaffform NOT FOUND !".
Thanks for the solutions.
Try this:
<input type="checkbox" name="delstaff[]" value="' . $row['staffid'] . '"/>';
print_r your $_POST and you'll see it sticks your submissions nicely into an array for you.
<?php
if (isset($_POST['delstaff']) && is_array($_POST['delstaff'])) {
echo 'Submission of delstaffform FOUND !';
$array = $_POST["delstaff"];
foreach($array as $value){
echo "<br>Value: ".$value."<br>";
}
} else {
echo 'Submission of delstaffform NOT FOUND !';
}
?>
Found the answer on my own but nevertheless you are helpful :D . Thanks a lot.

Categories