Insert data from a populated data table - php

I need your help to assist me on this problem. So as you can see in Form1.php, I've select data from db which are (flock id, house, breed) and these data will populate the row for the table. The problem is, this form will consist of 2 tables in database.
flock id, house, breed -> table1
age, prev day stock, cull, mortality -> table2
I want to insert all the data in table2. How do i link the data from table 1 & 2 and save the records in table2?
The below code is the form which i've coding so far. Glad if you can help me.
Form1.php
<form action="" method="post">
<table>
<?php
include 'db/dbconn.php';
$sql = "SELECT * FROM flockjawi";
$result = $dbconn->query($sql);
?>
<tr>
<th>FLOCK ID</th>
<th>HOUSE</th>
<th>BREED</th>
<th>AGE</th>
<th>PREV DAY STOCK</th>
<th>CULL</th>
<th>MORTALITY</th>
</tr>
<?php
if($result->num_rows > 0){
while($rows = $result->fetch_assoc()){ ?>
<tr>
<td><?php echo $rows['flockps_id']; ?></td>
<td><?php echo $rows['house_code']; ?></td>
<td><?php echo $rows['breed_doc']; ?></td>
<td><input type="number" name=""></td>
<td><input type="number" name=""></td>
<td><input type="number" name=""></td>
<td><input type="number" name=""></td>
</tr>
<tr>
<input type="submit" name="submit" value="Save">
</tr>
<?php
}
}
?>
</table>
</form>

You must add related id column for connecting this tables. In your second table add column named, for example, flockjawi_id. While you will add new row, add to this column id from your first table - flockjawi.
And then you will have a second table, which will contain rows with related column to the first table.

Related

Making a table with foreach, trying to submit data using each table row

So its been over 10 years since writing any code what so ever so i might be way off here. I have a table showing all students in a classroom populated by a foreach loop with an added box to input their grade. I need 1 submit button to insert one new row per student in the grades table in my database with their grade and the assignment name that is selected above.
I know i need to identify each grade value im just unsure how and it's only posting the person in the last row.
global $wpdb;
$asnames = $wpdb->get_results( "SELECT * FROM assignments" );
$results = $wpdb->get_results( "SELECT * FROM enrolled" );
?>
<div class="container"><center>
<form action ="<?php echo $_SERVER['REQUEST_URI']; ?>" method ="post">
<table class="form-table" id='topper'>
<tbody>
<tr>
<th>Assignment Name</th>
</tr>
<tr>
<td>
<select name="Assignment">
<?php foreach($asnames as $asname) { ?>
<option value="<?php echo $asname->id ?>"><?php echo $asname->assign_name ?></option>
<?php
} ?>
</select>
</td>
</tr>
</tbody>
</table></center>
</div>
<br><br>
<div class="container"><center>
<form action ="<?php echo $_SERVER['REQUEST_URI']; ?>" method ="post">
<table class="form-table" id='student'>
<tbody>
<tr>
<th>Students Name</th>
<th>Points</th>
</tr>
<?php foreach($results as $row){ ?>
<tr>
<td><?php echo "$row->student_name" ?></td>
<td><input type="text" class="regular-text" name="Grade"></td>
</tr>
<?php } ?>
<!-- </tbody> -->
</table>
<p><input type="submit" name="submitinsert" id="submitinsert" class="button button-primary" value="Submit"/></p> </form>
</center></div>
<?php
if ($_POST['submitinsert']){
$result = $wpdb->insert(
'grades',
array(
"student_name" => $row->student_name,
"assignment_id" => $asname->id ,
"grade" => $_POST['Grade']
)
);
}
I cant seem to get it to grab each row as it is in the table to insert, only the last row gets put in.
EDIT: I got the grade input worked out now just trying to get each loop put into the database with the single submit button.

PHP While loop only works for first two of three results?

