I have read articles and questions regarding this issue but I'm still finding it difficult to go about it.
I'm trying to achieve course registration. So I have this table populated from my db.
<form method="post" action="courses.php">
<table>
<thead>
<th>Action<th>
<th>Course Title<th>
<th>Course Code<th>
<th>Course Unit<th>
</thead>
<tbody>
<!--Query that fetches the data from the db (included dbcon.php).. the courses are created by admin-->
<tr>
<td><input type="checkbox" name="isChecked[]" value="<?php echo $course_id?>"></td>
<td><input type="hidden" name="ctitle[]" value="<?php echo $title?>"> <?php echo $title?></td>
<td><input type="hidden" name="ccode[]" value="<?php echo $code?>"> <?php echo $code?></td>
<td><input type="hidden" name="cunit[]" value="<?php echo $unit?>"> <?php echo $unit?></td>
</tr>
</tbody>
</table>
<input type="submit" name="enroll">
</form>
If a checkbox is checked, How can I get all the values of the array (title, code, unit) and insert them on its corresponding column in my enroll table also note that the courses are more than 1?
here is the little I have done but I'm beginning to think that I'm not going to go through with it (imaging creating another foreach of the array? initializing a counter foreach??)
<?php
if(isset($_POST['enroll'])){
$i=0;
if(!empty ($_POST['isChecked'])){
foreach($_POST['isChecked'] as $course){
$course = $_POST['isChecked'][$i];
$query = "INSERT INTO enrolled (course_id)
VALUES ('$course')";
$insert = $db->query($query);
$i++;
}
}?>
The above insert the course id to my DB quite fine. But what I want is to actually insert all the data i.e (id, title, code, and unit to the database )
That is because your code is wrong. Try this:
<tr>
<td><input type="checkbox" name="isChecked['course_id']" value="<?php echo $course_id?>"></td>
<td><input type="hidden" name="isChecked['title']" value="<?php echo $title?>"> <?php echo $title?></td>
<td><input type="hidden" name="isChecked['code']" value="<?php echo $code?>"> <?php echo $code?></td>
<td><input type="hidden" name="isChecked['unit']" value="<?php echo $unit?>"> <?php echo $unit?></td>
</tr>
Do not forget to BIND your values and check them before to execute your SQL code.
Related
I'm trying make a form where me or user can insert data. Some parts are coming form data base like: Work name and work price. In input fields can insert work amount. In each input row have checkbox, if checkbox ar checked, that row will be seen in php.
<table class="table">
<thead>
<tr>
<th scope="col">*</th>
<th scope="col">Work name</th>
<th scope="col">Quantity</th>
<th scope="col">Price for unit</th>
<th scope="col">Total price</th>
</tr>
</thead>
<form method="POST" action="process/pdf.process.php">
<tbody>
<?php
$works = ORM::for_table('work')->find_many();
foreach($works as $work){
?>
<tr id="<?php echo $work->id; ?>">
<td><input type="checkbox" name="useit[]" value="<?php echo $work->id; ?>"/></td>
<td><?php echo $work->name; ?></td>
<td><input type="text" placeholder="" class="amount"/> <?php echo $work->unit; ?></td>
<td class="work_price" data="<?php echo $work->price; ?>"><?php echo $work->price.'€/'.$work->unit; ?></td>
<td class="total_price">0€</td>
<input type="" name="work_id[]" value="<?php echo $work->id; ?>" />
<input type="hidden" name="work_name[]" value="<?php echo $work->name; ?>" />
<input type="hidden" name="amount[]" class="<?php echo $work->id; ?>_copy_amount" value="" />
<input type="hidden" name="unit[]" value="<?php echo $work->unit; ?>" />
<input type="hidden" name="unit_price[]" value="<?php echo $work->price; ?>€" />
<input type="hidden" name="unit_total[]" class="<?php echo $work->id; ?>_copy_total" value="" />
</tr>
<?php
}
?>
</tbody>
<input type="submit" name="do_pdf" value="Pga jkāuztaisa ar jquery" />
</form>
</table>
Now, there is php, but how can i show only checked rows in while loop?
<?php
$data = array();
$work_id = array();
$work_names = $_POST['work_name'];
$amounts = $_POST['amount'];
$units = $_POST['unit'];
$units_prices = $_POST['unit_price'];
$units_total = $_POST['unit_total'];
if(isset($_POST['useit'])){
$work_id = $_POST['useit'];
}
$data = array($work_id, $work_names, $amounts, $units, $units_prices, $units_total);
echo '<pre>';
echo htmlspecialchars(print_r($data, true));
echo '</pre>';
?>
There are different possibilities how to do that. One Suggestion (i limit it to the parts which are relevant)
form (note that i gave work_name the id as an index, use_it not (but it could have)
<td><input type="checkbox" name="useit[]" value="<?php echo $work->id; ?>"/></td>
<input type="hidden" name="work_name[<?php echo $work->id?>]" value="<?php echo $work->name; ?>" />
The form only submits the checked checkboxes values in an array, all other are omited. Therefore we could loop over the checked checkbox values like this
foreach($_POST['useit'] as $work_id){
$work_name = $work_names[$work_id];
//do something with the checked rows only (all others are not looped over)
}
This is only possible, due to the given id as an array key in the form work_name[<?php echo $work->id?>].
A general sidenote for better (and more secure) code: please note that your data could be modified by the user, and send back with wrong data (or worse). So please make sure to sanitize your input, or probably better in this case only submit the id in question and the new data and pickup the rest directly from your database. So you can make sure the hidden data has not been modified on the client side and send back wrong.
I'm new to php programming. I'm kind of confused and I can't find any helpful information online. I'm trying to build a school manangement system from scratch. What I need is to get all the 'offered courses' from the database and put it in a form and allow the student to add the classes directly from the row. How can I do that?
I created a form and an input where the student might enter the course number and register for class. And it works fine. But I feel like it's not practical.
Here is my code
<?php
session_start();
// include("config.php");
include("functions.php");
// $sql="SELECT `course_num`, `professors`.`name` AS pName, `courses`.`name`AS cName , max_students FROM `courses`, `student_courses`,`professors` WHERE `professors`.`id`=`courses`.`professor_teaching` AND `student_id`= '".$_SESSION['student_id']."'";
// $result = mysqli_query($link, $sql);
$result = viewAllCourses();
?>
<form method="post" action="functions.php">
<table>
<tr>
<th><label>Course No.</label></th>
<th><label>Course Name</label></th>
<th><label>Professor</label></th>
<th><label>Max. Students</label></th>
<th><label>Action</label></th>
</tr>
<?php
if(mysqli_num_rows($result)){
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><label name="course_num"><?php echo $row['course_num'];?>
<input type="hidden" name ="coursenumber" value=<?php $row['course_num']?>>
</label></td>
<td><label><?php echo $row['cName'];?></label>
</td>
<td><label><?php echo $row['pName']; ?></label></td>
<td><label><?php echo $row['max_students']; ?></label></td>
<td><input type="submit" name="add" value="add"></td>
</tr>
</form>
</table>
<?php
}
}
?>
and then in the functions.php I have this code:
if (isset($_GET['add'])) {
$link = conn();
echo "TST";
exit;
$courseNum= $_POST['coursenumber'];
$record = mysqli_query($link, "INSERT INTO `student_courses`
(`student_id`, `course_id_num`)
VALUES ('".$_SESSION['student_id']."', '$courseNum')");
}
But it does nothing.
I tried adding an input tag for the course_number and passing it from there. But it doesn't work. What is the right way to do this?
You're the same names for the inputs in all the rows. When you submit the form, $_POST['coursenumber'] will just be the last course number in the table, not the one the user clicked on. You can put the course number in the value of the add button, rather than a hidden input. When a form has multiple submit buttons, the value comes from the one that was clicked.
You need to fix the order of the </form> and </table> tags, so they nest properly.
<?php
if(mysqli_num_rows($result)){
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><label name="course_num"><?php echo $row['course_num'];?>
</label></td>
<td><label><?php echo $row['cName'];?></label>
</td>
<td><label><?php echo $row['pName']; ?></label></td>
<td><label><?php echo $row['max_students']; ?></label></td>
<td><input type="submit" name="add" value="<?php echo $row['course_num'];?>"></td>
</tr>
</table>
</form>
<?php
}
}
?>
Also, since you're submitting the form with method="POST", the button will be $_POST['add'], not $_GET['add'].
You should use a prepared statement to protect against SQL-injection.
if (isset($_POST['add'])) {
$link = conn();
$courseNum= $_POST['add'];
$stmt = mysqli_prepare("INSERT INTO student_courses (student_id, course_id_num) VALUES (?, ?)");
mysqli_stmt_bind_param($stmt, "ii", $_SESSION['student_id'], $courseNum);
mysqli_stmt_execute($stmt);
}
If you want to pass multiple fields, you can put a separate form with multiple hidden inputs into each row, rather than making the whole table a form.
<?php
if(mysqli_num_rows($result)){
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><label name="course_num"><?php echo $row['course_num'];?>
</label></td>
<td><label><?php echo $row['cName'];?></label>
</td>
<td><label><?php echo $row['pName']; ?></label></td>
<td><label><?php echo $row['max_students']; ?></label></td>
<td><form action="functions.php" method="post">
<input type="hidden" name="coursenumber" value="<?php echo $row['course_num'];?>">
<niput type="hidden" name="something" value="<?php echo $row['something'];?>">
<input type="submit" name="add" value="add">
</form></td>
</tr>
</table>
<?php
}
}
?>
Then the functions.php script can use $_POST['course_num'] and $_POST['something'] to get these parameters.
I'm trying to create a students attendance system and when I'm attempting to store information to the database, I'm getting various errors about the attendance status. I'm aware this isn't a typical problem for all but it would help a beginner of PHP.
<form action="tutor_attendance.php" method="post">
<table class="table table-striped">
<tr>
<th>Student ID</th> <th>Module Name</th> <th>Attendance Status </th>
</tr>
<?php $result=mysqli_query($conn, "SELECT * FROM student");
// $serialnumber=0;
$counter=0;
while($row=mysqli_fetch_array($result))
{
?>
<tr>
<td> <?php echo $row['stud_id']; ?> </td>
<input type="hidden" value="<?php echo $row['stud_id']; ?>" name="stud_id[]" >
<td> <?php echo $row['module_1']; ?> </td>
<input type="hidden" value="<?php echo $row['module_1']; ?>" name="module_1[]">
<td>
<input type="radio" name="attendance_status[<?php echo $counter; ?>]" value="Present">Present
<input type="radio" name="attendance_status[<?php echo $counter; ?>]" value="Absent">Absent
<input type="radio" name="attendance_status[<?php echo $counter; ?>]" value="Late">Late
</td>
</tr>
<?php
$counter++;
}
?>
</table>
<input type="submit" name="submit" class="btn btn-primary " value="submit" >
</form>
The code above is the form that I'm using to present data from the database and then capture their attendance with a radio button.
if(isset($_POST['submit']))
{
foreach($_POST['attendance_status'] as $id->$attendance_status)
{
$stud_id=$_POST['stud_id'][$id];
$module_1=$_POST['module_name'][$id];
$date=date("Y-m-d H:i:s");
mysqli_query($conn, "INSERT into attedance('stud_id, module_name, attendance_status, date) VALUES('$stud_id', '$module_1','$attendance_status','$date')");
}
}
Then the code above this is once the submit button has been pressed. The errors that I'm getting are: Undefined variable: attendance_status and Creating default object from empty value. Any help would be appreciated. The errors are occurring on line 8 - foreach($_POST['attendance_status'] as $id->$attendance_status)
I see a few different problems but the error you are getting is due to improper foreach syntax, which should be key => value not key->value
foreach($_POST['attendance_status'] as $id => $attendance_status) {
}
The errant quote in your SQL is not causing this error, but it is certainly another error. See this line:
"INSERT into attedance('stud_id, module_name, ...
Also did you really typo your table name for attendance? My guess is that it should be:
"INSERT into attendance(stud_id, module_name, ...
I am try to inset multiple rows to new table fetched from other table, but problem is that only last single row is being inserted and no other now is getting insert, so please tell the issue where i am lacking
<?php
error_reporting(1);
session_start();
$s=$_SESSION['username'];
//connect database
$con=mysql_connect("localhost","root","") or die(mysql_error());
// select database
mysql_select_db("education",$con);
$date= date("Y/m/d");
//select all values from empInfo table
$data="SELECT * FROM student";
$val=mysql_query($data);
?>
<html>
<body>
<table>
</table>
<form action="submit.php" method="post" >
<table>
<tr>
<th>Teacher name</th>
<th>Date</th>
<th>Roll No</th>
<th>Student name</th>
<th>Father name</th>
<th>Addhaar No</th>
<th>Status(P)</th>
<th>Status(A)</th>
<th>Status(L)</th>
</tr>
<?php while($r=mysql_fetch_array($val))
{?>
<tr style="border:2px solid black;">
<td><input type="text" name="teacher" value="
<?php echo $s; ?>"></td>
<td><input type="text" name="date" value="
<?php echo $date; ?>"></td>
<td ><input name="roll_no" value="
<?php echo $r['roll_no']; ?>">
</td>
<td><input name="student_name" value="
<?php echo $r['student_name'] ?>">
</td>
<td><input name="father_name" value="
<?php echo $r['father_name'] ?>">
</td>
<td>
<input name="addhaar_no" value="
<?php echo $r['addhaar_no'] ?>">
</td>
<td>
<input type="checkbox" value="present" name="status"> Present
</td>
<td>
<input type="checkbox" name="status" value="absent">Absent
</td>
<td>
<input type="checkbox" name="status" value="leave">Leave
</td>
</tr>
</table>
<?
}
?>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
submit.php -
<?php
error_reporting(1);
$con=mysql_connect("localhost","root","") or die(mysql_error());
// select database
mysql_select_db("education",$con);
//get data from html form
$roll_no=$_POST['roll_no'];
$student_name=$_POST['student_name'];
$father_name=$_POST['father_name'];
$addhaar_no=$_POST['addhaar_no'];
$status=$_POST['status'];
//Insert values in empInfo table with column name
$query="INSERT INTO attandance
VALUES ('', '$roll_no','$student_name','$father_name','$addhaar_no','$status'),
VALUES ('', '$roll_no','$student_name','$father_name','$addhaar_no','$status')";
echo $query;
die();
mysql_query($query);
?>
page
You need to have unique name for each fields. What you can do is have a counter in loop and add it the names of the fields to make it unique.
Sample:
$ctr = 0;
while($r=mysql_fetch_array($val)){
echo "<input type="text" name='teacher_".$ctr."'>";
$ctr++;
}
Or make the names array, and loop through the values in saving the data.
while($r=mysql_fetch_array($val)){
echo "<input type="text" name='teacher[]'>";
}
I think you should study PHP a bit more... As i can see in your code, you haven't understood fundamentals of PHP.
1: Normally, you won't mix up HTML and PHP like you did in your first code. Its just confusing and really annoying to read the code later.
2: When you post your form, for example the variable $_POST['student_name']; will just contain the value of the last row (your problem). So, why? Because you can't assign more than one value to a variable. Or at least, not the way you tried it. Array would be a good keywoard for this problem.
3: Please check your SQL syntax... Thats why i'm saying you haven't understand fundamentals... http://www.w3schools.com/sql/sql_insert.asp
Why you're repeating your values? You think the second time the variables will contain the values of the next row? Thats just false. A Variable contains everytime the same value, as long as you don't assign a new value to it.
4: mysql is depracted. Use mysqli or PDO instead.
My tip: You need to have unique input names. Just take a look at PHP, how for/while loops work, study a bit more and try it again. It's not difficult to solve, but i think you'll learn a lot more if we don't give you the direct solution.
Now mysql is depracted. So, you can use mysqli or PDO instead.
I can use now PDO. Please follow bellow code carefully:
<?php
$user = 'root';
$pass = '';
$dbh = new PDO('mysql:host=localhost;dbname=education', $user, $pass);
try {
$select = $dbh->query('SELECT * from student');
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
<html>
<body>
<form action="submit.php" method="post" >
<table>
<tr>
<th>Teacher name</th>
<th>Date</th>
<th>Roll No</th>
<th>Student name</th>
<th>Father name</th>
<th>Addhaar No</th>
<th>Status(P)</th>
<th>Status(A)</th>
<th>Status(L)</th>
</tr>
<?php
foreach($select as $val) {
?>
<tr style="border:2px solid black;">
<td><input type="text" name="teacher" value="<?php echo $s; ?>"></td>
<td><input type="text" name="date" value="<?php echo $date; ?>"></td>
<td><input name="roll_no" value="<?php echo $r['roll_no']; ?>"></td>
<td><input name="student_name" value="<?php echo $r['student_name'] ?>"></td>
<td><input name="father_name" value="<?php echo $r['father_name'] ?>"></td>
<td><input name="addhaar_no" value="<?php echo $r['addhaar_no'] ?>"></td>
<td><input type="checkbox" value="present" name="status"> Present</td>
<td><input type="checkbox" name="status" value="absent">Absent</td>
<td><input type="checkbox" name="status" value="leave">Leave</td>
</tr>
<?php
}
?>
</table>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
For submit.php code bellow
<?php
$user = 'root';
$pass = '';
$dbh = new PDO('mysql:host=localhost;dbname=education', $user, $pass);
$stmt = $dbh->prepare("INSERT INTO attandance (roll_no, student_name, father_name, addhaar_no, status) VALUES (?, ?, ?, ?, ?)");
$stmt->bindParam(1, $roll_no);
$stmt->bindParam(2, $student_name);
$stmt->bindParam(2, $father_name);
$stmt->bindParam(2, $addhaar_no);
$stmt->bindParam(2, $status);
//if you insert 2 time then
for($x=0; $x<2; $x++) {
$roll_no = $_POST['roll_no'];
$student_name = $_POST['student_name'];
$father_name = $_POST['father_name'];
$addhaar_no = $_POST['addhaar_no'];
$status = $_POST['status'];
$stmt->execute();
}
?>
i have this database
and this form, dynamically generated from the database
<table border="1" cellspacing="0" cellpadding="6">
<tr bgcolor="#CCCCCC">
<td><strong>product id</strong></td>
<td><strong>product name</strong></td>
<td><strong>product price</strong></td>
<td><strong>quantity</strong></td>
</tr>
<form method="post" action="insert.php">
<?php
$query = $dbh->query('SELECT * FROM products');
$results = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row)
{
?>
<tr>
<td><?php echo $row['product_id']; ?></td>
<td><?php echo $row['product_name']; ?></td>
<td><?php echo $row['product_price']; ?></td>
<td><input name="quantity" type="text" value="0"></td>
</tr>
</form>
<?php } ?>
</table>
<br>
<input type="submit" value="Add Records">
the quantity in the form is a textbox so i can modify it.
I would like to enter the quantities and the pressing the button to insert the values in the order_products table (including the quantity).
1) How can i pass ALL the quantities and product_id (and the rest) to the next page through post? (until now i know how to pass single values)
2) is there a better way to achieve it?
3) the insert statements should be in the same page or the page where i get the post vars?
db scheme
http://i.stack.imgur.com/oqdOy.jpg
thanks
Rob
1) First, you have to wrap your <input>s inside a single form (move your </form> tag after your <input type="submit" value="Add Records">, the way you have it now closes the <form> tag at first iteration) and submit it via HTTP POST method. Then, based on your schema, the only field you'll have to insert aside of quantity is product_id, which value you can assign inside a hidden field, like:
<?php
echo "<input type='hidden' name='pid_$row['product_id']' value='$row['product_id']'>";
echo $row['product_id'];
?>
Notice that you can still echo the value itself for viewing purposes. You also have to generate your quantity <input> field name property dynamically, otherwise $_POST will overwrite values when their keys are the same.
<?php
echo "<input type='text' name='pid-qtd_$row['product_id']'>";
?>
2) It depends on your development priorities. There are some frameworks out there that might simplify your process. I'd recommend you to keep all your DB queries and connection data within a DB helper class and require it wherever you need it.
3) Since you're using PDO, I assume you have an OOP design, which implies in doing that at your DB helper class or such. The page receiving the HTTP request must require your helper and deal with the $_POST parsing to parameters to its query methods. Don't forget to prepare your statements and parameterizing your queries.
Using hidden element you can post your data to second page. Using counter variable you can add dynamic form element and post it into second page.
<form method="post" action="test2.php">
<table border="1" cellspacing="0" cellpadding="6">
<tr bgcolor="#CCCCCC">
<td><strong>product id</strong></td>
<td><strong>product name</strong></td>
<td><strong>product price</strong></td>
<td><strong>quantity</strong></td>
</tr>
<?php
$query = $con->query('SELECT * FROM product'); //your query goes here
$results = $query->fetchAll(PDO::FETCH_ASSOC);
$i=0; //counter variable
foreach ($results as $row)
{
?>
<tr>
<td>
<?php echo $row['prod_id']; ?>
<input type="hidden" name="prod_id<?php echo $i; ?>" value="<?php echo $row['prod_id']; ?>" />
</td>
<td>
<?php echo $row['prodname']; ?>
<input type="hidden" name="name<?php echo $i; ?>" value="<?php echo $row['prodname']; ?>" />
</td>
<td>
<?php echo $row['price']; ?>
<input type="hidden" name="price<?php echo $i; ?>" value="<?php echo $row['price']; ?>" />
</td>
<td><input name="quantity<?php echo $i; ?>" type="text" value="0"></td>
</tr>
<?php
$i++; //increment counter variable
}
?>
<input type="hidden" name="rows" id="rows" value="<?php echo $i; ?>" />
</table>
<br>
<input type="submit" value="Add Records">
</form>
Your insert page code goes here....
for($i=0;$i<=$_POST['rows'];$i++)
{
$prodid = $_POST['prod_id'.$i];
$pname = $_POST['name'.$i];
$pprice = $_POST['price'.$i];
$con ->exec("insert into product(prod_id,prodname,price)values('$prodid', '$pname','$pprice' )" );
}
I suggest putting the product_id in a hidden form element like this:
<tr>
<input type='hidden' name='product_id' value='<?php echo $row['product_id']; ?>'/>
<td><?php echo $row['product_id']; ?></td>
<td><?php echo $row['product_name']; ?></td>
<td><?php echo $row['product_price']; ?></td>
<td><input name="quantity" type="text" value="0"></td>
</tr>
This will send the product_id with your quantity and you can use it in your insert statement.
The only problem with this is if you have more than one row, there will be more than one hidden element for product_id, etc. Ways to overcome this include differentiating them by appending an incrementing number on the hidden element's name, e.g.:
$i = 1;
foreach ($results as $row)
{
$product_id_name = 'product_id_'.$i;
$quantity_name = 'quantity_'.$i;
... echo your table row, using $product_id_name in the hidden element, and $quantity_name in your text input
$i++;
}
Then in your inserting code you have to look for all the items in $_POST whose keys start with "quantity_", and if they are non-zero, get the integer NNN after the key prefix "quantity_", and get the corresponding product_id_NNN value to do your insert.