Hi there's a live version of the code below (taken from a tutorial) at my website below http://www.prupt.com/edit_subject.php
The page has a form that allows you to edit the subjects in the navigation bar down the left hand side. For example, you could click on "About Widget Corp" and the name "About Widget Corp" will appear in the subject text field, at which point your supposed to be able to edit it (i.e. change its name if you like) then click "edit subject" and it will update the new name in the navigation down the left hand side.
That's what it's supposed to do, according to the tutorial. However, if I try to edit one of the names, and then click "edit subject" it doesn't change anything. I'm guessing it's not updating the database and thereafter not outputting the correct/new data to the navigation bar
Do you see anything in the code below which would explain why it's not updating the navigation bar once I click "edit subject"?
<?php
//1.Create a database connection
$connection = mysql_connect("98.130.0.87", "username", "password");
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db("C263430_testorwallo" ,$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
?>
<?php require_once("includes/functions.php"); ?>
<?php
if (intval($_GET['subj']) == 0) {
redirect_to("content.php");
}
if (isset($_POST['submit'])) {
$errors = array();
$required_fields = array('menu_name', 'position', 'visible');
foreach($required_fields as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] !=0)) {
$errors[] = $fieldname;
}
}
$fields_with_lengths = array('menu_name' => 30);
foreach($fields_with_lengths as $fieldname => $maxlength ) {
if (strlen(trim(mysql_prep($_POST[$fieldname]))) > $maxlength) {
$errors[] = $fieldname; }
}
if (empty($errors)){
//Perform Update
$id = mysql_prep($_GET['subj']);
$menu_name = mysql_prep($_POST['menu_name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
$query = "UPDATE subjects SET
menu_name = '{$menu_name}',
position = {$position},
visible = {$visible}
WHERE id = {$id}";
$result = mysql_query($query, $connection);
if (mysql_affected_rows() == 1) {
//Success
} else {
//Failed
}
} else {
// Errors occurred
}
} //end: (isset($_POST['submit']))
?>
<?php find_selected_page();?>
<?php include("includes/header.php"); ?>
<table id="structure">
<tr>
<td id="navigation">
<?php echo navigation($sel_subject, $sel_page); ?>
</td>
<td id="page">
<h2>Edit Subject <?php echo $sel_subject ['menu_name'];?></h2>
<form action="edit_subject.php?subj=<?php echo urlencode($sel_subject['id']);?>" method="post">
<p>Subject name: <input type="text" name="menu_name" value="<?php echo $sel_subject['menu_name']; ?>" id="menu_name" /></p>
<p>Position:
<select name="position">
<?php
$subject_set = get_all_subjects();
$subject_count = mysql_num_rows($subject_set);
//$subject_count +1 because we are adding a subject
for($count=1; $count <= $subject_count+1; $count++) {
echo "<option value=\"{$count}\"";
if ($sel_subject['position'] == $count) {
echo " selected";
}
echo ">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0"<?php
if ($sel_subject['visible'] == 0) { echo " checked";}
?>/>No
<input type="radio" name="visible" value="1"<?php
if ($sel_subject['visible'] == 1) { echo " checked"; }
?>/> Yes
</p>
<input type="submit" name"submit" value="Edit Subject"/>
</form>
<br/>
Cancel
</td>
</tr>
</table>
<?php include("includes/footer.php"); ?>
<?php
//5. Close connection
mysql_close($connection);
?>
Ok, saw the page code and it's likely that (see comment above).
<input type="submit" name"submit" value="Edit Subject"/>
You forgot the = sign, correct it to name="submit". That's why it doesn't see the form as submitted (if $_POST['submit']...)
Related
I have a edit form that has some checkboxes on it and I am having trouble getting the new checkbox values posted back to the db after it has been changed. So far the form will load in the current values in the db but after you click different check boxes it wont update the change in the db. Any help would be appreciated.
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($id, $firstname, $contactname, $phone, $type, $sex, $markers, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>First Name: *</strong> <input type="text" name="firstname" value="<?php echo $firstname; ?>"/><br/>
<strong>Contact Name: *</strong> <input type="text" name="contactname" value="<?php echo $contactname; ?>"/><br/>
<strong>Phone Number: *</strong> <input type="text" name="phone" value="<?php echo $phone; ?>"/><br/>
<strong>Type: *</strong>
<select name="type">
<option value="">Select...</option>
<option value="Inpatient Hospital" <?php if($type=="Inpatient Hospital")echo "selected=\"selected\""; ?>>Inpatient Hospital</option>
<option value="Residential Facility"<?php if($type=="Residential Facility")echo "selected=\"selected\""; ?>>Residential Facility</option>
<option value="Behavioral Treatment Facility"<?php if($type=="Behavioral Treatment Facility")echo "selected=\"selected\""; ?>>Behavioral Treatment Facility</option>
<option value="Therapeutic Group Home"<?php if($type=="Therapeutic Group Home")echo "selected=\"selected\""; ?>>Therapeutic Group Home</option>
<option value="Drug or Addictions Rehab"<?php if($type=="Drug or Addictions Rehab")echo "selected=\"selected\""; ?>>Drug or Addictions Rehab</option>
</select><br/>
<input type="radio" name="sex" value="Male" <?php echo ($sex=="Male")?'checked="checked"':'' ?>size="17">Male
<input type="radio" name="sex" value="Female" <?php echo ($sex=="Female")?'checked="checked"':'' ?> size="17">Female
<input type="radio" name="sex" value="Both" <?php echo ($sex=="Both")?'checked="checked"':'' ?> size="17">Both<br/>
<strong>Markers: *</strong> <input type="text" name="markers" value="<?php echo $markers; ?>"/><br/>
<?php
// Create connection
$con=mysqli_connect("localhost","un","pw","childcare");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT FMarkers FROM faci WHERE ID='$id'");
while($row = mysqli_fetch_array($result))
{
$focus=explode(",",$row['FMarkers']);
?>
Autism<input type="checkbox" name="FMarkers[]" value="Autism" <?php if(in_array("Autism",$focus)) { ?> checked="checked" <?php } ?> >
Attachement Disorder<input type="checkbox" name="FMarkers[]" value="Attachement Disorder" <?php if(in_array("Attachement Disorder",$focus)) { ?> checked="checked" <?php } ?> >
Dissociative Disorder<input type="checkbox" name="FMarkers[]" value="Dissociative Disorder" <?php if(in_array("Dissociative Disorder",$focus)) { ?> checked="checked" <?php } ?> >
ODD<input type="checkbox" name="FMarkers[]" value="ODD" <?php if(in_array("ODD",$focus)) { ?> checked="checked" <?php } ?> >
ADHD<input type="checkbox" name="FMarkers[]" value="ADHD" <?php if(in_array("ADHD",$focus)) { ?> checked="checked" <?php } ?> >
<?php
//print_r(array_values($focus));
//echo("<pre>\n");
//print_r($_POST);
//echo("</pre>\n");
//var_dump($dog);
//these below are different ways I have tried to get it to work
//$markers = implode(',', $_POST['dog']);
//$markers=$_POST['focus'];
//$markers = implode(",",$markers);
//$markers = implode(",",$_POST['focus']);
//$check = isset($_POST['focus']) ? $_POST['focus'] : '';
//$markers = is_array($check) ? implode(", ", $check) : '';
//echo $markers;
?>
<?php
}
?>
<p>* Required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$contactname = mysql_real_escape_string(htmlspecialchars($_POST['contactname']));
$phone = mysql_real_escape_string(htmlspecialchars($_POST['phone']));
$type = mysql_real_escape_string(htmlspecialchars($_POST['type']));
$sex = mysql_real_escape_string(htmlspecialchars($_POST['sex']));
$markers = mysql_real_escape_string(htmlspecialchars($_POST['markers']));
// check that firstname/lastname fields are both filled in
if ($firstname == '' || $contactname == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $firstname, $contactname, $phone, $type, $sex, $markers, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE faci SET FName='$firstname', FContact='$contactname', FPhone='$phone', FType='$type', FSex='$sex', FMarkers='$markers' WHERE ID='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: facility-view.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM faci WHERE ID=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$firstname = $row['FName'];
$contactname = $row['FContact'];
$phone = $row['FPhone'];
$type = $row['FType'];
$sex = $row['FSex'];
$markers = $row['FMarkers'];
// show form
renderForm($id, $firstname, $contactname, $phone, $type, $sex, $markers, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
This is kind of the error I'm getting:
Database query failed.
I've uploaded this webpage: http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1
Here's my file:
<?php require_once("../includes/session.php"); ?>
<?php require_once("../includes/db_connection.php"); ?>
<?php require_once("../includes/functions.php"); ?>
<?php require_once("../includes/validation_functions.php"); ?>
<?php find_selected_page(); ?>
<?php
if (!$current_subject)
{
// subject ID was missing or invalid or
// subject couldn't be found in database
redirect_to("manage_content.php");
}
?>
<?php
if (isset($_POST['submit']))
{
// validations
$required_fields = array("menu_name", "position", "visible");
validate_presences($required_fields);
$fields_with_max_lengths = array("menu_name" => 30);
validate_max_lengths($fields_with_max_lengths);
if (empty($errors))
{
// Perform Update
$id = $current_subject["id"];
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$query = "UPDATE subjects SET ";
$query .= "menu_name='{$menu_name}', ";
$query .= "position={$position}, ";
$query .= "visible={$visible} ";
$query .= "WHERE id={$id} ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) >= 0)
{
// Success
$_SESSION["message"] = "Subject updated.";
redirect_to("manage_content.php");
}
else
{
// Failure
$message = "Subject update failed.";
}
}
}
// else
// {
// // This is probably a GET request
// }
?>
<?php include("../includes/layouts/header.php"); ?>
<div id="main">
<div id="navigation">
<?php
echo navigation($current_subject, $current_page);
?>
</div>
<div id="page">
<?php
// echo message();
// $message is just a variable, doesn't use the SESSION
if(!empty($message))
{
echo "<div class=\"message\">" . htmlentities($message) . "</div>";
}
?>
<?php echo form_errors($errors); ?>
<h2>Edit Subject: <?php echo htmlentities($current_subject["menu_name"]); ?></h2>
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["menu_name"]); ?>" method="post">
<p>Menu name:
<input type="text" name="menu_name" value="<?php echo htmlentities($current_subject["menu_name"]); ?>" />
</p>
<p>Position:
<select name="position">
<?php
$subject_set = find_all_subjects();
$subject_count = mysqli_num_rows($subject_set);
for ($count=1; $count <= $subject_count; $count++)
{
echo "<option value=\"{$count}\"";
if ($current_subject["position"] == $count)
{
echo " selected";
}
echo ">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0" <?php if ($current_subject["visible"] == 0) { echo "checked"; } ?> /> No
<input type="radio" name="visible" value="1" <?php if ($current_subject["visible"] == 1) { echo "checked"; } ?> /> Yes
</p>
<input type="submit" name="submit" value="Edit Subject" />
</form>
<br />
Cancel
Delete Subject
</div>
The problem is somewhere else and not with your UPDATE query actually. If you see the link you posted, you are passing subject parameter with url, whose value is 1 which is integer.
Now when you click submit it's changing the url to http://widgetcorp.bugs3.com/public/edit_subject.php?subject=About%20Widget%20Corp .
Here as you see the subject parameter is not integer but string value name of subject. And that is causing the problem.
You are getting error as it's not retrieving the subject data from database correctly because of wrong id type. You just need to make sure the form is being posted to right url, which would be http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1.
You need to correct the action parameter on the <form> tag for that.
Look for the line below in your code:
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["menu_name"]); ?>" method="post">
And change it to
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["id"]); ?>" method="post">
If you see, now the form will be submitted to http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1, which is the correct url.
I'm currently just coding around in my free time and follow up some random tutorials that other developers/coder's created in there spare time. Now I'm stuck with something very small. I have been trying to find a answer on the interwebz but I cant seem to find one, so here I'm hoping that someone is willing to read my PHP and HTML and see the error I created.
But before I share my code let me tell you what my problem is and what I try to achieve.
If you go to the following link "removed because problem is solved." and when you click on Home/About/Service/Random, you are able to edit one of these menu's. (title, posistion, visible). Now when I want to change the menu name "Home" to "Welcome" it correctly execute my SQL but for some reason, in the HTML Form it loads it's previous information. What I can do is copy the PHP and save it in a new php file and when clicking on submit it will change both menu/title/html form at the same time, but it wont show my succes and fail message anymore. I hope any of you understand what I'm trying to explain here and try to achieve. Now lets share the code.
PHP
<? find_selected_page(); ?>
<?
if (intval($_GET['info']) == 0){
redirect_to("content.php");
}
if(isset($_POST['submit'])){
$errors = array();
$required_fields = array('menu', 'position', 'visible');
foreach ($required_fields as $fieldname){
if (!isset($POST[$fieldname]) || (empty($_POST[$fieldname]) &&
!is_numeric($_POST[$fieldname]))) {
$errors [] = $fieldname;
}
}
$fields_with_lengths = array('menu' => 30);
foreach($fields_with_lengths as $fieldname => $maxlength) {
if(strlen(trim(mysql_prep($_POST[$fieldname]))) > $maxlength){
$errors[] = $fieldname;
}
}
$id = mysql_prep($_GET['info']);
$menu = mysql_prep($_POST['menu']); //use post array cuz we used post var to coll val in form
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
$query = "UPDATE information SET menu = '{$menu}', position = {$position}, visible = {$visible} WHERE id = {$id}";
$result = mysql_query($query, $connection);
if (mysql_affected_rows() == 1) {
$message = "The information was correctly updated.";
} else {
//failed
}
} else { //errors
}
?>
HTML
<? require_once ("includes/functions.php"); ?>
<? require_once ("includes/connect.php"); ?> //HERE IS MY CONNECTION TO MY DATABASE
///HERE IS MY PHP CODE
<? include ("includes/header.php"); ?>
<div id="content"> <!-- content here -->
<table id="table">
<tr>
<td id="nav">
<? echo navigation($sel_table1, $table2); ?>
</td>
<td id="main">
<h2>Edit Info <? echo $sel_table1['menu']; ?></h2>
<? if (!empty($message)) { echo "<p class=\"message\">" . $message . "</p>";} ?>
<form action="edit_info.php?info=<? echo urlencode($sel_table1['id']); ?>" method="post"/>
<p>Menu title
<input type="text" name="menu" value="<? echo ($sel_table1['menu']); ?>" id="menu">
</p>
<p>Position
<select name="position">
<?
$info_set = get_all_info();
$info_count = mysql_num_rows($info_set); //asks how many rows there are should be 3
for($count=1; $count <= $info_count+1; $count++){
echo "<option value='{$count}'";
if($sel_table1['position'] == $count){
echo "selected";
}
echo ">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0"
<? if ($sel_table1['visible'] == 0){ echo "checked"; } ?>
/>No
<input type="radio" name="visible" value="1"
<? if ($sel_table1['visible'] == 1){ echo "checked"; } ?>
/>Yes
</p>
<input type="submit" name='submit' value="Edit information" />
</form> <br>
Cancel
</td>
</tr>
</table>
</div>
<? include ("includes/footer.php");?> //HERE I HAVE IF ISSET MYSQL CLOSE
And a more simple short version of the story is, I want to update the menu's with the success and failure message's without getting the old previous data in my HTML FORM
if needed for any reasons I have included the part of my functions.php where $sel_table and $table2 are staying.
function find_selected_page(){
global $sel_table1;
global $table2;
if (isset($_GET['info'])){
$sel_table1 = get_info_by_id($_GET['info']);
$sel_t2 = 0;
$table2 = NULL;
} else if (isset($_GET['page'])){
$table1 = 0;
$sel_table1 = NULL;
$table2 = get_pages_by_id($_GET['page']);
} else {
$table1 = NULL;
$sel_table1 = NULL;
$table2 = 0;
}
}
function navigation($sel_table1, $table2){
$output = "<ul class='info'>";
$info_set = get_all_info();
while ($info = mysql_fetch_array($info_set))
{
$output .= "<li"; if ($info["id"] == $sel_table1 ["id"]){
$output .= " class='selected'";
}
$output .= "><a href='edit_info.php?info=" . urlencode($info["id"]) . "'>{$info['menu']}</a></li>";
$page_set = get_pages_for_info($info["id"]);
$output .= "<ul class='pages'>";
while ($page = mysql_fetch_array($page_set))
{
$output .= "<li"; if ($page["id"] == $table2 ["id"]){
$output .= " class='selected'";
}
$output .= "><a href='content.php?page=" . urlencode($page["id"]) . "'>{$page['menu']}</a></li>"; }
$output .= "</ul>";
}
$output .= "</ul>";
return $output;
}
Hello my name is Patrick and this is my first question, i'm sorry but i'm not very good in PHP. probably there are more improvements but this post is for the questions. (but improvements are also welcome)
Question:
You can choose a team of 2 monsters // The monster are selected form database
The question is: if you choose 1 monster how can i fix that you can't choose the same monster on option 2?
PHP CODE:
Action of the 2 sumbit buttons
<?php
session_start();
include("header.php");
if(!isset($_SESSION['uid'])){
echo "You must be logged in to view this page!";
}else{
if (isset($_POST['save'])) {
if ($_POST['save'] == 'keuze4') {
$fuelQuery4 = sprintf("UPDATE user_team SET `m_keuze4` = '%s' WHERE `id`='".$_SESSION['uid']."' ",
mysql_real_escape_string($_POST['option4']));
$Result = mysql_query($fuelQuery4);
if($Result){
echo 'Team is aangepast!';
}
} elseif ($_POST['save'] == 'keuze5'){
$fuelQuery5 = sprintf("UPDATE user_team SET `m_keuze5` = '%s' WHERE `id`='".$_SESSION['uid']."' ",
mysql_real_escape_string($_POST['option5']));
$Result = mysql_query($fuelQuery5);
if($Result){
echo 'Team is aangepast!';
}
}
echo '';}
?>
Get the monsters form database and put it in a select list
<?php
$get=mysql_query("SELECT * FROM user_monsters WHERE `id`='".$_SESSION['uid']."' ORDER BY usid ASC");
$option4 = '';
while($row = mysql_fetch_assoc($get))
{
$option4 .= '<option value = "'.$row['usid'].'">'.$row['usid'].' - '.$row['monster'].' - '.$row['type'].'</option>';
}
?>
Show the selected item
<?php
$k4 = mysql_query("
SELECT user_team.m_keuze4, user_monsters.usid, user_monsters.monster, user_monsters.type, user_monsters.attack, user_monsters.defense
FROM user_team
INNER JOIN user_monsters
ON user_team.m_keuze4=user_monsters.usid
ORDER BY user_monsters.type;
");
while($row4 = mysql_fetch_assoc($k4))
{
$k4_1 = ''.$row4['m_keuze4'].' - '.$row4['monster'].' - '.$row4['type'].' - '.$row4['attack'].' - '.$row4['defense'].'';
}
?>
Option 5 is the same code as 4:
<?php
$get=mysql_query("SELECT * FROM user_monsters WHERE `id`='".$_SESSION['uid']."' ORDER BY usid ASC");
$option5 = '';
while($row = mysql_fetch_assoc($get))
{
$option5 .= '<option value = "'.$row['usid'].'">'.$row['usid'].' - '.$row['monster'].' - '.$row['type'].'</option>';
}
?>
<?php
$k5 = mysql_query("
SELECT user_team.m_keuze5, user_monsters.usid, user_monsters.monster, user_monsters.type, user_monsters.attack, user_monsters.defense
FROM user_team
INNER JOIN user_monsters
ON user_team.m_keuze5=user_monsters.usid
ORDER BY user_monsters.type;
");
while($row5 = mysql_fetch_assoc($k5))
{
$k5_1 = ''.$row5['m_keuze5'].' - '.$row5['monster'].' - '.$row5['type'].' - '.$row5['attack'].' - '.$row5['defense'].'';
}
?>
The Form
<form action="team.php" method="post">
<select name="option4">
<?php echo $option4; ?>
</select><br><br>Keuze 4
<?php
echo $k4_1;
?><br><br>
<input type="submit" name="save" value="keuze4"/>
</form>
<form action="team.php" method="post">
<select name="option5">
<?php echo $option5; ?>
</select><br><br>Keuze 5
<?php
echo $k5_1;
?><br><br>
<input type="submit" name="save" value="keuze5"/>
</form>
In php the best you can do check the option once its posted:
if (isset($_POST['save'])) {
if (filter_input(INPUT_POST,'option4') == filter_input(INPUT_POST,'option5')){
echo "Sorry. You can't select the same monster twice";
}else{
//your db insert logic goes here
}
}
It would be a good idea to also include some javascript to alert the user before they submit the form. This example uses jQuery
$('[name="option4"],[name="option5"]').change(function(){
if ($('[name="option4"]').val() == $('[name="option5"]').val()){
alert('you already chose that monster, please choose another');
}
});
The Form
<form action="team.php" method="post">
<select name="option4">
<?php echo $option4; ?>
</select><br><br>Keuze 4
<?php
echo $k4_1;
?><br><br>
<input type="submit" name="save" value="keuze4"/>
</form> <!-- remove this line-->
<form action="team.php" method="post"> <!-- and this line-->
<select name="option5">
<?php echo $option5; ?>
</select><br><br>Keuze 5
<?php
echo $k5_1;
?><br><br>
<input type="submit" name="save" value="keuze5"/>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
$('[name="option4"],[name="option5"]').change(function () {
if ($('[name="option4"]').val() == $('[name="option5"]').val()) {
alert('you already chose that monster, please choose another');
}
});
});
</script>
Action of the 2 sumbit buttons
if (isset($_POST['save'])) {
if (filter_input(INPUT_POST, 'option4') == filter_input(INPUT_POST, 'option5')) {
echo "Sorry. You can't select the same monster twice";
} else {
if ($_POST['save'] == 'keuze4') {
$fuelQuery4 = sprintf("UPDATE user_team SET `m_keuze4` = '%s' WHERE `id`='" . $_SESSION['uid'] . "' ", mysql_real_escape_string($_POST['option4']));
$Result = mysql_query($fuelQuery4);
if ($Result) {
echo 'Team is aangepast!';
}
} elseif ($_POST['save'] == 'keuze5') {
$fuelQuery5 = sprintf("UPDATE user_team SET `m_keuze5` = '%s' WHERE `id`='" . $_SESSION['uid'] . "' ", mysql_real_escape_string($_POST['option5']));
$Result = mysql_query($fuelQuery5);
if ($Result) {
echo 'Team is aangepast!';
}
}
}
}
Edit again,
Demo Fiddle of js
thank you for taking time to look at this. I have been dealing with this annoying foreach loop. Here is what I am trying to do.
I have the first page "form.php".
On this page I have check boxes. Each check box is generated from a database table. Here is the code:
<?php
include("config.php");
$mysqli = new mysqli($host, $db_uname, $db_pass, $db);
$query = "SELECT * FROM `plugins` WHERE 1";
if ($result = $mysqli->query($query)) {
echo '<form action="test.php" method="post">
<input name="gname" placeholder="Group Name..."/>
<table width="200">
';
while ($row = $result->fetch_assoc()) {
echo '<tr><td>
<label>
<input type="checkbox" value="'.$row["plugin"].'" name="checkbox[]">
'.$row["plugin"].'
</label>
</td></tr>';
}
echo '
</table>
<select name="permplugin">
<option>Select One...</option>';
$query2 = "SELECT * FROM `permission_types` WHERE 1";
if ($result2 = $mysqli->query($query2)) {
echo '<h3>Select Permission format below</h3><hr />';
while ($row2 = $result2->fetch_assoc()) {
echo '
<option value="'.$row2["plugin_name"].'">'.$row2["plugin_name"].'</option>';
}
echo '
</select>
<br />
<input name="" type="reset"><input name="" type="submit">
</form>';
}
}
?>
Now after that it sends the checked boxes to "test.php"
here is the code for that:
<?php
if(!empty($_POST['checkbox']) || !empty($_POST['select']) || !empty($_POST['gname'])) {
echo '<h1>'.$_POST['gname'].'</h1>';
$check1 = $_POST['checkbox'];
foreach($check1 as $check) {
include "functions.php";
checkboxes($check);
}
echo '<h3>Selected Permission format below</h3><hr />';
echo $_POST['permplugin'];
} else {
echo "please select atleast one plugin.";
}
?>
The functions page code looks like this:
<?php
//all functions are here.
function checkboxes($check){
$mysqli_perm = new mysqli("localhost", "uname", "pword", "tcordero_permnodes");
$query_perm = "SELECT * FROM permission_nodes WHERE plugin = `$check`";
if ($result_perm = $mysqli_perm->query($query_perm)) {
echo $check;
/* fetch associative array */
while ($row_perm = $result_perm->fetch_assoc()) {
echo $row_perm['node'].'<br />';
}
unset($check);
}
}
When I run the test.php I get this error:
Fatal error: Cannot redeclare checkboxes() (previously declared in C:\xampp\htdocs\TPYC\functions.php:3) in C:\xampp\htdocs\TPYC\functions.php on line 15
What am I doing wrong?
You need to take the include out of the foreach loop. Try this:
include "functions.php";
foreach($check1 as $check) {
checkboxes($check);
}