I know I am a beginner, but I have an issue I can't figure out. I've searched everywhere. Please don't be mean:) I'm trying to learn!:)
SO I have a while loop that is making an HTML table for me, and two of the three row[] echoes work every time, but the third echoes only the ID of the last entry in the table.
My code:
<?php
$searchsql = "SELECT * FROM `students` WHERE `fname` LIKE '%" . $searchvalue1 . "%' LIMIT 0, 10 ";
$search1result = mysql_query($searchsql);
while($search1row=mysql_fetch_array($search1result)){?>
<h3>
<table align="center">
<thead>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>Select</td>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $search1row['fname'];?></td>
<td><?php echo $search1row['lname'];?></td>
<td>
<form method="post" action="4.php">
<input type="hidden" id="voteid" name="voteid" class="inputbutton" value="<?php echo $search1row['studentid'];?>">
<input type="submit" class="inputbutton" value="SELECT">
</td>
</tr>
</tbody>
</table>
</h3>
<?php }?>
So if the table returned is (see picture)
The select button from within that form always posts the studentid from the LAST row... Every select button posts Jane's ID number. So John, Jason, Jane, and their last names are echoed correctly, but their corresponding ID numbers are not... if that makes any sense.
I have to keep it a form because of the way my site works (not a link with get variables).
Any ideas on how to get the ID to echo inside of that form?
You're not closing the form at the end of each loop. So each time the voteid input is getting overwritten which is why it always posts the id for the last row.
Add a closing form tag:
...
<form method="post" action="4.php">
<input type="hidden" id="voteid" name="voteid" class="inputbutton" value="<?php echo $search1row['studentid'];?>">
<input type="submit" class="inputbutton" value="SELECT">
</form>
...

Saving the selected rows by checkbox to database in php

I have a query to display all the records of the ebooks table from the database.
I displayed it in a table with a checkbox from the first column.
I'm trying to save the rows from the selected checkbox in the table width the Name of School but I don't have any idea.
I'm just a beginner in php, any help is appreciated. Here is my codes:
HTML codes:
$result1 = mysql_query("SELECT * FROM school GROUP BY SCHOOL_NAME");
while($row1=mysql_fetch_array($result1)) {
?>
<option><?php echo $row1['SCHOOL_NAME'];?></option>
<?php } ?>
</select>
<table class="table table-striped table-hover table-bordered datatable">
<thead style="background: #a83535; color: black;">
<tr>
<th style="width: 50px;"></th>
<th style="color: #3b3b3b;">Ebook Title</th>
<th style="color: #3b3b3b;">Category</th>
<th style="color: #3b3b3b;">File Name</th>
</tr>
</thead>
<tbody>
<?php
$result = mysql_query("SELECT * from ebooks ORDER BY EBOOK_TITLE");
$count = mysql_num_rows($result);
while($row=mysql_fetch_array($result)) {
?>
<tr>
<td>
<center><input type="checkbox" name="check[]" ></center>
</td>
<td><input type="" name="ebookname[]" value="<?php echo $row['EBOOK_TITLE'];?>"></label></td>
<td><input type="" name="ebookcategory[]" value="<?php echo $row['EBOOK_CATEGORY'];?>"></label></td>
<td><input type="label" name="ebookfilename[]" value="<?php echo $row['EBOOK_FILENAME'];?>"></label></td>
</tr>
<?php } //end of while loop ?>
</tbody>
</table>
<button type="submit" class="btn btn-hg btn-primary" name="AddEbooks">Submit</button>
I want to save the rows selected by the checkbox to database:
Table: school_management
Columns: ID_NUMBER, SCHOOL, EBOOK, FILE_NAME, DATE_ASSIGN
Values (from the HTML table to database): ('','$school_ebook','$ebookname','$ebookfilename','')
Here is the screenshot:
First, you will need to assign an ID number to the checkboxes so that you can differentiate each record. Using the ID_NUMBER would be ideal here. In your current script where you are displaying the checkbox, your line that reads this:
<center><input type="checkbox" name="check[]" ></center>
Should include the ID_NUMBER like this in the name. Additionally, a value should be assigned to the checkbox so we can verify later.
<center><input type="checkbox" name="check[<?php echo $row['ID_NUMBER'];?>]" value="1"></center>
Now you can go ahead and set up something that gets triggered when your form is submitted. You can essentially loop through each record and check it against the "check[ID_NUMBER]" checkbox to see if the value is 1. If the value is 1 then the record had been checked to save and you can then carry on saving the record.
How you want to handle the form is up to you - you could do AJAX to avoid reloading the entire page or you could do a simple form action="page_name_here.php" and handle the submission there. If you go about doing a simple form post without AJAX, it could be something like this -
Current page form tag:
<form name="" action="page_name_here.php" method="POST">
If you want to use the school_ebook var you need to assign the select options for the school_ebook a value:
<option value="<?php echo $row1['SCHOOL_NAME']'?>">
page_name_here.php:
<?php
/* Get the school name */
$school_ebook=$_POST["school_ebook"];
/* Query your books DB to get the records */
$result=mysql_query("SELECT * from ebooks ORDER BY EBOOK_TITLE");
$count=mysql_num_rows($result);
while($row=mysql_fetch_array($result)) {
$bookID=$row['ID_NUMBER'];
/* Get the Book ID and now we have to fetch from $_POST the value from the form */
if (array_key_exists($bookID, $_POST["check"])) {
$ischecked=$_POST["check"][$bookID];
/* See if this has a value of 1. If it does, it means it has been checked */
if ($ischecked==1) {
/* It is checked, so now in this area you can finish the code to retrieve the data from the row and save it however you like */
}
}
}
?>
Once completed with your inserts, etc., it should accomplish what you need.

