Insert checkbox corresponding quantity into database - php

I have multiple checkbox in my form and the person need to input the quantity of the types of item that is selected. Now, my problem is that I can't get the data to be inserted into database.
This is my add_record.php code:
<?php
include("connect.php");
include("header.php");
$sql_student = "SELECT * FROM student";
$result_student = mysql_query($sql_student);
?>
<form method="post" id="add_form" action="add_record.php">
<label>Name</label>
<input placeholder="Enter Student Name" type="text" name="name" id="name" class="form-control" />
<br />
<input placeholder="Enter Student ID" type="text" name="stud_id" id="stud_id" class="form-control" />
<br />
<?php
$sql_baggage = "SELECT * FROM baggage";
$result_baggage = mysql_query($sql_baggage);
?>
<label>Bag Types</label></br>
<table style="border:none;">
<?php while($row_bag = mysql_fetch_array($result_baggage))
{
$baggage_id = $row_bag['baggage_id'];
?>
<tr>
<td><?php echo $row_bag['baggage_id'];?>
<td><?php echo $row_bag['baggage_type'];?></td>
<td><input type="checkbox" name="tick[]" value="<?php echo $baggage_id;?>"/></td>
<td><input type="text" size="2" name="txt[<?php echo $baggage_id;?>]" placeholder=" "></td>
<?php
?></td></tr>
</table>
<br />
<input type="submit" name="submit" id="submit" value="Add Record" class="btn btn-success btn-secondary pull-right" />
</form>
<?php
if(isset($_POST['submit']))
{
$name = $_POST["name"];
$stud_id = $_POST["stud_id"];
$stu_query = "INSERT INTO student(student_id,student_name) VALUES ('$stud_id','$name')";
if(mysql_query($stu_query))
{
if(!empty($_POST['tick']))
{
foreach($_POST['tick'] as $selected)
{
$qty = $_POST['txt'][$selected];
$inv_query = "INSERT INTO inventory (invstu_id,invbag_id,invbag_quantity) VALUES
('$stud_id','$selected', '$qty')";
if(mysql_query($inv_query))
{
echo'<script>alert("A record has been inserted!")</script>';
}
else
{
echo "Database error";
}
}
}
else
{
echo'<script>alert("A record has been inserted!")</script>';
}
}
}
?>
</body>
</html>
I know that the data is passed through foreach function since I get the echo of database error two times when I tick two of the checkbox. However, the value is not inserted into the database.

Finally solve the issue by echoing the mysql_error(), there is nothing wrong with the code. Just a bit problem at the database. Thanks!!

Related

How to display certain row's data in a form after clicking edit? (PHP)

enter image description hereI'm new to PHP so please don't judge :D
I'm trying to make table with edit option. No matter in which row I click "Edit" button, only data from last row of the page gets loaded. What should I do?
$sql = "SELECT * FROM countries LIMIT " . $this_page_first_result . ',' . $results_per_page;
$result = $connection-> query($sql);
echo '<div style="text-align:center; font-weight: bold;">';
for ($page=1; $page<=$num_of_pages; $page++){
echo '' . $page . ' ';
}
echo '<div><br>';
if($result-> num_rows > 0){
while($row = mysqli_fetch_assoc($result)){
$id = $row['id'];
$Name = $row['Name'];
$Area = $row['Area'];
$Population = $row["Population"];
$Phone_code = $row["Phone_code"];
echo "<tr><td><a href='cities.php?id={$row['id']}'>".$row['Name']."</a></td><td>". $row["Area"] ."</td><td>"
. $row["Population"] ."</td><td>". $row["Phone_code"] ."</td><td><button id='update-button' onclick='openEdit()'>Update</button></td><td><button id='delete-button'>Delete</button></td></tr>";
}
print_r($row);
}
else{
echo "</table><h2 style='text-align:center'>There are no countries in the database..</h2>";
}
$connection-> close();
?>
</table>
<br>
<div style="text-align:center">
<button type="button" id="close-button-edit" onclick="closeEdit()" style="display:none">Close</button>
<div id="edit_form" style="display:none; text-align:left">
<form action="edit_country.php" method="POST" class="forms">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<p>Name: <input type="text" name="name" required value="<?php echo $Name; ?>"></p>
<p>Area: <input type="text" name="area" required value="<?php echo $Area; ?>"></p>
<p>Population: <input type="text" name="population" required value="<?php echo $Population; ?>"></p>
<p>Phone code: <input type="text" name="phone_code" required value="<?php echo $Phone_code; ?>"></p>
<input type="submit" name="update" value="Update">
</form>
</div>
There are two strategies that can be used for this problem: all php or using JavaScript.
PHP Only
This requires a submission to pre-fill the edit form. Each update button sends the id as a GET request (it is requesting information, not changing information, so use GET), in the form of an ordinary link, which the php script uses to populate the edit form.
<?php
// always start with php stuff and don't issue any html until you're done
// initialization
$sortDirection = 'asc';
if(isset($_REQUEST['sortDirection'])) {
// this decouples the value from user input. It can only be 'Asc' or 'Desc'
$sortDirection = $_REQUEST['sortDirection'] == 'asc' ? 'Asc' : 'desc';
}
$rowToEdit = '';
$pdo = new PDO( ... );
// Using PDO because it is more standard
// Leaving connection details to user. See https://phpdelusions.net/pdo_examples/connect_to_mysql for tutorial
// $pdo is assumed to be the pdo object
// deal with row delete. Destructive, so will be post, and delete button will be set
if(isset ($_POST['delete']) ) {
// delete from countries where id = ?
//redirect back to self (Post, Redirect, Get pattern).
// Always do this when done working with POST submissions!
header('Location: /countries.php');
exit;
}
// deal with row update. This changes data, so use POST
if(isset($_POST['id'])) {
// update countries set ...
// redirect back to self
header('Location: /countries.php');
exit;
}
// deal with request for row to edit, use GET for info requests
if(array_key_exists('id', $_GET) {
$rowToEdit = $pdo->prepare("select * from countries where id = ?");
$rowToEdit->execute([$id]);
// fall through to show page
}
// get all country rows (Note, OK to use $sortDirection here because it is decoupled from user input)
$country = $pdo->query("SELECT * FROM countries ORDER BY NAME $sortDirection")->fetchAll(PDO::FETCH_GROUP);
// got all our data, dealt with user input, now we can present the view
?>
<html>
<head>
</head>
<body>
<h1>Countries</h1>
Sort Asc
Sort Desc
<table>
<tr>
<th>Name</th>
<th>Area</th>
<th>Population</th>
<th>Phone</th>
<th></th>
<th></th>
</tr>
<?php foreach( $country as $row): ?>
<tr>
<td><a href='cities.php?country_id=<?=$row['id']?>'><?=$row['Name']?></a></td>
<td><?=$row["Area"]?></td>
<td><?=$row["Population"]?></td>
<td><?=$row["Phone_code"]?></td>
<td> <a href='countries.php?id=<?=$row['id']?>'>Update</a> </td>
<td>
<form method="post">
<input type="hidden" name="id" value="<?=$row['id']?>" />
<button id='delete-button'>Delete</button>
</form>
</td>
</tr>
</table>
<?php if($rowToEdit): ?>
<div style="text-align:center">
<form action="countries.php" method="POST" class="forms">
<input type="hidden" name="id" value="<?= rowToEdit ['id']?>">
<input type="hidden" name="sortDirection" value="<?= $sortDirection?>">
<p>Name: <input type="text" name="name" required value="<?= $rowToEdit['Name']?>"></p>
<p>Area: <input type="text" name="area" required value="<?= $rowToEdit['Area']?>"></p>
<p>Population: <input type="text" name="population" required value="<?= $rowToEdit["Population"]?>"></p>
<p>Phone code: <input type="text" name="phone_code" required value="<?= $rowToEdit["Phone_code"]?>"></p>
<input type="submit" name="update" value="Update">
</form>
</div>
<?php endif; ?>
</body>
</html>

when opening accordion, GET url by ID from that article

I want to display the article ID in my URL when i press the a href in code beneath
Update, i included the php section and the while loop with the article ID
require_once("inc/connection.php");
mysql_select_db("nieuws");
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$id = $_GET['id'];
$datum = $_POST["datum"];
$titel = $_POST["titel"];
$artikel = $_POST["artikel"];
$checkbox = $_POST["checkbox"];
$titel = mysql_real_escape_string(nl2br(htmlentities($_POST["titel"])));
$artikel = mysql_real_escape_string($_POST["artikel"]);
$id = mysql_real_escape_string($_POST['id']);
date_default_timezone_set('GMT');
$datum = date('Y-m-d', strtotime(str_replace('-', '/', $datum)));
if(isset($_POST['add'])){
if(!empty($_POST['titel']) && !empty($_POST['artikel']) && !empty($_POST['datum'])){
$query="INSERT INTO nieuws (id,datum,titel,artikel) VALUES ('$id','$datum','$titel','$artikel')";
$datum = date('Y-m-d', strtotime(str_replace('-', '/', $datum)));
str_replace('<br />', "\n", $textarea);
$result=mysql_query($query);
$juist1 = true;
}else{
$fout1 = true;
}
}if(isset($_POST['delete'])){
foreach($_POST['checkbox'] as $del_id){
$sql="DELETE FROM nieuws WHERE id='$del_id'";
$result = mysql_query($sql);
$juist2 = true;
}
}
}
This is the accordion script that opens on click
$('.acc_container').hide(); //Hide/close all containers
$('.acc_trigger').click(function(){
if( $(this).next().is(':hidden') ) { //If immediate next container is closed...
$('.acc_trigger').removeClass('active').next().slideUp();
$(this).toggleClass('active').next().slideDown();
}
return false;
});
});
This is the FORM part
<form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
<table style="width:950px; margin-bottom:5px;">
<tr>
<td>Datum:<br />
<input type="text" name="datum" size="20" style="width:100px;" value="<?php echo $datum; ?>" id="datepicker" placeholder="Kies datum"/><br /></td>
<td>Titel:<br />
<input type="text" name="titel" size="200" style="width:500px;" maxlength="45" value="<? php echo $titel; ?>" placeholder="Max. 50 characters toegelaten"/><br /></td> </tr>
</table>
Artikel: <br />
<textarea id="textarea" name="artikel" style="width:500px; height:150px;" value="<?php echo $artikel; ?>" ></textarea><br />
<input type="submit" name="add" value="Artikel toevoegen" />
</form>
This is the while loop where i ADD the row ID
$query="SELECT id,datum,titel,artikel FROM nieuws ORDER BY id DESC";
$result=mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo ("<div id=\"artikeltitel\" align=\"center\">
<div id=\"containerdatum\">".$row['datum']."</div>
<div id=\"containertitel\">".$row['titel']."</div>
<div id=\"container3\" style=\"font-size:12px;\">".$row['id']."
<input type=\"checkbox\" name=\"checkbox[]\" id=\"checkbox\" value=\"".$row['id']."\" />
</div>
</div>
<div class=\"container\" align=\"center\">
<h2 class=\"acc_trigger\"> » </h2>
<div class=\"acc_container\">
<div class=\"block\">".$row['artikel']."</div>
<div class=\"fb-comments\" data-href=\"http://www.zpb-polonez.be/user.php\" data-num- posts=\"10\" data-width=\"678\" style=\"margin-top:2px;\"></div>
</div>
</div>
");
}
I don't know what to add more to explain what i'm trying to achive
We lack some information here to be able to help but let's try anyway.
Let's assume that your article id is $row['id'] you could build your link this way:
echo 'Link';

