wordpress form with roster registration of users - php

I'm trying to build a manual form on a Wordpress page.
My goal is to create a dropdown menu of all the users with a fixed role (in my case "athlete") and register single users in some sport events.
My code:
<form name="team_captain" method="POST" >
Carnival Name: <input type="text" id="carnival_name" name="carnival_name" />
<input type="submit" name="submit_carnival" value="Create Carnival"/><br />
Event Name: <select name="event_name">
<option value="Ironman Race">Ironman Race</option>
<option value="Board Race">Board Race</option>
<option value="Ski Race">Ski Race</option>
<option value="Surf Race">Surf Race</option>
</select><br />
Athlete Name:
<select name="athlete_name">[insert_php] echo getUsersByRole('athlete','athlete-selector'); [/insert_php]</select><br />
Age Group: <select name="age_group">
<option value="Under 15">Under 15</option>
<option value="Under 17">Under 17</option>
<option value="Under 19">Under 19</option>
<option value="Open">Open</option>
</select><br />
Sex: <input type="radio" name="athlete_sex" value="Male">Male <input type="radio" name="athlete_sex" value="Female">Female<br />
<input type="submit" value="Insert Race"/>
</form>
[insert_php]
if(isset($_POST['submit_carnival'])) {
$carnival_name = $_POST['carnival_name'];
echo "Registrations for ".$carnival_name;
}
elseif(isset($_POST['submit'])) {
$event_name = $_POST["event_name"];
$athlete_sex = $_POST["athlete_sex"];
$age_group = $_POST["age_group"];
$athlete_name = $_POST["athlete_name"];
echo $event_name;
echo $age_group;
echo $athlete_sex;
echo $athtlete_name;
}
[/insert_php]
At this point I can display the name of the carnival, but I can't display the instances of the athletes. And the dropdown list of the athletes doesn't work.
This is the function:
function getUsersByRole($role,$name,$selected = '',$extra = '') {
global $wpdb;
$wp_user_search = new WP_User_Query(array("role"=> $role));
$role_data = $wp_user_search->get_results();
foreach($role_data as $item){
$role_data_ids[] = $item->ID;
}
$ids = implode(',', $role_data_ids);
$r = $wpdb->get_results("SELECT * from ".$wpdb->prefix . "users where id IN(".$ids .")", ARRAY_A);
$content .='<select name="'.$name.'" id="'.$name.'" '.$extra.'>';
if($selected == ''){
$content .='<option value="" selected="selected">Choose a user</option>';
}else{
$r_user = $wpdb->get_results("SELECT * from ".$wpdb->prefix . "users where ID = ".$selected."", ARRAY_A);
$content .='<option value="'.$selected.'" selected="selected">'.stripslashes($r_user[0]['display_name']).'</option>';
}
for($i=0; $i<count($r); $i++){
$content .='<option value="'.$r[$i]['ID'].'">'.stripslashes($r[$i]['display_name']).'</option>';
}
$content .='</select>';
return $content;
}

Because you're looking for a $_POST["submit"], you'll have to have an input with the name attribute equal to submit. In your case replace this:
<input type="submit" value="Insert Race"/>
with this:
<input type="submit" name="submit" value="Insert Race"/>
Your getUsersByRole() function is already including the "select" tag, so replace this line:
<select name="athlete_name">[insert_php] echo getUsersByRole('athlete','athlete-selector'); [/insert_php]</select><br />
with this, notice that I changed "athlete-selector" to "athlete_name":
[insert_php] echo getUsersByRole('athlete','athlete_name'); [/insert_php]<br />
With those two changes, things should be working, though I haven't studied your getUsersByRole() function intensively, so there could be a bug in there. Let me know in a comment below if this works for you or not.

Related

how do I retain search form results while submitting another form on the page?