issue when inserting data in DB using submit button

i define below codes to show my products on website. I fetch my products details from Database.
When i click on the enquiry submit button it is not selecting the same id and inserting another product id in to database. Please see below codes which i use to send details in database using enquiry Submit Button
Please see below the updated codes, these are all codes which i am using to inserting data when clicking on enquiry submit button
<?php
session_start();
include'database.php';
$userid=$_SESSION['userid'];
$c=mysql_query("select 'productid','productprice' from products order by rand()");
while(list($productid,$productprice)=mysql_fetch_array($c)):
?>
<td align="center">
<table class="newproducttd" align="center">
<tr>
<td class="code" align="center"><?php echo $productid; ?></td>
<td class="price" align="center"><?php echo $productprice; ?></td>
</tr>
<tr>
<td class="button" align="center"><input type="submit" class="enquiry" name="enquiry" value="ENQUIRY" /></td>
</tr>
</table>
</td><br>
<?php
endwhile;
if($_REQUEST['enquiry'])
{
mysql_query("insert into orders values('$userid','$productid','$productprice')");
}
?>
Your table in your mysql database probably has the columns in a different order. To make sure, specify the columns in your insert query before specifying the values.
You're getting the wrong value for $productid because it's assigning the last value of it in your while loop, as your insertion code (and therefore your reference to it) is below that loop, you want to send the product id and price to the page accessible by $_REQUEST when the user clicks submit, to do this in your case you can use hidden form fields to store the values of each product, and a separate form for each element in your loop.
Also you want to put your submission code above your loop.
Depending where this data comes from you might want to escape it before inserting it in the database, I haven't in this example.
<?php
session_start();
include'database.php';
$userid=$_SESSION['userid'];
//check for submission and insert if set
if($_REQUEST['enquiry'])
{
//use the userid session for userid, and submitted values for productid and productprice
mysql_query("insert into orders values('$userid,'{$_REQUEST['productid']}','{$_REQUEST['productprice']}')");
}
$c=mysql_query("select 'productid','productprice' from products order by rand()");
while(list($productid,$productprice)=mysql_fetch_array($c)):
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<td align="center">
<table class="newproducttd" align="center">
<tr>
<td class="code" align="center"><?php echo $productid; ?></td>
<td class="price" align="center"><?php echo $productprice; ?></td>
</tr>
<tr>
<td class="button" align="center"><input type="submit" class="enquiry" name="enquiry" value="ENQUIRY" /></td>
//hidden form fields to store data to send to page
<input type="hidden" name="productid" value="<?php echo $productid;?>">
<input type="hidden" name="productprice" value="<?php echo $productprice;?>">
</tr>
</table>
</form>
<?php
endwhile;
?>

