PHP how to Submit many records after search - php

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

Related

How do I make it so that my submit button updates all rows in my database?

I am learning basic php since September 2015, and I have to create a website with a fully functioning php update code.
What I have right now is a news page with 3 rows that have to be updated in an administration panel with a submit button for every field (date, title and content), so there are 3 forms for 3 news articles.
[http://i.imgur.com/zFhiDR8.png] picture showing the fields.
So everytime a new row gets created (even though there will always be 3), a new form appears in the administration panel.
Now, the problem that I have is that only the last field gets updated.
For example, I type information in all 3 forms, but only the last form gets the updated information shown on the news page when pressing the submit button according to the corresponding form. The updated information is also not getting added in the database.
If I type info in the first content field (inhoud) and press update, it will only check if the last form is updated.
Thinking about it, this would mean that my code only checks if the last id of the database, right?
For testing, I added a new row in the database with an auto-incrementing id of 4. And the result is that only the fourth id is checked for updating.
It also says in my error checker:
"NO RECORDS UPDATED ... ... ... WHERE ID=9"
This is all the information I could think of to put in here.
This is my php code:
<?php
session_start();
if(!isset($_SESSION['gebruiker'])){
header ("Location: admin_login.php");
}
else{
require_once 'db_config.php';
$query = "
SELECT
*
FROM
gip_home_nieuws";
$result = mysql_query($query);
if(!$res = mysql_query($sql))
{
trigger_error(mysql_error().'<br />In query: '.$sql);
}
elseif(mysql_num_rows($res) == 0)
{
echo 'Geen resultaten gevonden';
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Pagina's updaten</title>
<link href="admin_page1_css.css" rel="stylesheet" type="text/css">
</style>
</head>
<body>
<div id="container">
<div id="cont_header">
<div id="header">
<div id="header_logo"><img src="images/logo.png" width="200" height="110"></div>
<div id="header_slogan">We secure your future, the easy way</div>
<div id="knop_cont">
<div class="navigatie_knop" id="knop_nieuws">Nieuws</div>
<div class="navigatie_knop" id="knop_overons">Over ons</div>
<div class="navigatie_knop" id="knop_producten">Producten</div>
<div class="navigatie_knop" id="knop_winkel">Winkel</div>
<div class="navigatie_knop" id="knop_contact">Contact</div>
<div class="navigatie_knop" id="knop_uitloggen">Uitloggen</div>
</div>
</div>
</div>
<div id="divider1"></div>
<div id="cont_inhoud">
<div id="contact1">
<div class="contact_titel id="contact1_t>Administratie</div>
<div id="contact1_c">
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<?php
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$nieuws_date = $row['nieuws_date'];
$nieuws_titel = $row['nieuws_titel'];
$nieuws_content = $row['nieuws_content'];
?>
<td width="100"></td>
</tr>
<tr>
<td width="100">id</td>
<td><input class="input1" name="form_id" type="text" value="<?=$id?>"></td>
</tr>
<tr>
<td width="100">Datum</td>
<td><input class="input1" name="form_date" type="text" value="<?=$nieuws_date?>"></td>
</tr>
<tr>
<td width="100">Titel</td>
<td><input class="input2" name="form_titel" type="text" value="<?=$nieuws_titel?>"></td>
</tr>
<tr>
<td width="100">Inhoud</td>
<td><textarea class="input3" name="form_content" type="text"><?=$nieuws_content?></textarea></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<p><input type="submit" name="updaten" value="gegevens updaten"/>
<?php } ?></p>
</td>
</tr>
</table>
</form>
<?php
if(isset($_POST[updaten]))
{
$id2 = $_POST['form_id'];
$nieuws_date2 = $_POST['form_date'];
$nieuws_titel2 = $_POST['form_titel'];
$nieuws_content2 = $_POST['form_content'];
$sql = "
UPDATE
gip_home_nieuws
SET
nieuws_date = '".$nieuws_date2."',
nieuws_titel = '".$nieuws_titel2."',
nieuws_content = '".$nieuws_content2."'
WHERE
id=$id2
";
}
if(!$res = mysql_query($sql)) {
trigger_error(mysql_error().'<br />In query: '.$sql);
}
elseif(mysql_affected_rows() == 0) {
echo 'Geen records gegwijzigd. <br />Query: '.$sql;
echo"<a href=\"index.php\">Terug</a";
}
else
{
echo 'Update was succesvol!';
echo"<a href=\"index.php\"<br><br>>Terug</a";
}
?>
</div>
</div>
</div>
<div id="divider2"></div>
<div id="footer">
<div id="cont_footer">
<div id="footer_info">© Belgian Space Industries 2016</div>
</div>
</div>
</div>
<?php } ?>
</body>
</html>
I would really appreciate some help!
EDIT: seeing some posts with comments saying I shouldn't use mysql_* functions, I was teached to use MYSQL_* functions.
So sorry if there is confusion about this, but I can't really do something about this!
If you run this code and fill in each text input what happens when you submit the form?
<?php
var_dump($_POST)
?>
<form method="POST">
<input type="text" name="foo">
<input type="text" name="foo">
<input type="text" name="foo">
<input type="submit">
</form>
As all three of those foo fields above share the same name, when you POST, only one of the foo input's value will be available (it will clobber the other two).
You need to create three separate forms by creating each form inside your loop. Currently you have one form (your form html tags surround the loop).
You want something more akin to this:
<?php for($i=0; $i<3; $i++ ) { ?>
<form method="POST">
<table>
<tr>
<td>
Foo:
</td>
<td>
<input type="text" name="foo">
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit">
</td>
</tr>
</table>
</form>
<?php } ?>
Swap out the for for your while.
You should at least escape submitted values within your queries to reduce the chances of sql injection.
$sql = "
UPDATE
foo_table
SET
bar_field = '".mysql_real_escape_string($bar_value)."',
WHERE
baz_field = $baz_value
";
As others have pointed out the mysql functions are deprecated in PHP 5.5.0, and removed in PHP 7.0.0. Mysqli is a similar an alternative extension.

PHP calculator results in a new page? PHP first attempt

I'm trying to get the website to send the calculation results to another page. The code below is working but I have no idea how to get the rows with the results to be shown in a new page.
I know that i have to change the action below to /mynewpage
But I just want the results not the whole table.
I have no idea what to do to the code to make it show the results only in a new page. IF everything statys in the same page the calculator works well.
It's my first attempt with PHP, I clearly have no idea of what I'm doing. Many thanks in advance.
<?php
if (isset($_POST['valuea'])) $valuea = $_POST['valuea'];
if (isset($_POST['valueb'])) $valueb = $_POST['valueb'];
if (isset($_POST['valuec'])) $valuec = $_POST['valuec'];
if (isset($_POST['valued'])) $valued = $_POST['valued'];
if (isset($_POST['valuee'])) $valuee = $_POST['valuee'];
$balance = $valuec * $valuee;
$newphone = $valuea;
$total = $balance + $valuea;
$total2 = $balance + $valueb;
echo <<<_END
<form method='post' action='/'>
<table border='0' width='500px' cellpadding='3' cellspacing='1' class="table">
<tr class="calcheading"><td colspan="2"><strong>CALCULATOR</strong></td></tr>
<tr class="calcrow"><td>Phone Value:</td><td align="center"><input type='text' name='valuea' value="$valuea"/></td></tr>
<tr class="calcrow"><td>Phone upfront cost:</td><td align="center"><input type='text' name='valueb' value="$valueb"/></td></tr>
<tr class="calcrow"><td>Monthly contract cost:</td><td align="center"><input type='text' name='valuec' value="$valuec"/></td></tr>
<tr class="calcrow"><td>Contract duration:</td><td align="center"><input type='text' name='valued' value="$valued"/></td></tr>
<tr class="calcrow"><td>No. months left in the contract:</td><td align="center"><input type='text' name='valuee' value="$valuee"/></td></tr>
<tr class="submit"><td colspan="2"><input type='submit' value='Calculate'/></td></tr>
_END;
?>
<tr class="calcheading"><td colspan="2"><strong>OPTION 1 - PAY REMAINING OF THE CONTRACT AND BUY SAME PHONE UNLOCKED</strong></td></tr>
<tr class="calcrow">
<td><i>Payment left to network:</td>
<td align="center"><input type="text" value="<?php echo round($balance)?>"></td></i>
</tr>
<tr class="calcrow">
<td><i>New unlocked phone:</td>
<td align="center"><input type="text" value="<?php echo round($newphone)?>"></td></i>
</tr>
<tr class="calcrow">
<td><i>TOTAL:</td>
<td align="center"><input type="text" value="<?php echo round($total)?>"></td></i>
</tr>
<br>
<tr class="calcheading"><td colspan="2"><strong>OPTION 2 - PAY BALANCE LEFT AND GET SAME PHONE ON A NEW CONTRACT*</strong></td></tr>
<tr class="calcrow">
<td><i>Payment left to network:</td>
<td align="center"><input type="text" value="<?php echo round($balance)?>"></td></i>
</tr>
<tr class="calcrow">
<td><i>New contract phone initial cost:</td>
<td align="center"><input type="text" value="<?php echo round($valueb)?>"></td></i>
</tr>
<tr class="calcrow">
<td><i>TOTAL:</td>
<td align="center"><input type="text" value="<?php echo round($total2)?>"></td></i>
</tr></table>
</form>
You can either send the values in a form and receive them on the other page using
$value1 = $_GET['value1'];
$value2 = $_GET['value2']; // etc
The other method would be saving them in a session variable, at the top of any pages where you wish to use session variables, call session_start(), then save them
$_SESSION['value1'] = $value1;
Then in another page, you can call them by simply
echo $_SESSION['value1'];
I'm not sure what you mean by new page? If you have a script like process.php that has that code then you can add session_start(); as your first line after the php start tag. By using $_Session['result']=$calc_result; on the 'process.php' you will store the value in your session. In the 'new page' script you call session_start(); again and you can get the stored value by saying $_Session['result'].
There are many ways to print your answers on a new page but lets keep it simple: A good way to do it would be for you to separate out the HTML form that posts the values and the php calculation logic on two different pages. So for example, your HTML form is in one file values.php (does not have any php code, you can name it with a .html prefix as well) and the php code is in another file calc.php. Now, to your form, specify an action such as
<form method='post' action='calc.php'>
This will post all the values to calc.php where your calculation code is and you can display the results however you please (not limited to a form again) but in a table or so on. Once you learn ajax, you'll never want to come back to doing this.
Here is a working barebones example: http://runnable.com/VEKvtTTrkXFwjAwL/calculator555-for-php

Best practice in adding form row

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)

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