using form textfield name from dynamic table outside whileloop - php

I got another problem with my Code.
I generate a dynamic table from SQL-content and use textfields in the table to, maybe someday, change the content.
The problems is, I cann't access the textfields from outside the whileloop to save the content, all I get is Undefined index error for every field.
<form method="POST" enctype="text/html">
<?php
require_once ('config.php');
$sql = " SELECT * FROM kassen ORDER BY name ASC ";
$db_erg = mysql_query( $sql );
echo "<tr>";
echo "<td>";
echo '<table border="1" width="80%" align="center">';
echo "<tr> <th>Name</th><th>Stand</th><th>Verbrauch</th><th>Einzahlungen</th></tr>";
while ($zeile = mysql_fetch_assoc($db_erg))
{
echo '<tr>';
echo '<td>'. $zeile['name'] . '</td>';
echo '<td><center>'. $zeile['bier_stand'] . '€</td>';
echo '<td>';
/* in the text below, i set the name to verbrauch"'.$zeile['id'] and
ergebnis"'.$zeile['id'] which should generate a new unique name for every
single text*/
echo '<center><input type="text" name="verbrauch"'.$zeile['id'].' value="0" size="10" />';
echo '</td>';
echo '<td>';
echo '<center><input type="text" name="einzahlung"'.$zeile['id'].' value="0" size="10" />';
echo '</td>';
echo '</tr>';
} echo '</table>';
?>
<center><input type="hidden" name="aktion" value="speichern" />
<center><input type="Submit" name="" value="speichern"/>
</form>
<?php
if (isset ($_POST['aktion']))
{
if ($_POST['aktion'] == "speichern" )
{
require_once ('config.php');
$sql = " SELECT * FROM kassen ORDER BY name ASC ";
$db_erg = mysql_query( $sql );
while ($zeile = mysql_fetch_assoc($db_erg))
{
$standalt = $zeile["bier_stand"];
/* now I try to put the value of the text to the DB, but all i get is
Undefined Index error */
$verbrauch = $_POST['verbrauch'.$zeile['id']];
$einzahlung = $_POST['einzahlung'.$zeile['id']];
$stand = $zeile["bier_stand"] - $verbrauch + $einzahlung;
$id = $zeile["id"];
$sql = "UPDATE kassen SET ";
$sql .= " bier_stand_alt = '$standalt', ";
$sql .= " bier_stand = '$stand', ";
$sql .= " bier_verbrauch = '$verbrauch', ";
$sql .= " bier_einzahlungen = '$einzahlung' ";
$sql .= " WHERE id='$id'";
}
echo '<h2>Änderungen übernommen</h2>';
echo 'zurück zur Bierkasse';
exit;
}
}
?>
Any idea what I'm messing up?

Sorry for questioning,
realy stupid mistake
echo '<center><input type="text" name="einzahlung"'.$zeile['id'].' value="0" size="10" />';
should have been
echo '<center><input type="text" name="einzahlung'.$zeile['id'].'" value="0" size="10" />';
so actually just the " was in wrong place ... stupid stuff that happens at 3am

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
}

Error displaying data into a input text field

I'm having a problem trying to display the data into a input field, instead of display What is on the database it display ' $row[coursename] ', the one that is on the <td> works fine.
Any ideas of How to fix this, I'm really new with php
<?php
require("coneccion.php");
if(empty($_SESSION['user']))
{
header("Location: index.php");
die("Redirecting to index.php");
}
$query = "SELECT courseid, coursename, id FROM courses where courseid = 179";
try
{
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
die("Error");
}
$rows = $stmt->fetchAll();
?>
<table>
<tr>
<th>Name</th>
</tr>
<?php
foreach($rows as $row):
echo "<tr>";
echo '<td>' . htmlentities($row['coursename'], ENT_QUOTES, 'UTF-8') . '</td>';
echo '<input type="text" name="coursename" value=" $row[coursename] " />';
echo '</tr>';
endforeach;
echo "</table>";
Move the variable outside of the string:
echo '<input type="text" name="coursename" value="' .htmlentities($row['coursename']) . '" />';
You can't add double quotes around it without also adding brackets (but that invovles a lot of error-prone escaping)
echo "<input type=\"text\" name=\"coursename\" value=\"{htmlentities($row['coursename'])}\" />";
This should work:
echo '<input type="text" name="coursename" value=" '.htmlentities($row['coursename']).' " />';

update mysql row with html form and php

