I have a table in database in which there is a column named roll_no, there are other four columns in the table. I am having a form to insert data into this table. I want to display this form x number of times, where x is number of distinct values of roll_no. That means if roll_no have 50 distinct values then the form will be displayed for 50 times on the same page. And in the form the roll_no field should be filled automatically with the value fetched from the database.
The other 4 fields are start_date, end_date, total_lectures, attended_lectures.
suppose start_date = 7th and end_date = 20 so there are total 13 lectures and out of which roll_no 1 attended 10 lectures and roll_no 2 attended 7 lectures and so on. The teachers fills the data like this in the form and then submit the form and data gets updated in the table. the combination of roll_no, start_date and end_date together serves as primary key.
If you have used phpmyadmin then you know that when we click on insert it shows two different forms to insert data.
I also want to accomplish something like this but the number of forms will be about 60 maximum.
I can't for the life of me figure out what you're trying to do, but if I understand you correctly, you want to print something as often as there are distinct values in the database.
(Pardon me, but I still use the old-school MySQL functions so if you're using the newer ones you might need to change this somewhat.)
$distinct_query = mysql_query("
SELECT DISTINCT row_no
FROM table_name
");
for ($i = 0; $i < mysql_num_rows($distinct_query); $i++) {
?>
All the stuff you want to print, where <?php print $i; ?> is the iteration of your form.<br />
<?php
}
Please note that this code is untested.
You could simply add a unique number to each form element as you ouput each sub-form
1. <input type="text" name="roll_no_1" ... />
<input type="text" name="start_date_1" ... />
etc...
2. <input type="text" name="roll_no_2" ... />
<input type="text" name="start_date_2" ... />
etc...
...
50. <input type="text" name="roll_no_50" ... />
<input type="text" name="start_date_50" ... />
etc...
or, if you trust the users to not mangle the form, you can use PHP's array syntax for form fields:
1. <input type="text" name="roll_no[]" ... />
<input type="text" name="start_date[]" ... />
2. <input type="text" name="roll_no[]" ... />
<input type="text" name="start_date_[]" ... />
...
50. <input type="text" name="roll_no[]" ... />
<input type="text" name="start_date[]" ... />
Either way works. The first has the benefits of guaranteeing that all the related fields have the same "subscript" identification within the name. The other one makes it simpler to simply do foreach ($_POST['roll_no'] as $idx => $val) { ... }
Related
I have been searching this for the last couple of hours and there are a few very similar questions and answers but none are quite working for my situation. What I'm trying to do is insert a list of songs set to the same value for two columns, one per row, and with a couple of options set via radio buttons. The latter is the reason why I can't just write all of the songs in a textarea and split them.
This is what the form looks like (obviously not fully designed)
There are only three there now while I get it working, in reality an unlimited amount may be added via javascript.
And the code:
<form action="" method="post">
<label>Session ID</label>
<input type="text" name="session-id"><br>
<label>Songs</label><br>
<input type="text" name="song-key[]"><input type="checkbox" name="is-partial[]"><input type="checkbox" name="is-jam[]"><br>
<input type="text" name="song-key[]"><input type="checkbox" name="is-partial[]"><input type="checkbox" name="is-jam[]"><br>
<input type="text" name="song-key[]"><input type="checkbox" name="is-partial[]"><input type="checkbox" name="is-jam[]"><br>
<input type="text" name="update-date" value="<?php echo date(" Y-m-d H:i:s ");?>" hidden readonly><br>
<input type="submit" name="submit" value="Submit">
</form>
The desired result, assuming the ID has been set and a unique song entered for each of the them, and whatever variety on the radio buttons, would be three table rows. session-id and update-date would all be the same value, the rest would be unique based on entry.
This is what I currently have, but it only inserts the last of the three songs.
for ($i=0; $i < count($_POST['song-key']); $i++ ) {
$sessionkey = mysqli_real_escape_string($connection, $_POST["session-key"]);
$songkey = mysqli_real_escape_string($connection, $_POST["song-key"][$i]);
$partial = mysqli_real_escape_string($connection, isset($_POST['is-partial'][$i])) ? 1 : 0;
$jam = mysqli_real_escape_string($connection, isset($_POST['is-jam'][$i])) ? 1 : 0;
$updated = mysqli_real_escape_string($connection, $_POST["update-date"]);
$sql = "INSERT INTO session_songs (session_key, song_key, is_partial, is_jam, last_updated)
VALUES ('$sessionkey', '$songkey', '$partial', '$jam', '$updated')";
}
What do I need to change to ensure all three (or more) are entered?
If you alter your input names, you can get a more useful $_POST array.
<input type="text" name="songs[0][key]">
<input type="checkbox" name="songs[0][is-partial]">
<input type="checkbox" name="songs[0][is-jam]"><br>
<input type="text" name="songs[1][key]">
<input type="checkbox" name="songs[1][is-partial]">
<input type="checkbox" name="songs[1][is-jam]"><br>
<input type="text" name="songs[2][key]">
<input type="checkbox" name="songs[2][is-partial]">
<input type="checkbox" name="songs[2][is-jam]"><br>
With specified keys, the checkbox type inputs will match up properly with the text inputs, where they way you have it now, they will not*, because only checked checkboxes are submitted to PHP. (Try only checking "is-partial" in the second and "is-jam" in the third row, and then var_dump($_POST), and you'll see that they both have index 0.)
If your form is structured like that, you can insert your records using a foreach loop instead of a for loop.
foreach ($_POST['songs'] as $song) {
$key = $song['key'];
$partial = isset($song['is-partial']) ? 1 : 0;
$jam = isset($song['is-jam']) ? 1 : 0;
// do the insert inside the loop rather than just building the SQL
}
The reason you're currently only getting the last one is that you're defining the SQL string inside the loop, but without executing the statement in the loop, you'll only get the values from the last iteration of the loop. Move your query execution inside the loop and you should get all three rows.
*unless they are all checked
I have an entry form to post data into a MySQL database (with a submit button) and it works fine. Now I want to have edit, next & previous buttons on it, to get next and previous record and also to edit them if needed.
I have searched on the internet but could not find a solution according to my requirement.
First of all, you should ensure that you have a column for the record ID that's an INTEGER, a PRIMARY KEY, and set to AUTOINCREMENT, let's call this `recordID`.
Let's take an example person table schema:
CREATE TABLE people (
recordID INTEGER PRIMARY KEY AUTOINCREMENT,
firstName VARCHAR(140) NOT NULL,
middleNames VARCHAR(250),
lastName VARCHAR(140) NOT NULL,
dateOfBirth DATE NOT NULL
);
To query the first record, we can do:
SELECT * FROM people WHERE recordID = 1;
Now to edit the record, we can do:
UPDATE people SET firstName="NewName" WHERE recordID = 1;
Next we build an HTML form to display/edit this data in.
<form action="#" method="post">
<input type="text" readonly="readonly" name="recordID" id="recordID" />
<input type="text" name="firstName" id="firstName" />
<input type="text" name="middleNames" id="middleNames" />
<input type="text" name="lastName" id="lastName" />
<input type="date" name="dateOfBirth" id="dateOfBirth" />
<input type="submit" />
</form>
Last of all you create some next and previous buttons to traverse through the records and populate the input fields, and then an edit button that sends the data to the server for it to update the database.
If you're feeling extravagant, you could use SQL's INSERT INTO ... ON DUPLICATE KEY UPDATE. E.g.:
INSERT INTO people (firstName, lastName, middleNames, dateOfBirth) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE firstName="?", lastName="?", middleNames="?", dateOfBirth="?";
In order to do an "in-place edit", you could add a variable to the querystring.
For example, if you want to edit recordID = 3, you could have the URL as: http://yourserver.com/person/?id=3&edit.
On the serverside you can check for edit by using isset($_GET['edit']). If that returns true, than run your edit code and populate the fields/enable the edit functionality.
I am creating database for checkbox values with different column. How to insert the db?because I have stored the check box values in different column name,my column name is allsubject,science,maths.
my questions are:
1.if user checks allsubject,the value is inserted, the other two column is going with null values.
2.is this way of storing value is correct because among three check box user select any values, I want to clarify this?
3.More over I want to store the values in this manner only
dbstructure:
**allsubject science maths**
allsubject science maths
allsubject science
maths
allsubject
Myform:
<form name="f1" action="" method="post">
Student Name:<input type="text" name="sname" value=""/>
All Subject:<input type="checkbox" name="allsubject" value="allsubject"/>
Science<input type="checkbox" name="science" value="science"/>
Maths<input type="checkbox" name="maths" value="maths"/>
<input type="submit" name="submit" value="submit"/>
</form>
**myphp value is:**
<?php
mysql_connect('localhost','root','');
mysql_select_db('checkbox');
if(isset($_POST['submit'])=='submit')
{
$allsubject=$_POST['allsubject'];
$science=$_POST['science'];
$maths=$_POST['maths'];
$sql=mysql_query("insert into studentinfo (allsubject,science,maths) values ('".$allsubject."','".$science."','".$maths."')");
}
?>
if(isset($_POST['allsubject']){$allsubject=1;} (OR VALUE YOU WANT)
This is as detailed as possible.
I have 2 forms used for pre-registration for an upcoming game. Depending on which form someone fills out, will depend on the side they are registering for. Regardless both forms insert data into the same table and everything is working great for that part.
The issue Im running into is when I try to display the count for the number of times a certain side (red or blue) is used in the database, nothing is displayed.
The end result should show something like "3 vs 2" on the page so people can see it and have it update automatically when new info is submitted.
Where 3 is the current total of times the "blue" side has been chosen and 2 is the current total of times the "red" side has been chosen.
The table name is "game_checkin" and the column for the sides is "side". The two possible answers are "red" or "blue". Both are hidden fields.
Both of my forms looks like this:
<form action="/pre-reg.php" method="post">
<input type="text" name="name" placeholder="Name" required><br/>
<input type="text" name="age" placeholder="Age" maxlength="2" required><br/>
<input type="text" name="location" placeholder="City, ST" required><br/>
<input type="text" name="callsign" placeholder="Callsign" maxlength="12" required>
<input type="hidden" name="date" value="<?php echo date ('m-d-Y');?>">
<input type="hidden" name="side" value="blue"> red has a value of "red"...
<input type="submit" value="Check In">
</form>
This is the current code I use. I supplied an open area for anyone wanting to tell me what I'm missing.
<?php
$con=mysqli_connect("localhost","user","password","dbname");
// Verify Connection - duh!
if (mysqli_connect_errno())
{
echo "You kicked my doge and now he no pee straight:<br/>"
. mysqli_connect_error();
}
///// SCHOOL ME HERE \\\\\
mysqli_close($con);
?>
Like I mentioned,
I need to know how to display the total "number" of users that chose "blue" vs "red".
Then echo it to the page, for example like: 3 vs 2
my resources: mysql 5, php 5, phpmyadmin, linux os, paid hosting...
I have been stuck on this for the past few days trying to find an answer everywhere I could look. If you can help, it will be greatly appreciated.
It's actually kinda trivial...
$sql = mysqli_query($con,"select `side`, count(*) from `game_checkin` group by `side`");
$sides = array("blue"=>0,"red"=>0);
while($row = mysqli_fetch_row($sql)) $sides[$row[0]] = $row[1];
echo $sides['blue']." vs ".$sides['red'];
I have a variable number of fields in a form.
The number of text fields are defined by the user with a function in jquery, but the final code of the form (example) is this:
<form id='form_educ' name='form_educ' method='post' action='form/educ.php'>
<div id='educ'>
<input type='text' name='date1' id='date1'/>
<input type='text' name='date2' id='date2'/>
<input type='text' name='date3' id='date3'/>
<input type='text' name='date4' id='date4'/>
....
</div>
<input type='submit' name='form_educ' value='Refresh'/>
</form>
These text fields when added by the user is create a sql INSERT TO (in another file):
$date = clean($_GET['date']);
"INSERT INTO educ (index_of_form, date, email) VALUES('$index', '', '" .mysql_real_escape_string($_SESSION['SESS_EMAIL']). "')";
$date is date1, or date2, or date3 or date4 (example).
Now in the file educ.php I want to update all text fields in the mysql database.
Usually it is a
$example = clean($ _POST ['example']);
I can do an update in the table and is resolved.
But in my case how can I get all the values โโof the text field on the form and set the $_POST var if the number of fields is variable (could be date1, date2, date3, date4)?
I can think of no reason why form field name should be a unknown variable. Unless you're dealing with repeatable fields, in which case you would use an array like dates[], and you'd know what to expect in the process script.
For additional info see for example: http://www.web-design-talk.co.uk/58/adding-unlimited-form-fields-with-jquery-mysql/
Word of warning for future. When you make the field repeatable, allow users also to delete the fields they might have accidentally insertet. Watch out in the process script missing array keys (numerical index from 0โ10 might be missing some values if the user deleted some form fields before submitting). You can reset the array keys with the array_merge function. Missing keys is an issue if you have two arrays you are trying to add into database as syncronized.
Updated to answer the comment.
Sorry, I don't undestand your question. You don't necessarily have to use hidden field. What you need is a database structure to match your forms function: to support one to many relationship. After all you are inserting multiple dates that relate to one person, or some specific event type, or what ever. Lets assume one user wants to add his three favorite dates in the world. Your form's source code looks like:
<input type="text" name='dateLover' id='dateLover'/>
<input type="text" name="dates[]" id="date1" /> //you need a increasing variable for these id numbers (or dont't put the id at all)
<input type="text" name="dates[]" id="date2" />
<input type="text" name="dates[]" id="date3" />
In addition you could have more fields such as <input type="text" name="extra" />. In submitted $_POST array there would be variables and arrays like: $_POST['dateLover'], $_POST['date'][0], $_POST['date'][1], $_POST['date'][2], $_POST['extra']. You'd take the non-repeatable values straight out of the $_POST array but you need a foreach (or some else loop) to handle the dates array.
Your database has to contain two tables (structure simplified):
person: id, dateLover
date: id, dateLover FK to person.dateLover, date
In your process script you have to:
insert a new dateLover to person and use last_insert_id to get his id
use a foreach to insert new dates to table date (with a dateLover's id as FK)
This all is pretty well demonstrated in the link I supplied earlier. For now, it's hard to give an complete example without undestanding the actual problem.
Update 2.
You are serializing the form, not the div's. So your (dynamically generated) could look like this:
<form id="form_educ" name="form_educ" method="post" action="form/educ.php">
<div id="educ">
<div><!--This is for layout only-->
<input type="text" name="dates[]" id="date0" />
<input type="text" name="names[]" id="name0" />
</div>
<div>
<input type="text" name="dates[]" id="date1" />
<input type="text" name="names[]" id="name1" />
</div>
<div>
<input type="text" name="dates[]" id="date2" />
<input type="text" name="names[]" id="name2" />
</div>
</div>
<input type="submit" name="form_educ" value="Refresh" />
</form>โ
And in your process file you take these arrays from $_POST array and insert them into database maybe like this (with properly escaped and checked values of course...):
//dynamic part of the query
$qEnd = '';
$i = -1;
//this is static part of the query
$qBeginning = "INSERT INTO `date` (`id`, `date`, `name`) VALUES ";
foreach ($_POST['dates'] as $key => $date){
$i++;
$qValues[$i] = "(null, '{$date}', '{$_POST[names][$i]}')"; //never do this, always check values...
//value sets are concatenated one after another to the $qEnd
$qEnd .= $qValues . ',';
}
//combine the query parts and remove extra "," from the end
$q = $qBeginning . rtrim($qEnd, ',');
//now the (single) query ($q) is ready to be executed, echo it just for the fun of it
id should be auto increment field, or this kind of stuff doesn't work on the fly.
Again, this all should be clear in the jQuery link example so please read it carefully.
You should know all of the possible columns that could be updated before hand. Just check to see if those are set in the $_POST variable, then if they are append the insert or update statement with those values.
DANGER: Just looping on the $_POST variable looking at all params may end up inserting not database related POST fields into your insert statement and breaking.
Also when using these methods, be aware of SQL Injection, and use parameterized queries and never directly insert POST variable names or values into the SQL Statment.