I start by showing a list of businesses I have stored in a db. There is a form to search by industry or state. When showing a list of search results, I also provide the option to move the businesses to different tables. After submitting the form to move a business to a different table, the list refreshes to default result list, and we have to enter search term again.
I've tried assigning $_POST values to dynamic urls in the action url of my forms, I've tried assigning $_POST values to the value="" parameter of my forms.
<?php
if (isset($_POST['update']) && ($_POST['update'] == 'true')){
$sql = 'INSERT INTO table1 (columns,columns,columns)
SELECT columns,columns,columns
FROM table2 WHERE id = 1';
if (mysqli_query($db, $sql)) {}
}
?>
<div>
<form action="./?action=list" method="POST">
<input type="hidden" name="search" value="true" />
<input placeholder=" INDUSTRY" type="text" size="15" name="kw" />
<select name="state" onchange='this.form.submit()'>
<option value=''>BY STATE</option>
<?php require('includes/stateselect.php'); ?>
</select>
<input type="submit" value="SEARCH">
</form>
</div>
<table>
<?php
$sql = 'SELECT * FROM db.table ';
if ((isset($_POST['kw'])) && (!empty($_POST['kw']))){
$sql .=' WHERE `kw` LIKE \'%'.$_REQUEST['kw'].'%\' OR `biz` LIKE \'%'.$_POST['kw'].'%\' ';
}
if ((isset($_POST['state'])) && (!empty($_POST['state']))){
$sql .=' WHERE `state` = \''.$_POST['state'].'\' ';
}
if ($result = mysqli_query($db, $sql)){
while ($row = mysqli_fetch_array($result)) {
echo '<tr><form method="POST" action="./?action=list">
<input type="hidden" name="id" value="'.$row['id'].'" />
<input type="hidden" name="update" value="true" />
<td>'.$row['kw'] .'</td><td>'. $row['state'].'</td>';
echo '<td>
<select name="move">
<option>--Fresh--</option>
<option value="dnc">DNC</option>
</select>';
echo '<input type="submit" value="submit">';
echo '</td></form></tr>';
}
}
?>
</table>
We want to be able to search for lawyers, then disposition them from the list as we call them, but retain our search results.
You can store the search term inside a session so that you can use that term multiple times in your form. Store the search term in the session like this,
if ((isset($_POST['kw'])) && (!empty($_POST['kw']))){\
$_SESSION['search_term] = $_POST['kw'];
$sql .=' WHERE `kw` LIKE \'%'.$_REQUEST['kw'].'%\' OR `biz` LIKE
\'%'.$_POST['kw'].'%\' ';
}
You could try to re-set the kw as a hidden input within the second form to retain the search terms, like this :
<?php
if (isset($_POST['update']) && ($_POST['update'] == 'true')){
$sql = 'INSERT INTO table1 (columns,columns,columns)
SELECT columns,columns,columns
FROM table2 WHERE id = 1';
if (mysqli_query($db, $sql)) {}
}
?>
<div>
<form action="./?action=list" method="POST">
<input type="hidden" name="search" value="true" />
<input placeholder=" INDUSTRY" type="text" size="15" name="kw" />
<select name="state" onchange='this.form.submit()'>
<option value=''>BY STATE</option>
<?php require('includes/stateselect.php'); ?>
</select>
<input type="submit" value="SEARCH">
</form>
</div>
<table>
<?php
$sql = 'SELECT * FROM db.table ';
if ((isset($_POST['kw'])) && (!empty($_POST['kw']))){
$sql .=' WHERE `kw` LIKE \'%'.$_REQUEST['kw'].'%\' OR `biz` LIKE \'%'.$_POST['kw'].'%\' ';
}
if ((isset($_POST['state'])) && (!empty($_POST['state']))){
$sql .=' WHERE `state` = \''.$_POST['state'].'\' ';
}
if ($result = mysqli_query($db, $sql)){
while ($row = mysqli_fetch_array($result)) {
echo '<tr><form method="POST" action="./?action=list">
<input type="hidden" name="id" value="'.$row['id'].'" />
<input type="hidden" name="update" value="true" />
<td>'.$row['kw'] .'</td><td>'. $row['state'].'</td>';
echo '<td>
<select name="move">
<option>--Fresh--</option>
<option value="dnc">DNC</option>
</select>';
// added below blocks
if (!empty($_POST['kw'])){
echo '<input type="hidden" name="kw" value="'.$_POST['kw'].'" />';
// echo '<input type="hidden" name="search" value="true" />';
}
if (!empty($_POST['state'])){
echo '<input type="hidden" name="state" value="'.$_POST['state'].'" />';
}
echo '<input type="submit" value="submit">';
echo '</td></form></tr>';
}
}
?>
</table>

Adding radio button to MySQL fetch result and use result value to fetch another record...?

I want a first radio button to be checked by default. When I click get schedule I want to fetch the schedule of that radio selected train number using a WHERE clause.
<?php
while ($res = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td><input type = radio />" . $res['Train_no'] . "</td>";
?>
<form action="schedule.php" method="POST" class="form-inline">
<input type="submit" value="Get Schedule"/>
</form>
<?php
}
<?php
$con = mysql_connect("localhost", "root", "");
if ($con) {
$db = mysql_select_db('traindb', $con);
} else {
die('Could not connect: ' . mysql_error());
}
$selected_val = $_POST['Train_no']; // Storing Selected Value In Variable
echo "You have selected :" . $selected_val; // Displaying Selected Value
$result = mysql_query("SELECT * FROM train_detail WHERE Train_No='$selected_val'");
mysql_close($con);
?>
You can try this:
if(isset($_POST['Submit'])){
$selected_val = $_POST['Train_no']; // Storing Selected Value In
echo "You have selected :" .$selected_val; // Displaying Selected Value
$result = mysql_query("SELECT * FROM train_detail WHERE
Train_No='$selected_val'");
}
Here is one example of "select":
<form action="" method="post">
<select type="age" class="form-control" id="age" name="age">
<!-- <option value="disable" selected="">Please Select</option> -->
<option value="">Please select</option>
<option value="Under 35">Under 35</option>
<option value=">35 - 44">35 - 44</option>
<option value=">45 - 54">45 - 54</option>
<option value=">55 - 59">55 - 59</option>
<option value=">60 - 64">60 - 64</option>
<option value=">65 - 69">65 - 69</option>
<option value=">70 - 74">70 - 74</option>
<option value=">75 - 79">75 - 79</option>
<option value="80 +">80 +</option>
</select>
<input type="submit" value="Submit">
</form>
<?php
$age = $_POST['age'];
if (isset($_POST['age']) && $_POST['age'] == "")
echo "You did not choose any options. Pls try again.";
else {
echo $age;
}
?>
If you want embed PHP in select options, do it like this:
<option value="<?php echo $res['Train_no'] ?>"><?php echo $res['some_other'] ?></option>
For radio button it is like this:
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php">
<input type="radio" name="gender" value="<?php echo $res['Train_no'] ?>" checked><?php echo $res['some_other'] ?><br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other<br><br>
<input type="submit">
</form>
</body>
</html>

Form that uses array, assign object to array

I need to create a form that allows the user to select a number from 0 to 7 and "show all" and the script will then output the object found in that train car to the user, or if show all is picked then it runs a loop that shows all 8 objects along with the train number. But my code doesn't really run.
(Please ignore my code if it doesn't make any sense, but I don't seem to get arrays :( Please point out the mistakes and thank you so so so much)
<html>
<body>
<form name="train" method="GET" action="test.php">
<select>
<option value="0" name="object">0</option>
<option value="1" name="object">1</option>
<option value="2" name="object">2</option>
<option value="3" name="object">3</option>
<option value="4" name="object">4</option>
<option value="5" name="object">5</option>
<option value="6" name="object">6</option>
<option value="7" name="object">7</option>
<option value="8" name="object">8</option>
<option value="all" name="all">Show All</option>
</select>
<input type="submit" name="submit" id="submit" value="submit" size="10">
</form>
<?php
$train[0] ="pencil";
$train[1] = "macaron";
$train[2] = "notes";
$train[3] = "book";
$train[4] = "eraser";
$train[5] = "cake";
$train[6] = "laptop";
$train[7] = "mint";
$train[8] = "cup";
if ($_GET['submit']) {
$train = $_GET['object'];
echo "<p>I have $train!</p>";
}
for ($i = 0; $i < sizeof($train); $i++) {
echo "<li>" . $train[$i] . "</li>";
}
?>
</body>
</html>
There are some mistakes in the code
Select should have name attribute
Need to get object and display results based on the selected option.
Use the below code
<form name="train" method="GET" >
<select name="object">
<option value="0">0</option>
......
<option value="all">Show All</option>
</select>
<input type="submit" name="submit" id="submit" value="submit" size="10">
</form>
PHP code
$train[0] ="pencil";
....
$train[8] = "cup";
if ($_GET['submit']) {
$object = $_GET['object'];
if($object == 'all'){
for ($i = 0; $i < sizeof($train); $i++) {
echo "<li>" . $train[$i] . "</li>";
}
}else{
echo "<p>I have $train[$object]!</p>";
}
}

Populating select box with existing value

I have created a form which allows users to edit existing data within a database, I pull information from one page to the next to populate text boxes and select boxes. I have managed to populate the select box with the correct value but when the update statement goes through it deletes or doesn't recognize the pre-existing value. Can anyone help?
if (isset($_POST['submit'])) {
// Process the form
if (empty($errors)) {
$id = $brand["brandId"];
$brandName = mysql_prep($_POST["brandName"]);
$brandCategory = mysql_prep($_POST["brandCategory"]);
$brandKeyword = mysql_prep($_POST["brandKeyword"]);
$addedBy = mysql_prep($_SESSION['username']);
$query = "UPDATE brands SET ";
$query .= "brandName = '{$brandName}', ";
$query .= "brandCategory = '{$brandCategory}', ";
$query .= "brandKeyword = '{$brandKeyword}', ";
$query .= "addedBy = '{$addedBy}', ";
$query .= "dateTime = CURRENT_TIMESTAMP ";
$query .= "WHERE brandId = '{$id}' ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) == 1) {
// Success
$_SESSION["message"] = "Brand updated.";
redirect_to("search.php");
} else {
// Failure
$_SESSION["message"] = "Brand update failed.";
}
}
} else {
// This is probably a GET request
} // end: if (isset($_POST['submit']))
?>
<?php $layout_context = "user"; ?>
<?php include("../includes/layouts/header.php"); ?>
<?php include("../includes/layouts/navigation.php"); ?>
<div class="section">
<div id="message">
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
</div>
<form id="edit_brands" action="edit_brands.php?id=<?php echo urlencode($brand["brandId"]); ?>" method="post">
<h2>Edit Brand Information: <?php echo htmlentities($brand["brandName"]);?></h2>
<p>
<label for="bname">Brand Name:</label>
<input class="textbox" id="bname" type="text" name="brandName" value="<?php echo htmlentities($brand["brandName"]); ?>" autofocus/>
</p>
<p>
<label for="bcategory">Brand Category:</label>
<select class="textbox" id="bcategory" type="text" name="brandCategory">
<option value=""><?php echo htmlentities($brand["brandCategory"]); ?></option>
<option value="Animation">Animation</option>
<option value="Automotive">Automotive</option>
<option value="Beauty and Fashion">Beauty & Fashion</option>
<option value="Comedy">Comedy</option>
<option value="Cooking and Health">Cooking & Health</option>
<option value="DIY">DIY</option>
<option value="Fashion">Fashion</option>
<option value="Film and Entertainment">Film & Entertainment</option>
<option value="Food and Drink">Food & Drink</option>
<option value="Gaming">Gaming</option>
<option value="Lifestyle">Lifestyle</option>
<option value="Music">Music</option>
<option value="News and Politics">News & Politics</option>
<option value="Science&Education">Science & Education</option>
<option value="Sports">Sports</option>
<option value="Technology">Technology</option>
<option value="Television">Television</option>
</select>
</p>
<p>
<label for="bkeyword">Brand Keyword:</label>
<textarea class="FormElement" id="bkeyword" name="brandKeyword" id="brandKeyword" placeholder=""><?php echo htmlentities($brand["brandKeyword"]); ?></textarea>
</p>
<p>
<input type="submit" class="button" name="submit" value="Edit Brand" onclick="return confirm('Do you wish to edit brand?');"/>
</p>
<p>
Cancel
</p>
</form>
</div>
</div>
The best way is to build the select from an array.
For instance:
<?php
$array = array('Animation', 'Automotive', 'Beauty and Fashion ', ...);
echo '<select class="textbox" id="bcategory" type="text" name="brandCategory">';
foreach ($array as $value){
if($value == htmlentities($brand["brandCategory"]){
echo '<option value='.$value.' selected>'.$value.'</option>';
}else{
echo '<option value='.$value.'>'.$value.'</option>';
}
}
echo '</select>;
This way you can check if the value in the array is the same that the one recieved by post and then add the selected attribute to the option tag.

Simple form does not get $_POST value and cannot submit

Somehow this takes me a day and still does not solve, I have other forms that works properly. But this one looks perfect but it simply refresh the page after I submit the form.
<form action="" enctype='multipart/form-data' name= 'myForm' id="myForm" method='post'>
<label>
<span>Product Name</span><input id="product_name" value='<?php echo $product_name;?>' type="text" name="product_name" disabled >
</label>
<label>
<span>Retail Price</span> <input name='retail_price' value="<?php echo $retail_price;?>" type='text' id='retail_price' size='10' disabled >
</label>
<label>
<span>Discount (%)</span> <input name='discount' value="<?php echo $discount;?>" type='text' id='discount' size='10'disabled >
</label>
<label>
<span>Details</span><textarea id="details" class="product_details" placeholder="For any other reasons, please provide details here" name="details"></textarea>
</label>
<label>
<span>Reason to Report</span>
<select name='reason' id='reason' class="required">
<option value = '' > </option>
<option value = 'price10' > Product price is higher than $9.9</option>
<option value = 'shelf' > Product is off the shelf</option>
<option value = 'no_fs' > Product does not have free-shipping</option>
<option value = 'reject' > Seller does not deliver products</option>
<option value = 'price_not_match' > Product Price does not match on Upto9 </option>
<option value = 'category' > Product is in wrong category </option>
<option value = 'other' > Other reasons</option>
</label>
<label>
<input name='submit' type='submit' id='button' class="button" value="Submit Report"/>
</label>
</form>
THen This is my php code :
echo 'before';
if (isset($_POST['submit'])) {
echo 'after';
var_dump($_POST);
$con= mysqli_connect("xxxxx.com"," admin","xxxxx","xxxxx") or die(mysqli_error($con));
$details=mysqli_real_escape_string($con,$_POST['details']);
$reason=mysqli_real_escape_string($con,$_POST['reason']);
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
$sql="INSERT INTO reports (pid,product_name,listing_price,links,discount,retail_price,details,stock_level,reason,report_time,reporter,reporter,ip) VALUES
('$pid','$product_name','$listing_price','$links','$discount','$retail_price','$details','$stock_level','$reason',now(),'$log_username','$ip')";
$query = mysqli_query($con, $sql);
mysqli_insert_id($con);
mysqli_close($con);
header('Location: ' . $_SERVER['HTTP_REFERER']);
echo "successful!";}
The output is: befre
after I added the sql code var_dump($_POST) gives me nothing, so probably the sql code is wrong...

Categories