assign data from one table to a specific table (group)

I have a classrooms in schools and when I click on a certain classroom, I want to add students into it but my actual code is doing something stupid. It adds a student but i can see the student in all classrooms, not just in the one that i added him into. So when Im in classroom number 1, I see a form in there, I can add a student there, ... see how it works here:
here is the code: http://www.xxxx.xx/projekt/
here is my code in file trieda.php
<table align="center"><tr><td>
<form action="vlozit2.php" method="post">
Meno: <input type="text" name="meno" placeholder="Janko" maxlength="15" required>
Priezvisko: <input type="text" name="priezvisko" placeholder="Hruška" maxlength="20" required>
<input type="hidden" name="id_triedy" value="<?= $trieda['id_triedy'] ?>" />
<input type="submit" name="submit" value="Pridať študenta do triedy">
</form>
</td></tr></table>
<?php
$result = mysqli_query($prip,"SELECT * FROM student ORDER BY meno");
while($student = mysqli_fetch_array($result))
{
echo "<br /><table cellspacing='1' cellpadding='1' class='tabulka1' align='center'><tr>";
echo "<td width='200'><a href='student.php?id_triedy=".$trieda['id_triedy']."".id_student=".$student['id_student']."'>".$student['meno']." ".$student['priezvisko']."</a></td>";
?>
<td width='300px' align='right' bgcolor="#fbfbfb">Zmazať</td>
</tr></table>
<?php
}
?>
here is vlozit2.php (a code that works for the form to add a student)
if(isset($_POST['submit']))
{
//meno a priezvisko
$student = $_POST['meno'];
$student = $_POST['priezvisko'];
$trieda = $_POST['id_triedy'];
//connect to the database
include 'config.php';
//insert results from the form input
$sql = "INSERT INTO student (meno, priezvisko, id_triedy) VALUES('$_POST[meno]', '$_POST[priezvisko]', '$_POST[id_triedy]')";
$add = "<table align='center'>
<tr>
<td> Študent bol úspešne pridaný do triedy. </td>
</tr>
<tr>
<td><a href='./trieda.php'><strong>Späť</strong></a></td>
</tr>
</table>";
$not_add = "<table align='center'>
<tr>
<td> Študent s týmto menom a priezviskom už je v tejto triede. </td>
</tr>
<tr>
<td><a href='./trieda.php'><strong>Späť</strong></a></td>
</tr>
</table>";
if (mysqli_query($prip, $sql)) {
echo $add;
}else{
echo $not_add;
}
mysqli_close($prip);
}
?>
Try to replace your part of code with these snipets:
1) in trieda.php
<form action="vlozit2.php?id_triedy=<?php echo $_GET["id_triedy"];?>" method="post">
Meno: <input type="text" name="meno" placeholder="Janko" maxlength="15" required>
Priezvisko: <input type="text" name="priezvisko" placeholder="Hruška" maxlength="20" required>
<input type="submit" name="submit" value="Pridať študenta do triedy">
</form>
2) in vlozit2.php
$student = $_POST['meno'];
$priezvisko = $_POST['priezvisko'];
$id_trieda = $_GET['id_triedy'];
and
$sql = "INSERT INTO student (meno, priezvisko, id_triedy) VALUES( '{$student}', '{$priezvisko}', {$id_trieda} )";
Hopefully you store your id_trieda as INT type.
In your vlozit2.php file is nothing about inserting of class id. So put
<input type="hidden" name="classId" value="<?= $trieda['id'] ?>" />
to your form and in vlozit2.php get this value from $_POST['classId'] and insert it with other students data or anywhere you want to have it.

