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());
}
}
? >
Related
I'm creating a simple survey and I want the values in the column to be just (1) one row and separated with "|". But the only problem is, how do I save those values that I've got from the $_POST into an array on my database? For example:
Male|Employed|Married| instead of this...
<?php
$cnt = 1; // VARIABLE FOR QUESTIONS //
$query = "SELECT * FROM questions";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_object($result))
{
$choices = explode ("|", $row->choices);
if(isset($_POST['submit_post']))
{ // eq - radio button name (choices) for $cnt - question # //
$choice = $_POST["eq$cnt"]; // What to do in this $_POST part? //
$query = "INSERT INTO users(answers)";
$query .= "VALUES ('{$choice}')";
$create_post_query = mysqli_query($connection, $query);
}
?>
<form action="" method="post">
<?php
if($row->num ==0)
{
$num=" ";
} else
{
$num=$row->num.". ";
}
?>
<p id="eqIdentify_<?php echo $cnt ?>"><strong><?php echo $num; echo $row->questions; ?></strong> <?php ?> <?php echo $cnt; ?>
<?php
// VARIABLE FOR CHOICES //
for($a=0;$a<count($choices);$a++)
{
?>
<br/><label><input type="radio" name="eq<?php echo $cnt;?>" value="<?php echo $choices[$a] ?>" /><?php echo $choices[$a]?></label>
<?php
}
?>
<?php
$cnt = $cnt + 1;
}
?>
<input type="submit" name="submit_post">
</form>
change your table structure so you have a field for each of the questions.
like
ID Question1 Question2
and then change your insert query such
INSERT INTO `answers`( `question1`, `question2`, `question3`, `question4`) VALUES ([value-2],[value-3],[value-4],[value-5])
But please please look in to PDO and prepared query's
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[???]] . "')");
}
}
}
I have two tables:
'courses' with these fields:COURSE_ID(auto
increment),start_date,end_date,title
'courses_students' with these fields:ID(auto
increment),COURSE_ID,STUDENT_ID.
I want to insert some values in my mysql table called "courses_students" from my other table called "courses".
Users can see in a page the data from 'courses'(courses names,starting dates,ending dates) and they must select which course they want to attend,by clicking the button 'attent course'.
Everytime someone clicks the submit button,the values are inserted in courses_students table,but not correctly.The problem is that everytime,the COURSE_ID from 'courses_students' has the value of the last COURSE_ID from 'courses'.And,other strange problem is that the values are inserted twice,everytime.
This is the code:
<?php
$link = mysql_connect('localhost','root','');
if(!$link){
die('Could not connect: '.mysql_error());
}
mysql_selectdb("db");
?>
<ul>
<?php
$sql = "SELECT * FROM courses";
$result = mysql_query($sql);
while($file = mysql_fetch_array($result)){
echo '<ul>';
echo '<li>';
$STUDENT_ID = $_SESSION['ID'];
$COURSE_ID = $file['COURSE_ID']; //**It dislays the CORRECT ID for each course!**
echo 'the course id: ' .$COURSE_ID;
echo 'course name: ' .$file['title'];
echo 'Starting: ' .$file['start_date'];
echo ' ending: '.$file['end_date'];
echo '<form action="lista_cursuri.php" method="post"> <input type="submit" name="submit" value="attent course!"> </form>';
echo '</li>';
}
?>
</ul>
<?php
if(isset($_POST['submit'])){
$sql1 = "INSERT INTO `courses_students` (COURSE_ID,STUDENT_ID) VALUES ($COURSE_ID,$STUDENT_ID)";
$result = mysql_query($sql1);
}
?>
I can't manage to see where the problem is.Maybe this is not the correct procedure.
Salut
Change mysql_fetch_array which is a multidimensional array once numerically indexed and once by field name which gives you double results to mysql_fetch_assoc
and $COURSE_ID is always last because for each loop it is overwritten
Try this:
Part 1:
while($file = mysql_fetch_assoc($result)){
echo '<ul>';
echo '<li>';
$STUDENT_ID = $_SESSION['ID'];
$COURSE_ID = $file['COURSE_ID'];
echo 'the course id: ' .$COURSE_ID;
echo 'course name: ' .$file['title'];
echo 'Starting: ' .$file['start_date'];
echo ' ending: '.$file['end_date'];
echo "<form action='lista_cursuri.php' method='post'>
<input type='hidden' name='courseid' value='".$COURSE_ID."' >
<input type='submit' name='submit' value='attent course!''> </form>";
echo '</li>';
}
Part 2:
if(isset($_POST['submit'])){
$course = $_POST['courseid'];
$sql1 = "INSERT INTO `courses_students` (COURSE_ID,STUDENT_ID) VALUES ($course,$STUDENT_ID)";
$result = mysql_query($sql1);
}
Try this:
$sql1 = "INSERT INTO `courses_students` (COURSE_ID,STUDENT_ID)
VALUES ('".$COURSE_ID."','".$STUDENT_ID."')"; $result = mysql_query($sql1);
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 dynamically generating a set of radio buttons from MySQL. The buttons are creating and the variables assigned to them are populating as I did an echo print_r and it shows the array for the variable. I now want to compare the values generated from this and if the vale is "0" I want to insert a score and present a green check graphic and the word correct. If the value is "1" I want it to input different values for the score and present Incorrect and a red X graphic. Here is what I have so far (Everything populates dynamically both the question and the answers as radio buttons):
<?php
echo '<form id="frmQuestion" name="frmQuestion" method="post" action="QuizQuestion1.php">';
// Connect to the Database
require_once('mysqli_connect.php');
//create the query for the question
$q = "SELECT `Question` FROM tbl_Question WHERE QuestionID = 1";
//Create the query for the Answers
$q2 = "SELECT `Answer`,`AnswerStatusID`,`AnswerResponse` FROM tbl_Answer WHERE QuestionID = 1";
//Run the query
$r = mysqli_query($conn,$q);
//run the answer query
$r2 = mysqli_query($conn,$q2);
while($row = mysqli_fetch_array($r,MYSQLI_ASSOC)){
echo '<div id="Question1"><p> ' . $row['Question'] . '</div></p>';
}
//Declare the variables as a array
$AnswerResponse = array();
$AnswerStatusID = array();
while($row2 = mysqli_fetch_array($r2,MYSQLI_ASSOC)){
echo '<div id="Question1"><input name="q1" type="radio" value="'.$AnswerStatusID.'"/>' . $row2['Answer'] . '</div><br/>';
//Assign the AnswerStatusID to a var
$AnswerStatusID[] = $row2['AnswerStatusID'];
//Assign the AnswerResponse to a var
$AnswerResponse[] = $row2['AnswerResponse'];
}
//Create the submit button
echo '<input type="submit" value="Submit Answer" name="submit"/>';
echo '</form>';
//Logic for correct or incorrect answers
if (isset($_POST['q1']) && ($_POST['q1'] == '0'))
{
//create the query for the score
$q3 = "INSERT INTO tbl_Score (`Score`,`QuestionID`) VALUES ('100%','1')";
//Run the query
$r = #mysqli_query ($conn,$q3);
if($r){
//Confirm message data was entered with a correct response and a graphic
echo '<h1>Correct!!</h1><img src="/images/green_Check_Low.jpg" alt="Green Check"/>';
echo 'Click here for the next question';
}
else
{
//there was an error
echo'<h1>System error</h1>';
//Debugging message
echo'<p>' . mysqli_error($conn) . '<br/><br/>Query:' . $q3 . '</p>';
}//End of nested IF
}
else{
//create the query for the score
$q4 = "INSERT INTO tbl_Score (`Score`,`QuestionID`) VALUES ('0%','1')";
//Run the query
$r2 = #mysqli_query ($conn,$q3);
if($r2){
//Confirm message data was entered with a correct response and a graphic
echo '<h1>Incorrect!!</h1><img src="/images/red_X_Low.jpg" alt="Red X"/>';
echo 'Click here for the next question';
}
else
{
//there was an error
echo'<h1>System error</h1>';
//Debugging message
echo'<p>' . mysqli_error($conn) . '<br/><br/>Query:' . $q3 . '</p>';
}//End of nested IF
}
//Free up the results for the Question query
mysqli_free_result($r);
//Free up the results from the Answer query
mysqli_free_result($r2);
//close the DB connection
mysqli_close($conn);
?>
This is the answer and work as intended. Thanks for everyones input.
//Declare the variables as a array
$AnswerResponse = array();
$AnswerStatusID = array();
while($row2 = mysqli_fetch_array($r2,MYSQLI_ASSOC)){
echo '<div id="Question1"><input name="q1" type="radio" value="'.$row2['AnswerStatusID'].'"/>' . $row2['Answer'] . '</div><br/>';
//Assign the AnswerStatusID to a var
$AnswerStatusID[] = $row2['AnswerStatusID'];
//Assign the AnswerResponse to a var
$AnswerResponse[] = $row2['AnswerResponse'];
}
//Create the submit button
echo '<input type="submit" value="Submit Answer" name="submit"/>';
echo '<input type="hidden"name="submitted"value="TRUE"/>';
echo '</form>';
if($_POST['submitted']) {
//Logic for correct or incorrect answers
if (isset($_POST['q1']) && ($_POST['q1'] == '0'))
{
//create the query for the score
$q3 = "INSERT INTO tbl_Score (`Score`,`QuestionID`) VALUES ('100%','1')";
//Run the query
$r3 = #mysqli_query ($conn,$q3);
//Confirm message data was entered with a correct response and a graphic
echo '<h1>Correct!!</h1><img src="/images/green_Check_Low.jpg" alt="Green Check"/>';
echo 'Click here for the next question';
}
else{
//create the query for the score
$q4 = "INSERT INTO tbl_Score (`Score`,`QuestionID`) VALUES ('0%','1')";
//Run the query
$r4 = #mysqli_query ($conn,$q4);
//Confirm message data was entered with a correct response and a graphic
echo '<h1>Incorrect!!</h1><img src="/images/red_X_Low.jpg" alt="Red X"/><br/>';
echo 'Click here to try again';
}
}