Dear Stack Overflow members,
I’m trying to create a form for school awards where a user will select a class (level) and submit. The awards for that class (there can be many awards) will display in a table with a dropdown of a list of students in that class beside each award.
The user will then select a student from the dropdown beside each award and submit again which will save the records in a table.
It is working fine except the last part where the students and the awards are not being saved. Not sure if the issue is with one isset within another isset is causing the issue.
<?php
if(isset($_POST['submit'])) {
include 'db_connect.php';
$level = $_POST['level'];
$query = mysqli_query($conn, "SELECT a.awardcode, a.level, b.awardname, a.year FROM awardyrlevel AS a
INNER JOIN award AS b
ON a.awardcode = b.awardcode
WHERE a.level = '$level' AND a.year = year(curdate())");
?>
<table border="1" style= "background-color: white; color: #761a9b; <!--margin: 0 auto-->;" >
<thead>
<tr>
<th>Award Code</th>
<th>Award Name</th>
<th>Year Level</th>
<th>Select Student</th>
</tr>
</thead>
<tbody>
<?php
while( $row = mysqli_fetch_assoc( $query ) ){
?>
<tr>
<td> <input type = "text" name="awardcode[]" value = "<?php echo $row['awardcode']; ?>" readonly /> </td>
<td><?php echo "{$row['awardname']}" ?> </td>
<td><?php echo "{$row['level']}" ?></td>
<td><select name="studcode[]" >
<option disabled selected value> -- Select Student -- </option>
<?php
$sql = mysqli_query($conn, "SELECT * FROM student where year_level = '$level'");
while ($row = mysqli_fetch_assoc($sql)){
echo '<option value = " '.$row['stud_code'].'"> '.$row['name'].' </option>';
}
?>
</select>
</td>
</tr>\n;
<?php } ?>
</tbody>
</table>
<br><br>
<input id="save_button" type="submit" name="saveselection" value="Save Selection">
<input id="exit_button" type="submit" name="exit" value="Exit" onclick="window.history.go(-1); return false;">
<?php
if(isset($_POST['saveselection'])) {
$awardcode = $_POST['awardcode'];
$studcode = $_POST['studcode'];
$level = $row['level'];
$year = year(curdate());
$session_user = '2365';
echo $awardcode;
foreach ($_POST['awardcode'] as $awardcode) {
$query = mysqli_query($conn, "INSERT INTO `awardwinner`(`awardcode`, `stud_code`, `level`, `year`, `doe`, `enteredby`)
VALUES ('$awardcode', '$studcode', '$level', '$year', now(), '$session_user')");
}
}
}
?>
The code I have written is simple with html and php. I tried to debug this for quite sometime. Can any of you please suggest what is wrong with this that the records cant be saved?
There are a couple of things wrong with this code, including not keeping to standards of PHP programming. Keep your issets at the top of the page, don't litter them throughout, it makes things difficult to track.
You have an input with the name listed as an array... why? You're not submitting multiple values here. Perhaps you mean to use it as a checkbox/radio? Otherwise it's not needed.
Then in your final query, you're actually using ` for a number of them, instead of ' . That's a ` which should be under your esc key, instead of an apostrophe (')
Also just as a preference, I tend to write for readability rather than raw efficiency when working with a few people, so I personally would write:
$query = "WHATEVER MY QUERY IS";
$get_thing_query = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($get_thing_query)){
//Do your stuff, if you're not expecting multiple rows don't use while.
}
Related
I want to create time table. Need to get subject names from database in check boxes and teachers name from database in select dropdown. I am using following code but it give me only single row. I don't know where I am doing mistake.
<table width="100%">
<tr>
<th>Select Subject</th>
<th>Period Time</th>
<th>Teacher</th>
</tr>
<?php
$query = mysqli_query($conn, "select * from subjects");
while ($row = mysqli_fetch_array($query))
{
$subject_id = $row['subject_id'];
$subject_name = $row['subject_name'];
echo "<tr>
<td><input type='checkbox' name='subject_id' value='$subject_id'> $subject_name</td>
<td>
<div class='form-group'>
<select name='class_time' class='form-control'>
<option>10:00</option>
<option>11:00</option>
<option>12:00</option>
<option>01:00</option>
</select>
</div>
</td>
<td>
<div class='form-group'>
<select name='employee_id' class='form-control'>";
$query = mysqli_query($conn, "select * from employees where designation = 'Teacher' OR designation = 'Principal'");
while ($row = mysqli_fetch_array($query))
{
$employee_id = $row['employee_id'];
$employee_name = $row['employee_name'];
echo "
<option>$employee_name</option>";
}
echo "</select></div>
</td>
</tr>";
}
?>
</table>
The problem you have is that you use the same variable name $query for both queries, and so the second one overwrites the first one. Try using $empQuery or something else for the second one.. (same for $row -> $empRow)
Here Is my problem: I do not get any error with my code but my problem is when i click the 'Delete Multiple' Button it does nothing not even reload the page.
Note: By The Way the redirect_to(); function i created so do not get confused by thinking that is a php function or anything
PHP Code:
display_errors(E_ALL);
if(isset($_POST['muldelete'])) {
$mul = $_POST['checkdelete'];
$sql = "DELETE FROM cmarkers WHERE id = " . $mul;
$result = mysqli_query($db, $sql);
redirect_to("elerts.php");
}
HTML Code:
<form action="elerts.php" method="post">
<table class="table table-striped">
<tr>
<td> </td>
<td>Date</td>
<td>Comment</td>
<td>Actions</td>
</tr>
<?php
$sql = "SELECT * FROM cmarkers";
$result = $db->query($sql);
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><input type="checkbox" name="checkdelete[]" value="<?php echo $row['id']; ?>" /></td>
<td><?php echo $row['date']; ?></td>
<td><?php echo $row['comment']; ?></td>
<td>DeleteEdit</td>
</tr>
<?php
}
?>
<input type="submit" name="muldelete" value="Delete Multiple" />
</table>
</form>
Thank You
If you need more info please let me know
First, your code contain some attention and placements errors.
input between <table> outer of td's is incorrect.
You can't make a multiple delete if you generate one form by value to
delete.
Fix them.
Getting Array of muldelete
To all the checked inputs, you must add the array field symbol
to clusterize the name "muldelete" to a post array.
<td><input type="checkbox" name="checkdelete[]" value="<?php $row['id']; ?>" /></td>
PHP side
Now you can fetch whole deletion array, like this:
if(!empty($_POST["muldelete"]))
{
$mul = join(',', $_POST['checkdelete']);
// Using IN() to make only one query for all records instead of multiple
// ex: IN(3, 4, 54, 8)
$query = "DELETE FROM cmarkers WHERE id IN(".$mul.")";
$result = mysqli_query($db, $query);
redirect_to("elerts.php");
}
Security
If ID's are integer value, you can prevent string injection into the sql query
$mul = array_map(function($id)
{
return intval($id);
}, $mul);
Your button is outside the <form></form> tags, so it is not related to the form elements or the form method at all. Instead of having a different form for each checkbox you should surround the entire table with the form tags thus ensuring that all the checkboxes and the button are in the same form.
<form method='post' action='elerts.php'>
<table class="table table-striped">
...all your table data including checkboxes...
<input type="submit" name="muldelete" value="Delete Multiple" />
</table>
</form>
I think because You are closing form tag earlier than submit button.
Try to put whole table into and should work.
PHP should looks like
display_errors(E_ALL);
if(isset($_POST['muldelete'])) {
$mul = implode(',',$_POST['checkdelete']);
$sql = "DELETE FROM cmarkers WHERE id IN(" . $mul.")";
$result = mysqli_query($db, $sql);
redirect_to("elerts.php");
}
I have a question for using the mysql_insert_id function when I want to insert new data from html form into multiple tables?
The form I'm using is this:
<form method="POST" action="insert.php">
<table>
<tr>
<td>Room</td>
<td>
<select name="room">
<?php
openDB();
$sql = "SELECT room_id, name FROM room";
$rs = executeDB($sql);
while(list($room_id, $name) = mysql_fetch_array($rs)) {
echo "<option value='$room_id'>$name</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td>Product</td>
<td>
<select name="product">
<?php
openDB();
$sql = "SELECT product_id, name FROM product";
$rs = executeDB($sql);
while(list($product_id, $name) = mysql_fetch_array($rs)) {
echo "<option value='$product_id'>$name</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td>Quantity</td>
<td>
<?php
openDB();
$sql = "SELECT quantity FROM items_order";
$rs = executeDB($sql);
while(list($quantity ) = mysql_fetch_array($rs)) {
echo " <input type='number' name='quantity []' min='1' max='4'/></td>";
}
?>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form>
Then to enter those variables :
if(isset($_POST['user'])) {
$user= $_POST['user'];
$room_id = $_POST['room_id'];
$product_id = $_POST['product_id'];
$quantity= $_POST['quantity'];
$status = 0; // if it's payed or not, if it is status= 1 else status = 0
Here is the code:
$sql = "INSERT INTO order (status, room_id, user_id) VALUES ('$status','$room_id','$user_id')";
$rs = mysql_query($sql);
$newid = mysql_insert_id();
$sql2 ="INSERT INTO items_order VALUES ('$newid ','$product_id','$quantity')";
$rs = mysql_query($sql2);
and it doesn't work.
The tables I have are; order , items_order, product, the order has order_id primary key as auto increment,
the items_order has two primary keys: order_id,
and product_id as they are foreign keys, room has room_id, and the product has product_id,
the foreign keys in order table are user_id, room_id, for.
Do i have to use that function to enter new data or not?
And most importantly what am I doing wrong that this code doesn't work?
Please help.
I'm pretty sure PHP doesn't use string interpolation, so the strings you see in the program code are actually what it tries to give to MySQL. Obviously that wouldn't work.
The correct way to do this is to use prepared queries where you can substitute the parameters in a safe manner. What you are doing is just an invitation for an SQL injection attack. Of course, the old MySQL extension for PHP doesn't support those, which is why it is deprecated and slated to be removed soon. So you shouldn't use it.
Follow this link and its instructions and learn about the right way to access MySQL in PHP:
http://us3.php.net/manual/en/mysqlinfo.api.choosing.php
My main issue that I am running into is basically this:
I have a while loop that generates results from a query. With the results that have been generated, I want the ability to update the table the original query was from.
The query produces the expected results, but the table is not being updated when I click the REMOVE button. I am also trying to find a solution for the results to be updated after the UPDATE query executes...
<?php
$sql = "SELECT * FROM vehicles WHERE sold='n' ORDER BY year DESC";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
echo
"
<tr>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['year'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['make'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['model'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'><input type='submit' name='remove' value='REMOVE' style='background-color:#C33;color:white;padding:10px;border-radius:5px;width:70px'/></td>
</tr>";
if(isset($_POST['remove'])){
$removeSql = "UPDATE `table`.`vehicles` SET `display`='0' WHERE `vin`='{$row['vin']}'";
mysql_query($removeSql) or die('check that code dummy');
}
}
mysql_close($connection);
?>
That's a submit button, will not work without form tag. You can't do it this way.
You can write the remove code on a separate page and convert that submit button to normal button and pass vin id on click of that button and call that page using ajax.
Or if you don't know ajax and want to do it on that page itself then do it this way :
<?php
$sql = "SELECT * FROM vehicles WHERE sold='n' ORDER BY year DESC";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
echo
"
<tr>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['year'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['make'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['model'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>
<form action="" method="POST">
<input type="hidden" name="vin_id" value="<?php echo $row['vin']; ?>">
<input type='submit' name='remove' value='REMOVE' style='background-color:#C33;color:white;padding:10px;border-radius:5px;width:70px'/>
</form></td>
</tr>";
}
if(isset($_POST['remove'])){
$removeSql = "UPDATE `table`.`vehicles` SET `display`='0' WHERE `vin`='".$_POST['vin_id']."'";
mysql_query($removeSql) or die('check that code dummy');
}
mysql_close($connection);
?>
my current problem is :
I have a HTML table created "dynamically" according to how many rows brings back a mysql_query. The first column gets tha data from the query and the second column have a text field (see below):
<?php
$selApart = "SELECT idAPARTMENT FROM BUILDING, APARTMENT WHERE APARTMENT.BUILDING_ID = BUILDING.idBUILDING AND idBUILDING = '$building'";
$res = mysql_query($selApart) or die("Could not execute query.");
?>
<table width="244" border="0" cellspacing="0" id="hours_table">
<tr>
<td width="121">APARTMENT</td>
<td width="119">HOURS</td>
</tr>
<?php
$rcnt = 0;
while($r = mysql_fetch_array($res)){
$a = $r['idAPARTMENT'];
$rcnt++;
$rid = 'row'.$rcnt;
?>
<tr>
<td>'<?php echo $a?>'</td>
<td id='<?php echo $rid?>'><input type="text" name="hours" id="hours" value="0"/></td>
</tr>
<?php } ?>
<input type="submit" name="complete" id="complete" align="middle" value="INSERT"/>
After my table is "ready", I want to fill in my text fields and insert these values in an sql table. What I don't know is how I can get the value of each column through the id I set, sth like
if(isset($_POST['complete'])){
for($i=0; $i<$rcnt; $i++){
//INSERT INTO APARTMENT (idAPARTMENT, HOURS) VALUES ($a, **table.row.id**)
}
}
Can someone help? Is this possible to be done?
Thanks in advance!
He, thing you have to do is add $rid as name to text box, then just submit form and you will have them in $_POST["row"+$rid];
You can loop through every $_POST and if variable starts with row + num save it in db
foreach($_POST as $key => $value)
//if $key starts with row execute your db save
I hope this helps
Put that table into a form with method=POST and when submitting you'll find all input's in the $_POST array by name.
<?php
print_r($_POST);//this will just show you the contents of the array, you play with it later on
$selApart = "SELECT idAPARTMENT FROM BUILDING, APARTMENT WHERE APARTMENT.BUILDING_ID = BUILDING.idBUILDING AND idBUILDING = '$building'";
$res = mysql_query($selApart) or die("Could not execute query.");
?>
<form action="" method="POST"><!-- table must be included in a form with action pointing the script location, "" means itself -->
<table width="244" border="0" cellspacing="0" id="hours_table">
<tr>
<td width="121">APARTMENT</td>
<td width="119">HOURS</td>
</tr>
<?php
$rcnt = 0;
while($r = mysql_fetch_array($res)){
$a = $r['idAPARTMENT'];
$rcnt++;
$rid = 'row'.$rcnt;
?>
<tr>
<td>'<?php echo $a?>'</td>
<td id='<?php echo $rid?>'><input type="text" name="hours<?= $a ?>" id="hours" value="0"/></td><!-- name="hourse<?= $a ?>" each name must be unique, that's why you include the ID from your table. It's not a good idea to put a counter, use actual data from the table. -->
</tr>
<?php } ?>
</table>
<input type="submit" name="complete" id="complete" align="middle" value="INSERT"/>
</form>
The post "get data from dynamically created html table for certain columns" was very useful. It helped me a lot, but needs a little change:
<?php
//database connectivity
mysql_connect ("localhost","root","","sis")or die("cannot connect");
mysql_select_db("sis")or die("cannot select DB");
//query to fetch data
$sql1="select * from student";
$result1= mysql_query($sql1);
// forming table to view data
if($result1){
echo "<table cellspacing='1' cellpadding='5'>
<th width='30%'>Roll_No </th>
<th width='40%'>Name </th>
<th width='30%'>Sem & Sec </th>";
while($row=mysql_fetch_array($result1)){
$Roll_No=$row['Roll_No'];
$Name=$row['Name'];
$Sem_Sec=$row['Sem_Sec'];
echo"<tr>
<td>$Roll_No</td>
<td>$Name</td>
<td>$Sem_Sec</td>
</tr>";
}
?>