I've been looking through many threads on here without finding a solution to my problem.
I've created a form that is supposed to show content of a database in input boxes, and when i change the content, it should be updated in the database.
No errors, nothing gets changed.
<?php
$con=mysqli_connect("localhost","root","","frontpage");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM frontpage_left_links")
or die("Error: ".mysqli_error($con));
while($row = mysqli_fetch_array($result)){
echo '<form action="" method="post">';
echo '<div style="float:left">';
echo '<table border="1" bordercolor="#000000">';
echo '<tr>';
echo '<td>link</td>';
echo '<td><input type="text" name="linkid" value="'.$row['link'].'"></td>';
echo '</tr>';
echo '<tr>';
echo '<td>img</td>';
echo '<td><input type="text" name="imgid" value="'.$row['img'].'"></td>';
echo '</tr>';
echo '<tr>';
echo '<td>tekst</td>';
echo '<td><input type="text" name="imgid" value="'.$row['name'].'"></td>';
echo '</tr>';
echo '<tr>';
echo '<td><input type="submit" id="update" name="gem" value="Gem"</td></td>';
echo '<td><input type="hidden" name="id" value="'.$row['id'].'"></td>';
echo '</tr>';
echo '</table></div>';
echo '<div style="float:left"><center><img src="img/'.$row['img'].'"><br />'.$row['name'].'</center></div>';
echo '</form><br /><br /><br /><br /><br /><br /><br /><br />';
}
if(isset($_POST['update'])){
$id = $_POST['id'];
$link = $_POST['linkid'];
$img = $_POST['imgid'];
$name = $_POST['nameid'];
$sql = mysqli_query("UPDATE frontpage_left_links SET link = '$link', img = '$img', name = '$name' WHERE id = '$id'");
$retval = mysqli_query( $sql, $con );
if(! $retval ){
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
}
mysqli_close($con);
?>
The form show the database content fine, but nothing happens when changed.
I appreciate any help I can get.
This is what it looks like now.
<?php
$con=mysqli_connect("localhost","root","","frontpage");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['gem']))
{
$id = $_POST['id'];
$link = $_POST['linkid'];
$img = $_POST['imgid'];
$name = $_POST['nameid'];
$sql = mysqli_query("UPDATE frontpage_left_links SET link = '$link', img = '$img', name = '$name' WHERE id = '$id'");
$retval = mysqli_query( $con, $sql );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
}
$result = mysqli_query($con,"SELECT * FROM frontpage_left_links")
or die("Error: ".mysqli_error($con));
while($row = mysqli_fetch_array($result))
{
echo '<form action="" method="post">';
echo '<div style="float:left">';
echo '<table border="1" bordercolor="#000000">';
echo '<tr>';
echo '<td>link</td>';
echo '<td><input type="text" name="linkid" value="'.$row['link'].'"></td>';
echo '</tr>';
echo '<tr>';
echo '<td>img</td>';
echo '<td><input type="text" name="imgid" value="'.$row['img'].'"></td>';
echo '</tr>';
echo '<tr>';
echo '<td>tekst</td>';
echo '<td><input type="text" name="nameid" value="'.$row['name'].'"></td>';
echo '</tr>';
echo '<tr>';
echo '<td><input type="submit" id="update" name="gem" value="Gem"</td></td>';
echo '<td><input type="hidden" name="id" value="'.$row['id'].'"></td>';
echo '</tr>';
echo '</table></div>';
echo '<div style="float:left"><center><img src="img/'.$row['img'].'"><br />'.$row['name'].'</center></div>';
echo '</form><br /><br /><br /><br /><br /><br /><br /><br />';
}
mysqli_close($con);
?>
Now i get this error.
Warning: mysqli_query() expects at least 2 parameters, 1 given in /Applications/XAMPP/xamppfiles/htdocs/page/admin.php on line 17
Warning: mysqli_query(): Empty query in /Applications/XAMPP/xamppfiles/htdocs/page/admin.php on line 19
Could not update data:
Because your udate is at the end of the page put it above the rest.
And also change isset($_POST['update'] to isset($_POST['gem']
<?php
$con=mysqli_connect("localhost","root","","frontpage");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['gem']))
{
$id = $_POST['id'];
$link = $_POST['linkid'];
$img = $_POST['imgid'];
$name = $_POST['nameid'];
$sql = "UPDATE frontpage_left_links SET link = '$link', img = '$img', name = '$name' WHERE id = '$id'";
$retval = mysqli_query($con,$sql );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
}
$result = mysqli_query($con,"SELECT * FROM frontpage_left_links")
or die("Error: ".mysqli_error($con));
while($row = mysqli_fetch_array($result))
{
echo '<form action="" method="post">';
echo '<div style="float:left">';
echo '<table border="1" bordercolor="#000000">';
echo '<tr>';
echo '<td>link</td>';
echo '<td><input type="text" name="linkid" value="'.$row['link'].'"></td>';
echo '</tr>';
echo '<tr>';
echo '<td>img</td>';
echo '<td><input type="text" name="imgid" value="'.$row['img'].'"></td>';
echo '</tr>';
echo '<tr>';
echo '<td>tekst</td>';
echo '<td><input type="text" name="imgid" value="'.$row['name'].'"></td>';
echo '</tr>';
echo '<tr>';
echo '<td><input type="submit" id="update" name="gem" value="Gem"</td></td>';
echo '<td><input type="hidden" name="id" value="'.$row['id'].'"></td>';
echo '</tr>';
echo '</table></div>';
echo '<div style="float:left"><center><img src="img/'.$row['img'].'"><br />'.$row['name'].'</center></div>';
echo '</form><br /><br /><br /><br /><br /><br /><br /><br />';
}
mysqli_close($con);
?>
try to replace :
echo '<td><input type="submit" id="update" name="gem" value="Gem"</td></td>';
with :
echo '<td><input type="submit" id="update" name="update" value="Gem"</td></td>';
In your form you are having update button name as gem but you are using if(isset($_POST['update'])) to run update query.
Change it to if(isset($_POST['gem']))
The easiest way would be to simply change the name attribute on your submit to the $_POST[] variable you used. name="update"The easiest way would be to simply change the name attribute on your submit to the $_POST[] variable you used. name="update"
Edit :: Answered already.
echo '<td><input type="submit" id="update" name="update" value="Gem"</td></td>';
Just delete the second td from above!!!

Categories