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.
Related
I am going to fetching table values in a html table along checkbox in each row and then inserting values in another database table from multi check boxes in php.
Only the values of checked boxes should be submitted to that table.
db name "laboratory":
test: fetching values.
package: inserting table.
view
Status
Active
Inactive
<?php
$conn=mysqli_connect("localhost","root","","laboratory") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$query="SELECT * FROM test";
$result=mysqli_query($conn,$query);
if ($result) {
while ($record=mysqli_fetch_array($result)) {
Please try to follow this code and implement in your program . Hope that this will cooperate you much
if(isset($_POST['name'])){
$name = $_POST['name'];
$status = $_POST['status'];
if(empty($name) || empty($status)){
echo "Field Must Not be empty";
} else{
$conn=new mysqli("localhost","root","","test");
if($conn){
$query = "SELECT * FROM userdata limit 5";
$stmt = $conn->query($query);
$val = '<form action="" method=""> ';
$val .= '<table> ';
if ($stmt) { ?>
<form action="" method="post">
<table>
<?php while ($result=$stmt->fetch_assoc()) { ?>
<tr>
<td><?php echo $result['post']; ?></td>
<td><input value="<?php echo $result['post']; ?>" type="checkbox" name="check[]" /></td>
</tr>
<?php } ?>
<tr>
<td>Actual Price </td>
<td>Discount</td>
<td>Final Price</td>
</tr>
<tr>
<td><input type="text" name="actual"/></td>
<td><input type="text" name="discount"/></td>
<td><input type="text" name="final"/></td>
</tr>
<tr>
<td>Description</td>
<td><textarea name="description" id="" cols="30" rows="10"></textarea></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
<td><input type="reset" value="Cancel" /></td>
</tr>
</table>
</form>
<?php }} }}?>
<?php
if(isset($_POST)){
echo "<pre>";
print_r($_POST);
echo "<pre>";
}
?>`enter code here`
First of all you have to decide that what are you using either mysqli or mysql, if you are using mysqli then you have to improve your code
$query="SELECT * FROM test";
$result=mysqli_query($conn,$query);
if ($result) {
while ($record=mysqli_fetch_array($result)) {
and when you want to insert the checked data will be inserted in package table. If package table in another database then you have to give us the full detail i mean tell us the database name of package table.
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 had to add a form action to go to a different page to edit a specific record, but with doing that, it won't allow me to delete a record because it is taking me away from it before it will do the query. I am unsure of how to make this work and still get to the new page when I hit the "Edit" button.
<table id="tableid">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Product</th>
<th>Save</th>
<th>Delete</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$stmt = $dbc->query("SELECT `id`,`first`,`last`,`product` FROM users");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while($row = $stmt->fetch()) {
?>
<form method="POST" action="edit-product">
<tr>
<td><?php echo $row['id'];?>"</td>
<td><?php echo $row['first'];?></td>
<td><?php echo $row['last'];?></td>
<td><?php echo $row['product'];?></td>
<input name="id" type="hidden" value="<?php echo $row['id'];?>" readonly>
<input name="first" type="hidden" value="<?php echo $row['first'];?>">
<input name="last" type="hidden" value="<?php echo $row['last'];?>">
<input name="product" type="hidden" value="<?php echo $row['product'];?>">
<td><input name="save" type="submit" value="Save"></td>
<td><div class="delete-class" name="delete" id="<?php echo $row['id']; ?>">Delete</div></td>
<td><input name="edit" type="submit" value="Edit"></td>
</tr>
</form>
<?php } ?>
</tbody>
</table>
PHP DELETE query
if(isset($_POST['delete'])) {
$id = $_POST['id'];
$stmt = $dbc->prepare("DELETE FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
}
How can I change the markup to still get both the edit (going to another page with the action) and the delete to work on this page?
UPDATE AJAX code:
$(function() {
$(".delete_class").click(function(){
var del_id = $(this).attr('id');
$.ajax({
type:'POST',
url:'delete-product.php',
data:'delete_id='+del_id,
success:function(data) {
if(data) { // DO SOMETHING
} else { // DO SOMETHING }
}
)); //here
});
});
This is not very ideal but one way to do it. You change the HTML markup to create two forms, one for edit case and another one for Delete. The delete case sends the request to the current page like this:
while($row = $stmt->fetch()) {
?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['first'];?></td>
<td><?php echo $row['last'];?></td>
<td><?php echo $row['product'];?></td>
<td>
<form method="post" action="edit-product">
<input name="id" type="hidden" value="<?php echo $row['id'];?>">
<input name="first" type="hidden" value="<?php echo $row['first'];?>">
<input name="last" type="hidden" value="<?php echo $row['last'];?>">
<input name="product" type="hidden" value="<?php echo $row['product'];?>">
<input name="save" type="submit" value="Edit">
</form>
</td>
<td>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input name="id" type="hidden" value="<?php echo $row['id'];?>">
<input name="delete" type="submit" value="Delete">
</form>
</td>
</tr>
<?php }
?>
</tbody>
</table>
<?php
// the delete code goes here
if(isset($_POST['delete'])) {
$id = $_POST['id'];
$stmt = $dbc->prepare("DELETE FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
}
?>
I left out the save case but it will be similar to edit case.
Rather than having a form you could just have links instead of form submit buttons. That way each link could take you to a specific page that performs a specific task. By passing query string variables and using $_GET rather than $_POST, you can retain the product ID information.
Example:
<td>Save</td>
<td>Delete</td>
<td>Edit</td>
These individual pages could then perform your tasks in the database. Both save and delete could use Header re-directs to get back to your original page with your product list.
delete_product.php Example:
// delete product from database
$id = $_GET['id']; // Note that it's a $_GET
$stmt = $dbc->prepare("DELETE FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
// re-direct to original list page
header("Location: product_list.php"); // or whatever you have your list page named.
The edit_product.php page would then have your typical form for making changes to a specific product. You will need to lookup the product again in the database using $_GET['id'] value to match it with.
As it was suggested in the comments, using AJAX would make the whole process appear to be seamless, rather than jumping around between pages and being re-directed.
im currently displaying all the information from the table product in a tabular format, i have a button ADD which when click should add only the id, name and price from the table product to the table product_add in the same database. but my problem is that when i click on the button ADD, nothing is entered in the product_add table.
<?php
include'connect.php';
$image =$_GET['image'];
$id =$_GET['id'];
$name =$_GET['name'];
$price=$_GET['price'];
$sql="SELECT * FROM product";
$result = mysql_query($sql);
if($result>0)
{
?>
<form method="post" id="form" name="form">
<table border='1'>
<?php
while ($row = mysql_fetch_array($result))
{
extract($row);
?>
<tr>
<td><?php echo $row['id']?></td>
<td><img src=<?php echo $row['image'] ?> /></td>
<td><?php echo $row['name']?></td>
<td><?php echo $row['price']?></td>
<td><input type='button' value='ADD' id="insert" name="insert"/></td>
</tr>
<?php
}
?>
</table>
</form>
<?php
}
if(isset($_REQUEST['insert']))
{
$insert = "INSERT INTO product_add(id, name, price)
VALUES ('$row[id]','$row['name']','$row['price']')";
$insertQuery=mysql_query($insert);
}
?>
</body>
</html>
I have updated the codes as shown below but the last row from the table product is being added to the table product_add. I want to add only a specific row when i click on the button submit.
<?php
include'connect.php';
$image = isset($_GET['image']) ? $_GET['image'] : "";
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$price= isset($_GET['price']) ? $_GET['price'] : "";
$sql="SELECT * FROM product";
$result = mysql_query($sql);
if($result>0){
?>
<form method="POST" id="form" name="form">
<table border='1'>
<tr>
<th>Id</th>
<th>Image</th>
<th>Name</th>
<th>Price MUR</th>
</tr>
<?php
while ($row = mysql_fetch_array($result)){
extract($row);
?>
<tr>
<td><input name="id" value="<?php echo htmlspecialchars($row['id']); ?>">
</td>
<td><img src=<?php echo $row['image'] ?> width='120' height='100'/></td>
<td><input name="name" value="<?php echo htmlspecialchars($row['name']);
?>"></td>
<td><input name="price" value="<?php echo htmlspecialchars($row['price']);
?>"></td>
<td>
<input id="submit" type="submit" name="submit" value='Add to cart' />
</td>
</tr>
<?php
}
?>
</table>
</form>
<?php
}
if (isset($_REQUEST['submit']))
{
$insert = "INSERT INTO product_add(id, name, price) VALUES ('$id',
'$name','$price')";
$insertQuery=mysql_query($insert);
}
?>
Apart from the method (if your form uses POST, you should use $_POST in php), you do not have any form fields.
For example:
<?php echo $row['id']?>
Should be something like:
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
and:
<?php echo $row['name']?>
should be:
<input name="name" value="<?php echo htmlspecialchars($row['name']); ?>">
etc.
You should also switch to PDO or mysqli and prepared statements as the code you have now is vulnerable to sql injection. And ID's in html need to be unique.
One point is, you have multiple
<input type='button' ...>
with the same id="insert". ids must be unique within a web page.
The other thing is, you need a submit input to send the form
<input type="submit" ...>
From Submit Button state (type=submit)
The input element represents a button that, when activated, submits the form.
With <input type='button' ...> nothing happens, because it has no default action, see Button state (type=button)
The input element represents a button with no default behavior.
If you want an <input type='button' ...> to submit the form, you must do so by using some Javascript code.
One idea is to load content once the button is clicked.
js
$("#button").click(function() {
$("#holder").load("insert.php");
});
insert.php
$db->query("INSERT INTO table VALUES('one','two','three')");
I just need to insert my form data into mysql database & display it in browser. But, when I fill up the form & click submit , the row gets added but with no data except for ID field which is autoincremented.. even the table in phpmyadmin looks same with the row added & empty fileds.
any suggestions will be highly appreciated...
my html form looks like this,
<table border="1">
<tr>
<td align="center">Form Input Students Data</td>
</tr>
<tr>
<td>
<table>
<form method="POST" action="data_insert_htmlform.php/">
<tr>
<td><label for="Name">Name</label></td>
<td><input type="text" name="name" size="20">
</td>
</tr>
<tr>
<td><label for="Age">Age</label></td>
<td><input type="text" name="age" size="20">
</td>
</tr>
<tr>
<td><label for="Birth_Date">Birth_Date</label></td>
<td><input type="text" name="Birth_Date" size="20">
</td>
</tr>
<tr>
<td><label for="Address"Address</label></td>
<td><input type="text" name="address" size="40">
</td>
</tr>
<tr>
<td></td>
<td align="center">
<input type="submit" name="submit" value="Sent">
</td>
</tr>
</form>
</table>
</td>
</tr>
</table>
and my php code,
<?php
error_reporting(E_ERROR | E_PARSE);
$database = 'students';
$continued=mysql_connect("localhost" , "root", "");
if(mysql_select_db($database))
echo ("<br><br>connection to the database succeeds");
else
echo ("connection failed");
/*$name = $_POST['name'];
$age = $_POST['age'];
$birth_date = $_POST['Birth_date'];
$address = $_POST['address'];*/
$insert = "INSERT INTO students_basicinfo(Name, Age, Birth_Date, Address) VALUES ('{$_POST['name']}','{$_POST['age']}' , '{$_POST['Birth_date']}' , '{$_POST['address']}')";
$abc = mysql_query($insert);
if($abc){
echo("<br>Input data is succeed");
}else{
echo("<br>Input data is fail");
}
$order = "SELECT * FROM students_basicinfo";
$result = mysql_query($order);
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
echo "<table border='1'>";
while($data = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>".$data[ID]."</td>";
echo "<td>".$data[Name]."</td>";
echo "<td>".$data[Age]."</td>";
echo "<td>".$data[Birth_Date]."</td>";
echo "<td>".$data[Address]."</td>";
echo "</tr>";
}
echo "</table>";
?>
This issue about input name case sensitive
Change $_POST['Birth_date'] to $_POST['Birth_Date'] with uppercase D
Try following query, this will work.
$insert = "INSERT INTO students_basicinfo(Name, Age, Birth_Date, Address) VALUES ('{$_POST['name']}','{$_POST['age']}' , '{$_POST['Birth_Date']}' , '{$_POST['address']}')";
Replace
'{$_POST['name']}','{$_POST['age']}' , '{$_POST['Birth_date']}' , '{$_POST['address']}'
with
'".$_POST['name']."','".$_POST['age']."' , '".$_POST['Birth_date']."' , '".$_POST['address']."'
Try :
echo "<tr>";
echo "<td>".$data['ID']."</td>";
echo "<td>".$data['Name']."</td>";
echo "<td>".$data['Age']."</td>";
echo "<td>".$data['Birth_Date']."</td>";
echo "<td>".$data['Address']."</td>";
echo "</tr>";
(Use prepared statements.)
Dump the statement, in a HTML comment <!-- ... ---> so you can try it yourself.
Use echo mysql_error() to check for errors.
I mistrust the date field, DATE? Use '2013-08-31or '2013-08-31 14_:07 / '2013-08-31T14_:07`.