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.
Related
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.
I tried to look in this site but none of the question which relate exactly like mine. I need help on this problem since am very new in PHP.
Iam developing students result application which used to collect scores of the students. My problem is, I fail to submit all information I get like (idnumber, names and subject), after searching records of students of a certain class, here is my scripts.
<?php
$number = $courseObj->sele_ct_class($class, $year);
?>
<table class="table table-bordered" style="border-radius: 100px" border="0">
<tr style="font-size: medium; background-color: lavenderblush">
<td>#</td>
<td>Admission Number</td>
<td>Student name</td>
<td>Max.Mark</td>
<td>Mark</td>
</tr>
</thead>
<tbody>
<?php
$i = 1;
$notaVilableId = $courseObj->seleId($class, $year); // Select_all From curClass according to aguments (return all idnumber)
foreach ($notaVilableId AS $haika) {
$classIdnumber = $haika->idnumber;
$jina = $haika->jina;
?>
<tr>
<td style="width: 5%"><?php echo $i++; ?></td>
<td><?php echo $classIdnumber ?></td> <!-- this display idnumber -->
<td><?php echo $jina ?></td> <!-- this display name -->
<td>100</td>
<td class="col-sm-2"><input type="number" id="subject" name="subject" class="form-control"></td> <!-- this fiels used to input score marks -->
</tr>
<?php } ?> <!-- end foreach -->
<tr>
<td colspan="20px">
<button class="btn btn-success" type="submit" name="fee_submit" id="fee_submit">Save
</button> <!-- submission button -->
</tr>
Problem is here, I get only idnumber of one student and the rest not appear, can any one show me how I could get all information like (idnumber, name and subject score which entered for each student). I mean that I want all information displayed to be submited with there scrored marks. Thank
<?php
if (isset($_POST['fee_submit'])) {
$classIdnumber;
$jina;
$score = sanitize($_POST['subject']);
$courseObj->insertseTExams($classIdnumber, $jina, $score); // function used to insert data
}
change this
<input type="number" id="subject" name="subject" class="form-control">
to note name="subject[]" change
<input type="number" id="subject" name="subject[]" class="form-control">
getting the data in php
i=0;
$number=count($_POST["subject"];
while ($i < $number ){
$score = sanitize($_POST['subject'][$i]);
//instert your data or do whatever else
$i++;
}
it seems you have assigned $classIdnumber,$jina to read its values from the $_POST super global variable.. And also, any data that is to be submitted to a server page for processing should be in-between form tags,this way you can access this values through the $_POST super global
I've been working on my website's database and I had this problem recently:
I want the user to read a field of a row, when another field of the same row is submitted.
I.e:
user_id=1 user_name=Fran user_pass=Potato referedby_id=0 referedby_name=empty
When going inside www.website.com/form.php?referedby_id=1
I want the user to see "So, Fran refered you?"
I've been learning php and I decided to try this:
$referedbyid = mysqli_real_escape_string($con,$_POST["referedby_id"]); //In this case it's 1 because of the url
$sel_referedbyname = "select user_name from users where user_id='$referedbyid'"; //Then this should be the select of the user_name "Fran"
$run_referedbyname = mysqli_query($con, $sel_referedbyname); //Then a query for that select
$check_referedbyname = mysqli_fetch_field($run_referedbyname); //And this one the content of the query's result
$refername = $check_refername->user_name; //As the query result is an object I want to convert it to text
if(isset($_POST["register"]) && $check_user == 0 && $check_email == 0 && $pass == $pass2){ //If everything is right and the user/email does not already exist
mysqli_query($con,"INSERT INTO users (user_name, user_email, user_pass, refer_id, refer_name) VALUES ('$user', '$email', '$pass', '$referid', '$refername')"); //It's submitted to the database with the other values.
mysqli_close($con); //And we finish the connection with the db.
The problem is that when I try this and check the database, the referedby_name field is empty. Is it a syntax error? Or is this because it didn't convert to text properly?
In case $referedbyname is not text, how can I convert it properly? Is this because I'm using the fetch_field function wrong?
Additional info: $referedbyid is being called properly (I think) in a POST form with this html
<form action="register.php" method="post" onsubmit="validate();">
<table width="500" align="center" bgcolor="skyblue">
<tr align="center">
<td colspan="3"><h2>Registrarse</h2></td>
</tr>
<tr>
<td align="right"><b>Nombre de usuario:</b></td>
<td><input type="text" name="user" required="required"/></td>
</tr>
<tr>
<td align="right"><b>Email:</b></td>
<td><input type="email" name="email" required="required"/></td>
</tr>
<tr>
<tr>
<td align="right"><b>ContraseƱa:</b></td>
<td><input type="password" id="pass" name="pass" required="required"/></td>
</tr>
<tr>
<td align="right"><b>Verificar contraseƱa:</b></td>
<td><input type="password" id="pass2" name="pass2" required="required"/></td>
</tr>
<tr align="center">
<td colspan="3">
<input type="hidden" name="referedby_id" value="<?php echo $_GET["referedby_id"]; ?>"/>
<input type="submit" name="register" value="Registrarse"/></td>
</tr>
</table>
</form>
I don't know why the downvotes, I tried to be as clear and specific as I could...
Anyways, if someone else has any trouble finding the value of a specific field just use mysqli_fetch_assoc(mysqli_query($conect, $select))['name of the sql field']
mysqli_fetch_field($result) will only show you information about the field, like the type of input, name of the table, name of the column, etc.
Hope that's useful for someone with the same issue. Bye.
I have a working form with a javascript 'Add Row' button, data collection and processing by PHP. While it works, the code seems fairly high-maintenance and clumsy to me (for one thing, every time I change the form I need to work the same changes into the js that adds the new row). I'm looking for suggestions to make it more sleek and simple. Currently I'm assigning each input a unique name, with hidden input that keeps track of the number of rows for me, and then I use that number to determine the amount of for loops the PHP script needs to work through to post to the database.
One thing I've considered is changing from input names to using name[], but I'm not sure if that's the right method for my needs, and how I post each row as a separate record to the database. In any case, here's the code.
HTML
<table id="table1">
<tr style="display: none"><td colspan="2">
<input type="hidden" id="samp_count" name="samp_counter" value="" />
<input type="hidden" value="sample" name="type1" /></td>
</tr>
<tr>
<td >pic caption </td>
<td>
<input type="text" name="desc1"/></td></tr>
<tr>
<td >extended description</td>
<td><textarea style="width:100%" rows="7" name="notes1"></textarea></td>
</tr>
<tr>
<td>pic file</td>
<td><input id="pic_file1" type="file" name="pic1" /></td>
</tr>
</table>
<button type="button" class="add_row" width="40px" id="samp_add_button">add row
JavaScript for the button
$(document).ready(function(){
$("#samp_count").val("1");
$("#samp_add_button").click(function(){
var iter_str=$("#samp_count").val();
var pic_id = "#pic_file" + iter_str;
if (!$(pic_id).val()){
$("#samp_error").css("visibility","visible");
}
else{
iter_str ++; // update counter
$("#samp_count").val(iter_str); //reset counter in table header to current count
var a = '<tr><td colspan="2" ><span>pic caption<input type="text" name="desc'+iter_str+'"/></span><br /></td>";
var b = '<td rowspan="3">extended description<br /><textarea style="width:100%" rows="7" name="notes'+iter_str+'"></textarea></td>';
var c = '<tr><td colspan="2" >pic file</td><td><input id="pic_file'+iter_str+'" type="file" name="pic'+iter_str+'" /></td></tr>';
$("#table1").append(a+b+c);
$("#samp_error").css("visibility","hidden");
}
});
});
PHP
<?php
if(isset($_POST['send_button'])&&$isValid==TRUE){
$user = $_POST['user'];
$count_str1 = $_POST['samp_counter'];
$count1 = intval($count_str1);
for ($i=1; $i <= $count1; $i++) {
$desc= "desc".$i;
$pic= "pic".$i;
$notes= "notes".$i;
$desc_con = $_POST[$desc];
$notes_con = $_POST[$notes];
if($_FILES[$pic]["name"]){
if( formFileUpload($pic, $user)){ //custom function to validate and upload pics-- not relevant to question at hand
$uid_path = "portfolios/".$user."/";
$file_path=$uid_path.$_FILES[$pic]["name"];
$dbh = new PDO('mysql:host=localhost;dbname=db', 'admin','pass');
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);
$statement=$dbh->prepare("INSERT INTO portfolios (UserID, Description, FilePath, FileType, Notes) VALUES (?,?,?,?,?)");
$statement->bindParam(1,$user);
$statement->bindParam(2,$desc_con);
$statement->bindParam(3,$file_path);
$statement->bindParam(4,$_POST[type1]);
$statement->bindParam(5,$notes_con);
$statement->execute();
}
else{
$fileErrorDis="inline";
$isValid=FALSE;
} }}
?>
Link to working website -- self-explanatory but text in Hebrew (in some of the forms, the js has not been updated and the new row does not resemble the original one)
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;
?>