How to add a delete button to a PHP form that will delete a row from a MySQL table

I have outputted the results of a MySQL table to an HTML table. In the last column, I want to add a delete option which calls another form and deletes the user from the MySQL table. I can't seem to get it to work though.
This is my code for the results page:
<?php
$contacts = mysql_query("
SELECT * FROM contacts ORDER BY ID ASC") or die( mysql_error() );
// If results
if( mysql_num_rows( $contacts ) > 0 )
?>
<table id="contact-list">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Telephone</th>
<th>Address</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php while( $contact = mysql_fetch_array( $contacts ) ) : ?>
<tr>
<td class="contact-name"><?php echo $contact['name']; ?></td>
<td class="contact-email"><?php echo $contact['email']; ?></td>
<td class="contact-telephone"><?php echo $contact['telephone']; ?></td>
<td class="contact-address"><?php echo $contact['address']; ?></td>
<td class="contact-delete"><form action='delete.php' method="post">
<input type="hidden" name="name" value="">
<input type="submit" name="submit" value="Delete">
</form></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
and, this is my delete.php script
<?php
//Define the query
$query = "DELETE FROM contacts WHERE name={$_POST['name']} LIMIT 1";
//sends the query to delete the entry
mysql_query ($query);
if (mysql_affected_rows() == 1) {
//if it updated
?>
<strong>Contact Has Been Deleted</strong><br /><br />
<?php
} else {
//if it failed
?>
<strong>Deletion Failed</strong><br /><br />
<?php
}
?>
I cannot figure out why this is not working.
You have to pass a variable in the delete link. You have to pass <?php echo $contact['name']; ?> (the name value) in a hidden field or pass this value in URL:
Replace
<td class="contact-delete">
<form action='delete.php' method="post">
<input type="hidden" name="name" value="">
<input type="submit" name="submit" value="Delete">
</form>
</td>
With
<td class="contact-delete">
<form action='delete.php?name="<?php echo $contact['name']; ?>"' method="post">
<input type="hidden" name="name" value="<?php echo $contact['name']; ?>">
<input type="submit" name="submit" value="Delete">
</form>
</td>
USe javascript
<input name="Submit2" type="button" class="button" onclick="javascript:location.href='delete.php?id=<?php echo $your_id;?>';" value="« Back" />
and in delet.php
$id=$_GET['id'];
and put $id in your sql statement.
You are missing to pass name in this line:
<input type="hidden" name="name" value="">
You need to have something (<?php echo $contact['name']; ?>) in the value attribute.
BTW, do not use deprecated mysql_* functions, use PDO or mysqli_* instead.
<input type="hidden" name="name" value="">
You are missing a value which wil be picked up by this line in your delete file.
$query = "DELETE FROM contacts WHERE name={$_POST['name']} LIMIT 1";
Right now it isn't receiving anything, which is why it will not work.
So add a value to it and it will work. Example:
<input type="hidden" name="name" value="<?php echo $contact['name']; ?>">
First, you should not write the code in that way; the code has no protection against SQL injection.
1. Try to use primary IDs instead of using a name (what happens if 2 people has the same name?).
So, you can create a hidden field to know which 'person' you are dealing with.
<input type="hidden" name="contact_id" value="<?php $contact['contact_id']; ?>">
2. Sanitize variables to avoid attacks:
<?php $contact_id = isset($_POST['contact_id'])?intval($_POST['contact_id']):0;
// proceed with the query
if($contact_id>0) { $query = "DELETE FROM contacts WHERE contact_id = '$contact_id'";
}
// redirect to the main table with header("location: main.php");
?>

How to send multiple row value submit button?

I get the values from same row, but many values with fetch array. I did it, but with buttons, as many as how many values there are. If I have 5 rows, then I should have five submits, but I want one submit button.
Here is my code:
$result2 = mysql_query ("select * from price where dom='$cat'",$db);
$myrow2= mysql_fetch_array($result2);
<form action="priceupdatetes.php" method="post">
<?php
do {
echo <<<here
<td><input name="etiket[$myrow2[id]]" type="text" value="$myrow2[etiket]"/></td>
<td><input name="pricestandart[$myrow2[id]]" type="text" value="$myrow2[pricestandart]"/></td>
<td><input name="number[$myrow2[id]]" type="text" value="$myrow2[number]"/></td>
<td><input name="totalunper[$myrow2[id]]" type="text" value="$myrow2[totalunper]" disabled="disabled"/></td>
<td><input name="discount[$myrow2[id]]" type="text" value="$myrow2[discount]"/></td>
<td><input name="totalwithper[$myrow2[id]]" type="text" value="$myrow2[totalwithper]" disabled="disabled"/></td>
</tr>
here;
}
while($myrow2= mysql_fetch_array($result2)) ;
?>
<input NAME="id[]" TYPE=hidden value="<?php foreach($myrow2[id] as $mid) {print $mid;} ?> "/>
<input name="submit" type="submit" value="Submit"/><br>
</form>
HERE is UPDATEPAGE.php:
if (isset($_POST['etiket'])) {$etiket = $_POST['etiket']; }
if (isset($_POST['pricestandart'])) {$pricestandart = $_POST['pricestandart'];}
if (isset($_POST['number'])) {$number = $_POST['number']; }
if (isset($_POST['discount'])) {$discount = $_POST['discount']; }
if (isset($_POST['id'])) {$id = $_POST['id']; }
$totalunper=$pricestandart*$number;
$percent=$discount/100;
$totalwithper1=$totalunper*$percent;
$totalwithper=$totalunper-$totalwithper1;
foreach($id as $team_id)
{
$result = mysql_query("UPDATE price SET etiket='$etiket[$team_id]',pricestandart='$pricestandart[$team_id]',number='$number[$team_id]',totalunper='$totalunper[$team_id]',discount='$discount[$team_id]',totalwithper='$totalwithper[$team_id]' WHERE id='$team_id'"); }
How can I get values with different id's and update them?
<input NAME="id[]" TYPE=hidden value="<?php foreach($myrow2[id] as $mid) {print $mid;} ?> "/>
is wrong. $myrow2[id] is not an array. Inside your while-loop, you should add:
<input NAME="id[]" TYPE="hidden" value="$myrow2[id]"/>

Categories