Displaying Data from mysql table

I have created this form using the while loop so that i dont have to make 28 text field ... but when i submit the data into my mysql database it works well but how to display the data back to my form for edit and update .. when i type a value to a text field (EX - submitted data from mysql in emp_name field) then it repeated 4 times in the text field .... i know it is happening because of loop but is there any way that i can display multiple data in each text field for updating after submitting data by the user as normal ....
my form.php
<form action="userdata.php" name="frmAdd" method="post">
<table width="80%" border="0" cellpadding="3" cellspacing="3" class="forms">
<tr>
<td width="5"> <div align="center">NO</div></td>
<td width="91"> <div align="center">Employer's NAME</div></td>
<td width="160"> <div align="center">COUNTRY</div></td>
<td width="198"> <div align="center">POSITION</div></td>
<td width="70"> <div align="center">FROM</div></td>
<td width="70"> <div align="center">TO</div></td>
<td width="70"> <div align="center">SALARY</div></td>
<td width="70"> <div align="center">REASONS FOR LEAVING</div></td>
</tr>
<?php for($i=1;$i<=4;$i++) { ?>
<tr>
<th width="5"> <div align="center"><? echo $i . "."; ?></div></th>
<td><input type="text" name="emp_name<?=$i;?>" size="25" value="submitted data from mysql"></td>
<td><input type="text" name="emp_country<?=$i;?>" size="10"></td>
<td><input type="text" name="emp_pos<?=$i;?>" size="10"></td>
<td><input type="text" name="emp_frm<?=$i;?>" size="5"></td>
<td><input type="text" name="emp_to<?=$i;?>" size="5"></td>
<td><input type="text" name="emp_sal<?=$i;?>" size="5"></td>
<td><input type="text" name="emp_lev<?=$i;?>" size="25"></td>
</tr>
<?php } ?>
</table>
</br>
<input type="submit" name="doHis" value="Save Employment History">
<input type="hidden" name="hdlfrm" value="<?=$i;?>">
</form>
and my userdata.php
if($_POST['doHis'] == 'Save Employment History')
{
try{
$conn = new PDO("mysql:host=localhost;dbname=dbname", "user", "pass");
}
catch(PDOException $pe)
{
die('Connection error, because: ' .$pe->getMessage());
}
for($i=1;$i<=$_POST["hdlfrm"];$i++){
if($_POST["emp_name$i"] != ""){
$sql = "INSERT INTO emp_table (emp_name, emp_country, emp_pos, emp_frm, emp_to, emp_sal, emp_lev)
VALUES (:emp_name, :emp_country, :emp_pos, :emp_frm, :emp_to, :emp_sal, :emp_lev)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':emp_name', $_POST["emp_name$i"]);
$stmt->bindParam(':emp_country', $_POST["emp_country$i"]);
$stmt->bindParam(':emp_pos', $_POST["emp_pos$i"]);
$stmt->bindParam(':emp_frm', $_POST["emp_frm$i"]);
$stmt->bindParam(':emp_to', $_POST["emp_to$i"]);
$stmt->bindParam(':emp_sal', $_POST["emp_sal$i"]);
$stmt->bindParam(':emp_lev', $_POST["emp_lev$i"]);
$stmt->execute();
echo "Save Done. Click <a href='phpMySQLListRecord.php'>here</a> to view.";
}
}
}
and here is the snapshot
The problem you have is your data model - you are saving employment history, but for who? It needs to have an employee_id somewhere to say who this data belongs to, and join it to a table that saves the employee_table data. Next you need to have a unique ID on the emp_table to identify each row, which you can use instead of your $i index.
TABLE
history_id INT autoincrement | employee_id INT | emp_name VARCHAR | your other fields....
SELECT
SELECT history_id, emp_name, ... FROM emp_history where employee_id = ?
You can then loop over the results and use the history_id to identify the row that the data belongs to to update it. Submitting multiple fields with the same name will be an array you can iterate over, so you don't need to use a unique field name for each.
As a side note, you probably want to use isset($_POST["key"]) instead of $_POST["key"] != "" to check if a field was submitted.

Categories