I've got a problem with inserting multiple row to one table.
I've got a 3 tables:
1. student with id_student
2. ankieta with id_ankieta
3. student_ankieta with id_student and id_ankieta
I want to choose students from database using select or checkbox and choose one id_ankieta. After confirming, there are rows created in table (student_ankieta).
Now I can choose students but when I confirm, only one student gets added to the database.
Can anyone help me corect the code?
<?php
echo'<form method="post" action="student_ankieta.php">
<div class="box" style="margin:0 auto; top:0px;">
<h1>Student - ankieta:</h1>
<label>
<span><br/>Ankieta:</span>
</label>
<select class="wpis" name="id_ankieta">
<option>wybierz ankiete</option>';
$query = "SELECT * FROM ankieta";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['id_ankieta'].'">' . $row{'rok_akademicki'}.' '. $row{'semestr_akademicki'}.' '.$row{'active_ankieta'} .'</option>';
}
echo '
</select>';
$query = "SELECT * FROM student";
$result = mysql_query($query);
echo'
<label>
<span><br/>Wybierz stundentów:</span>
</label>
<select multiple="multiple" name="id_student[]" size="10">';
while ($row = mysql_fetch_assoc($result))
{
echo '<option class="wpis" value="'.$row['id_student'].'" />'.$row{'pesel'}.' '. $row{'nazwisko'}.' '.$row{'imie'} .'</option>';
}
echo'<br/><input class="button" type="submit" value="Dodaj ankiete" name="dodaja">';
if(isset($_POST['dodaja']))
{
$id_ankieta = $_POST['id_ankieta'];
if(empty($_POST['id_ankieta']))
{
echo '<p style="margin-top:10px; font-size:75%; font-family: Calibri; color: red; text-align:center;">Musisz wypełnić wszystkie pola.</p>';
}
else
{
$id_student = $_POST['id_student'];
for ($i = 0; $i < count($id_student); $i++)
{
$id_student = $id_student[$i];
mysql_query("INSERT INTO student_ankieta (id_student, id_ankieta) VALUES ('" . $id_student . "','$id_ankieta')");
}
}
}
echo'</div></form>';?>
Put all students in to an array with the key = id_student
$query = "SELECT * FROM ankieta";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
students[$row['id_student']] = array($row['pesel'],$row['nazwisko'],$row['imie'];
}
If the form was posted the confirm will = 1 (from hidden input)
When first enter script "confirm will = 0
When zero, display all student with a check box with a name which includes the id_student in the format of n-i_student.
if intval($_POST['confirm']) = 0){
echo '<form action = "confirm.php" method="post"><input type="hidden" name="confirm" value="1"/><table>';
foreach ($students as $id => val){
echo "<tr><td><input type=\"checkbox\" name=\"n-$id\" value=\"1\" /> Select </div></td>$val[0]<td>$val[0]</td><td>$val[1]</td><td>$val[2]</td></tr>";
}
echo '</table></form>';
}
When confirm = 1
The checkboxes that were checked are inserted.
Check each post value for a key the starts with "n-"
get the rest of the key value after the n- for the id_student value.
Still 1 Major Problem, I do not know where to get the $id_ankieta'
And match it with the id_student.
I left that value as $val[???]
elseif intval($_POST['confirm']) = 1){
foreach ($_POST as $k =>$val){
if (inval($val) == 1 && substr($k,0,2) == 'n-'){
$id = substr($k,2);
$sql = mysql_query("INSERT INTO student_ankieta (id_student, id_ankieta) VALUES ('$id','" . $students[$id][$val[???]] . "')");
}
}
}
Related
I have the facility to update what I call 'documents' (ver similar to creating a post) on my cms which works fine but I have introduced categories where the documents are associated to them. Now I have managed to bind them when creating the doc from new but when trying update them I am getting a bit stuck. I am using checkboxes to show the list of categories and when selected it updates a join table which uses the doc_id and the cat_id.
Here is the script for updating the doc:
<?php
include ('includes/header.php');
require ('../../db_con.php');
echo '<h1>Document Edit</h1>';
// Check for a valid document ID, through GET or POST:
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // From view_docs.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) { // Form submission.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<p class="error">This page has been accessed in error.</p>';
exit();
}
// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();
// Check for a document name:
if (empty($_POST['doc_name'])) {
$errors[] = 'You forgot to enter your document name.';
} else {
$dn = mysqli_real_escape_string($dbc, trim($_POST['doc_name']));
}
// Check for a document content:
if (empty($_POST['doc_content'])) {
$errors[] = 'You forgot to enter your last name.';
} else {
$dc = mysqli_real_escape_string($dbc, trim($_POST['doc_content']));
}
if (empty($errors)) { // If everything's OK.
// Test for unique doc title:
$q = "SELECT doc_id FROM docs WHERE doc_name='$dn' AND doc_id != $id";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) == 0) {
// Make the query:
$q = "UPDATE docs SET doc_name='$dn', doc_content='$dc', doc_name='$dn' WHERE doc_id=$id LIMIT 1";
$r = mysqli_query ($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
$doc_id = mysqli_insert_id($dbc);
$query = "UPDATE doc_cat_join (cat_id,doc_id) VALUES ";
$cat_ids = $_POST['cat_id'];
$length = count($cat_ids);
for ($i = 0; $i < count($cat_ids); $i++) {
$query.='(' . $cat_ids[$i] . ',' . $doc_id . ')';
if ($i < $length - 1)
$query.=',';
}
// Print a message:
echo '<p>The document has been edited.</p>';
} else { // If it did not run OK.
echo '<p class="error">The document could not be edited due to a system error. We apologize for any inconvenience.</p>'; // Public message.
echo '<p>' . mysqli_error($dbc) . '<br />Query: ' . $q . '</p>'; // Debugging message.
}
} else { // Already used.
echo '<p class="error">The document name has already been used.</p>';
}
} else { // Report the errors.
echo '<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br />\n";
}
echo '</p><p>Please try again.</p>';
} // End of if (empty($errors)) IF.
} // End of submit conditional.
// Always show the form...
// Retrieve the document's information:
$q = "SELECT * FROM docs WHERE doc_id=$id";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) { // Valid document ID, show the form.
// Get the document's information:
$row = mysqli_fetch_array ($r, MYSQLI_NUM);
// Create the form:
echo '<form action="edit_doc.php" method="post">
<p>Document Name: <input type="text" name="doc_name" size="15" maxlength="15" value="' . $row[1] . '" /></p>
<textarea name="doc_content" id="doc_content" placeholder="Document Content" style="display: none;"></textarea>
<iframe name="editor" id="editor" ></iframe>'
?>
<div class="row">
<div class="col-group-1">
<?php
$q = "SELECT * FROM cats";
$r = mysqli_query ($dbc, $q); // Run the query.
echo '<div class="view_body">';
// FETCH AND PRINT ALL THE RECORDS
while ($row = mysqli_fetch_array($r)) {
echo '<br><label><input type="checkbox" name="cat_id[]" value="' . $row['cat_id'] . '">' . $row["cat_name"] . '</label>';
}
echo '</div>';
?>
</div>
</div>
<br><br>
<input onclick="formsubmit()" type="submit" value="Update Document" name="submit"/>
<?php echo'
<input type="hidden" name="id" value="' . $id . '" />
</form>
<br><br>Back to docs list';
} else { // Not a valid document ID.
echo '<p class="error">This page has been accessed in error.</p>';
}
?>
<?php
mysqli_close($dbc);
?>
So I have three tables:
docs
doc_id
doc_name
doc_content
cats
cat_id
cat_name
doc_cat_join
doc_id
cat_id
the join table related the doc_id and cat_id which then associates them together. I am guessing in my script when I update a doc it will need to delete the rows and then re-insert them? I just need to know a way or the easiest way of updating the join table as I am a tad stuck...
In case of checkbox update you need to delete previous stored checkbox of with appropriate id and insert new one you can't update checkbox as we can't predict how many checkbox will be selected by user....
Case:
It may happen that user remove one checkbox at update time so you will never know which one to be deleted.......
In your code...
docs
doc_id
doc_name
doc_content
cats
cat_id
cat_name
doc_cat_join
id
doc_id
cat_id
here you have to delete old checkbox of updation doc,
DELETE FROM doc_cat_join WHERE cat_id = some_id
next you can insert selected checkbox as you are inserting first time...
I have 3 drop downs I want to display whatever the user will select after he/she has selected a function or a scrpt will do but it must be within the script
<?php
$resource_names = mysql_query("SELECT DISTINCT NAME FROM selections ORDER BY id ASC");
$names = array();
while($row = mysql_fetch_row($resource_names)){
$names[] = $row[0]
}
$resource_surnames = mysql_query("SELECT DISTINCT SURNAME FROM selections ORDER BY id ASC");
$surnames = array();
while($row = mysql_fetch_row($resource_surnames)){
$surnames[] = $row[0];
}
$resource_emails = mysql_query("SELECT DISTINCT EMAIL FROM selections ORDER BY id ASC");
$emails = array();
while($row = mysql_fetch_row($resource_emails)){
$emails[] = $row[0];
}
if(count($emails) <= 0 || count($surnames) <= 0 || count($emails) <= 0){
echo 'No results have been found.';
} else {
// Display form
echo '<form name="form" method="post" action="test.php">';
//Names dropdown:
echo '<select name="id" id="names">';
foreach($names as $name) echo "<option id='$name'>$name</option>";
echo '</select>';
//Surnames dropdown
echo '<select name="id" id="surnames">';
foreach($surnames as $surname) echo "<option id='$surname'>$surname</option>";
echo '</select>';
//Emails dropdown
echo '<select name="id" id="emails">';
foreach($emails as $email) echo "<option id='$email'>$email</option>";
echo '</select>';
echo "<button id='write_in_div'>Click me!</button>";
echo '</form>';
}
?>
Something that will call the write_in_div When Click me! button is press or any other method that can be used to display 3 selection user selected
The Output should be something like You select 1) Name 2)Surname and Email
You have an error in your html selects each select has the same name "id" they each need to be unique so you can detect then.
You need to detect if the user has submitted the form
if(isset($_POST["select_name"])) {
echo $_POST["select_name"];
}
There is a big mistake on you form.
In a form, each select and input MUST have a unique name. You need this name to retrieve the submitted value back in your php script.
I suppose you have this:
<?php
$resource_names = mysql_query("SELECT DISTINCT NAME FROM selections ORDER BY id ASC");
$names = array();
while($row = mysql_fetch_row($resource_names)){
$names[] = $row[0]
}
$resource_surnames = mysql_query("SELECT DISTINCT SURNAME FROM selections ORDER BY id ASC");
$surnames = array();
while($row = mysql_fetch_row($resource_surnames)){
$surnames[] = $row[0];
}
$resource_emails = mysql_query("SELECT DISTINCT EMAIL FROM selections ORDER BY id ASC");
$emails = array();
while($row = mysql_fetch_row($resource_emails)){
$emails[] = $row[0];
}
if(count($emails) <= 0 || count($surnames) <= 0 || count($emails) <= 0){
echo 'No results have been found.';
} else {
// Display form
echo '<form method="post" action="test.php">';
//Names dropdown:
echo '<select name="names">';
foreach($names as $name) echo "<option id='$name'>$name</option>";
echo '</select>';
//Surnames dropdown
echo '<select name="surnames">';
foreach($surnames as $surname) echo "<option id='$surname'>$surname</option>";
echo '</select>';
//Emails dropdown
echo '<select name="emails">';
foreach($emails as $email) echo "<option id='$email'>$email</option>";
echo '</select>';
echo '<button id="write_in_div">Click me!</button>';
echo '</form>';
}
When the form is submitted, test.php will have the posted data: $_REQUEST['names'], $_REQUEST['surnames'] and $_REQUEST['emails'].
You just have to check the content of thoses vars and print them if not null.
Note1: ?> is useless at the end of a file.
Note2: be carefull about ' and " when writing an html file. The value of an html attribute is written with ", not '.
I am having problem adding up the values in a column with php.
These values where sent from checkboxes and i want to count only the values that where checked from the unit column.
Here is my code:
<?php
$id = $_POST['course'];
foreach($id as $value)
{
//echo $value;
$query = " SELECT * FROM french WHERE id= $value ";
$result = mysql_query($query) or die('Error, query failed');
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$course = htmlspecialchars($row['course_name']);
$code = htmlspecialchars($row['course_code']);
$unit = $row['unit'];
$status = $row['status'];
?>
Are you trying like this? Getting form array of form checkboxs and checking on database via ID's?
HTML FORM
Check 1 <input type="checkbox" name="val[]" />
Check 2 <input type="checkbox" name="val[]" />
PHP RESULT
$val = $_POST['val'];
$count = count($val);
foreach ($val as $val_res)
{
$query = 'SELECT * FROM french WHERE id='.$val_res;
}
I have multiple text boxes displaying a string corresponding to a row in the mysql database. I want to be able to change each string in the database by typing in the textbox and clicking submit.
So I create my text boxes with a while loop after connecting to the DB.
<form action="<?php $self ?>" form method="post">
<?php
$query = "SELECT * FROM `table` ORDER BY table.ID DESC";
$result = #mysql_query($query) or die('
ERR: The database returned an unexpected error.
');
$num=mysql_numrows($result);
$change="";
$i=0;
while ($i < $num) {
$post=mysql_result($result,$i,"post");
$id=mysql_result($result,$i,"ID");
$ts=mysql_result($result,$i,"timeStamp");
$page = html_entity_decode($post);
$output = stripslashes($page);
if ($output != "") {
echo '<textarea name="' . $id . '" rows="4" cols="70">' . $output . '</textarea><div class="time"><font face="monospace">' . $ts . '</font></div>';
} //creates tables for each filled entry with a name corrsponing to its auto-increment id.
$i++;
}
?>
<input name="send" type="hidden" />
<div class="mod">
<p><input class="master" type="submit" value="Mod" /></p></div><!--submit button is called "Mod"-->
</form>
</body>
</html>
Everything displays properly. If the database has 4 rows with text in them than it will display those 4, each in a separate text box.
Now I want to replace the text in the database with whatever the user enters in the text boxes. This is the code I tried. It does nothing.
<?php
$i=0;
while ($i < $num) {
$id=mysql_result($result,$i,"ID");
$post=mysql_result($result,$i,"post");
if (!isset($_POST[$id])) {
$_POST[$id] = "";
}
$change = $_POST[$id];
mysql_query("UPDATE 'database'.'table' SET 'post' = '$change' WHERE 'table'.'ID' ='$id';");
$i++;
}
Basically the loop will run once for every row in the table. For every text box, it should UPDATE 'database'.'table' with $_POST[1] for 'post' with ID '1', $_POST[2] for 'post' with ID '2', etc...
Instead nothing happens.
Any help would be appreciated.
As Prowla mentioned , you should use PDO instead of mysql_ functions.
Anyway, I improved your code and it suppose to work now:
<form action="<?php $self ?>" form method="post">
<?php
$query = "SELECT * FROM `table` ORDER BY table.ID DESC";
$result = #mysql_query($query) or die('Query error:'.mysql_error());
$num=mysql_num_rows($result);
$change="";
while($post = mysql_fetch_array($result))
{
/*
$post = array(
'post' => '....',
'ID' => '...',
'timeStamp' => '...'
);
*/
$page = html_entity_decode($post['post']);
$output = stripslashes($page);
if ($output != "") {
echo '<textarea name="posts['.$post['ID'].']" rows="4" cols="70">' . $output . '</textarea><div class="time"><font face="monospace">' . $post['timeStamp'] . '</font></div>';
} //creates tables for each filled entry with a name corrsponing to its auto-increment id.
}
?>
<input name="send" type="hidden" />
<div class="mod">
<p><input class="master" type="submit" value="Mod" /></p></div><!--submit button is called "Mod"-->
</form>
</body>
</html>
The php update file:
$query = "SELECT * FROM `table` ORDER BY table.ID DESC";
$result = #mysql_query($query) or die('Query error:'.mysql_error());
while($update_post = mysql_fetch_array($result))
{
$update = (isset($_POST[$update_post['ID']])) ? $_POST[$update_post['ID']] : "";
if($update != "")
{
mysql_query("UPDATE 'database'.'table' SET 'post' = '$update' WHERE 'table'.'ID' ='".$update_post['ID']."';");
echo "<!--POST ID ".$update_post['ID']." been updated-->\n";
}
}
I added an html comment (<!-- -->) so you can check if the update actually takes place.
This way you can debug your code. (you should also read about print_r , var_dump)
I am having a big issue.
This is the first time I sue a foreach and I do not even know if it's the right thing to use.
I have a textarea where my members can add some text.
They also have all the accounts where to send the posted text.
Accounts are of two types F and T.
They are shown as checkboxes.
So when a member types "submit" the text should be INSERTED in a specific table for EACH of the selected accounts. I thought php foreach was the right thing. But I am not sure anymore.
Please take in mind I do not know anything about foreach and arrays. So please when helping me, consider to provide the modded code =D . Thank you so much!
<?php
require_once('dbconnection.php');
$MembID = (int)$_COOKIE['Loggedin'];
?>
<form action="" method="post">
<p align="center"><textarea id="countable1" name="addit" cols="48" rows="10" style="border-color: #ccc; border-style: solid;"></textarea>
<br>
<?
$DB = new DBConfig();
$DB -> config();
$DB -> conn();
$on="on";
$queryF ="SELECT * FROM `TableF` WHERE `Active`='$on' AND `memberID`='$MembID' ORDER BY ID ASC";
$result=mysql_query($queryF) or die("Errore select from TableF: ".mysql_error());
$count = mysql_num_rows($result);
if ($count > 0)
{
while($row = mysql_fetch_array($result)) {
?><div style="width:400px; height:100px;margin-bottom:50px;"><?
$rowid = $row['ID'];
echo $row['Name'] . '</br>';
$checkit = "checked";
if ($row['Main'] == "")
$checkit = "";
if ($row['Locale'] =="")
$row['Locale'] ="None" . '</br>';
echo $row['Locale'] . '</br>';
if ($row['Link'] =="")
$row['Link'] ="javaScript:void(0);";
?>
<!-- HERE WE HAVE THE "F" CHECKBOXES. $rowid SHOULD BE TAKEN AND INSERTED IN THE FOREACH BELOW FOR ANY SELECTED CHECKBOX IN THE FIELD "Type".SEE BELOW -->
<input type="checkbox" name="f[<?php echo $rowid?>]" <?php echo $checkit;?>>
</div>
<?
}//END WHILE MYSQL
}else{
echo "you do not have any Active account";
}
$DB = new DBConfig();
$DB -> config();
$DB -> conn();
$queryTW ="SELECT * FROM `TableT` WHERE `Active`='$on' AND `memberID`='$MembID' ORDER BY ID ASC";
$result=mysql_query($queryTW) or die("Errore select TableT: ".mysql_error());
$count = mysql_num_rows($result);
if ($count > 0)
{
while($row = mysql_fetch_array($result)) {
?><div style="width:400px; height:100px;margin-bottom:50px;"><?
$rowid = $row['ID'];
echo $row['Name'] . '</br>';
$checkit = "checked";
if ($row['Main'] == "")
$checkit = "";
if ($row['Locale'] =="")
$row['Locale'] ="None" . '</br>';
echo $row['Locale'] . '</br>';
if ($row['Link'] =="")
$row['Link'] ="javaScript:void(0);";
?>
<!-- HERE WE HAVE THE "T" CHECKBOXES. $rowid SHOULD BE TAKEN AND INSERTED IN THE FOREACH BELOW FOR ANY SELECTED CHECKBOX IN THE FIELD "Type".SEE BELOW -->
<input type="checkbox" name="t[<?php echo $rowid?>]" <?php echo $checkit;?> >
</div>
<?
}//END 2° WHILE MYSQL
}else{
echo "you do not have any Active account";
}
?>
<input type="submit" value="submit">
</form>
<?
//WHEN CHECKBOXES "F" ARE FOUND, FOR EACH CHECKBOX IT SHOULD INSERT INTO TableG THE VALUES BELOW, FOR EACH SELECTED "F" CHECKBOX
if(!empty($_POST['addit']) && !empty($_POST['f'])){
$thispostF = $_POST['f'];
$f="F";
foreach ($thispostF as $valF)
//THE MOST IMPORTANT FIELD HERE IS "Type". THE ARRAY INSERT "on", I NEED INSTEAD THE VALUE $rowid AS ABOVE
$queryaddF="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$f."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
//WHEN CHECKBOXES "T" ARE FOUND, FOR EACH CHECKBOX IT SHOULD INSERT INTO TableG THE VALUES BELOW, FOR EACH SELECTED "T" CHECKBOX
if(!empty($_POST['addit']) && !empty($_POST['t'])){
$thispostT = $_POST['t'];
$t="T";
foreach ($thispostT as $valF)
//THE MOST IMPORTANT VALUE HERE IS "Type". THE ARRAY GIVES "on", I NEED INSTEAD THE VALUE $rowid AS ABOVE
$queryaddT="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$t."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
?>
foreach ($thispostT as $valF)
{
$queryaddT="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$t."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
please put start and ending bracket to your foreach loop and try i have not read the whole code but just found you missing the brackets. hope that helps you.
I think I know what you're doing...
You're going to need to do:
foreach($_POST as $key => $value) {
$type = substr($key,0,1);
$id = substr($key,1);
if($type == 't') {
// do insert for t table here
} else if($type == 'f') {
// do insert for f table here
}
}
I didn't test it but it should be something like this.
My suggestion is
create field name as t[] (array)
onchecked value will be passed on the next page
the form checkbox field should be like that
<input type="checkbox" name="t[]" value="< ?php echo $rowid?>" <?php echo $checkit;? > >
and when you Submit the form
GET THE VALUE and insert in to database;
< ?
if($_POST['t'])
{
foreach($_POST['t'] as $v)
{
queryaddT="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$t."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
}
? >