Second Select Won't POST - php

I have a form that includes two <select> tags:
<li>
<label for="uname">Select User : </label>
<select id="uname" name="uname">
<option value="3">Kaine McAuley</option>
</select>
</li>
<li>
<label for="uweek">Week Number : </label>
<select id="uweek" name="uweek">
<option value="1">Week 1</option>
<option value="2">Week 2</option>
<option value="3">Week 3</option>
<option value="4">Week 4</option>
<option value="5">Week 5</option>
<option value="6">Week 6</option>
<option value="7">Week 7</option>
<option value="8">Week 8</option>
<option value="9">Week 9</option>
<option value="10">Week 10</option>
<option value="11">Week 11</option>
<option value="12">Week 12</option>
</select>
</li>
That's how it comes out in the browser. I have echo'd the contents of $_POST and uweek doesn't exist in there. However, uname does!
My actual PHP code that creates the form is as follows:
echo '<h2>Update Users</h2><form action="" method="post">
<ul style="list-style: none;">
<li>
<label for="uname">Select User : </label>
<select id="uname" name="uname">';
while($r = mysqli_fetch_assoc($sql))
{
switch($r['Username'])
{
case 'Mike':
case '3rungohan':
case 'Test':
case 'Jestress':break;
default: echo '<option value="' . $r['UserID'] . '">' . $r['RealName'] . '</option>';
}
}
echo '</select></li>
<li>
<label for="uweek">Week Number : </label>
<select id="uweek" name="uweek">';
for($i=1;$i<13;$i++)
{
$week = "Week " . $i;
echo '<option value="' . $i . '">' . $week . '</option>';
}
echo '</select>
</li>
<li>
<label for="uaims">Week Aims : </label><br />
<textarea id="uaims" name="uaims" rows="4" cols="40" required="required"></textarea>
</li>
<li>
<label for="upros">Week Progress : </label><br />
<textarea id="upros" name="upros" rows="4" cols="40" required="required"></textarea>
</li>
<li>
<label for="unote">Week Notes : </label><br />
<textarea id="unote" name="unote" rows="4" cols="40" required="required" placeholder="If no notes, just enter: No notes"></textarea>
</li>
<li>
<input type="submit" value="Submit" />
</li>
</ul>
</form>';
Results of print_r($_POST);
Array ( [uname] => 3 [uaims] => Aims [upros] => Nope [unote] => No )
Similar results from var_dump($_REQUEST);
array(4) { ["uname"]=> string(1) "3" ["uaims"]=> string(4) "Aims" ["upros"]=> string(4) "Nope" ["unote"]=> string(2) "No" }
Once $_POST executes and goes through, my code (at the top of the php document):
Sorry for the endless queries I needed several rounds of info from different tables.
if(!empty($_POST['uname']))
{
foreach($_POST as $k => $v) {$up[$k] = $v;}
$sql2 = mysqli_query($link, "SELECT * FROM jestresstracker WHERE UserID='" . mysqli_real_escape_string($link, $up['uname']) ."' ORDER BY WeekNum DESC LIMIT 1");
$temp = mysqli_fetch_assoc($sql2);
$sql3 = mysqli_query($link, "SELECT * FROM jestress_users WHERE UserID='" . mysqli_real_escape_string($link, $up['uname']) ."' LIMIT 1");
$r = mysqli_fetch_assoc($sql3);
foreach($r as $k => $v) {$User[$k] = $v;}
if(!empty($temp['WeekNum']))
{
if($up['uweek']<=$temp['WeekNum']) {$result = "Error. Update already set for this week. Week Num: " . $temp['WeekNum'];}
}
else {
$ins = mysqli_query($link, "INSERT INTO jestresstracker (UserID, WeekNum, WeekAims, WeekPro, Updated, UpdatedBy, Notes) VALUES('" . mysqli_real_escape_string($link, $up['uname']) . "', '" . mysqli_real_escape_string($link, $up['uweek']) . "', '" . mysqli_real_escape_string($link, nl2br($up['uaims'])) . "', '" . mysqli_real_escape_string($link, nl2br($up['upros'])) . "', NOW(), '" . mysqli_real_escape_string($link, $res['UserID']) . "', '" . mysqli_real_escape_string($link, nl2br($up['unote'])) . "')");
if($ins) {$result = "Successfully updated " . $User['RealName'] . "'s Week " . $up['uweek'] . " post.";var_dump($_REQUEST);}
else {$result = "Error: " . mysqli_error($link);}
}
}
EDIT: Changing the id/name doesn't return different results.

The best friend here in such situation is firebug or any network analysis tool..
Check the headers and make sure that concerned field is indeed posted through..
I think this may help greatly..

It seems there is something wrong with your php or webserver. Try to create $_POST array yourself using this function:
function decodePost(){
$var = file_get_contents('php://input');
$postContent = explode('&',$var);
for($i = 0; $i < count($postContent); $i++){
$postContent[$i] = urldecode($postContent[$i]);
$map = explode('=', $postContent[$i]);
$post[$map[0]] = $map[1];
}
return $post;
}
And see whether anything changes.

You didn't give all the HTML code with the form and all the fields.
Do you have many of them ? Are they big/long ?
Do you have limitation in your php.ini configuration ? Check post_max_size value.
Do you have suhosin module installed on your server ? (check phpinfo() to be sure).
Suhosin may be tricky sometimes, it logs in system logs (eg. /var/log/syslog) instead of logging in webserver logs (eg. Apache logs).
Try checking these default values in suhosin.ini :
suhosin.post.max_array_depth = 100
suhosin.post.max_array_index_length = 64
suhosin.post.max_name_length = 64
suhosin.post.max_totalname_length = 256
suhosin.post.max_value_length = 1000000
suhosin.post.max_vars = 1000
Also check your HTML code with W3 validator, to be sure everything is correctly formatted. Maybe your browser acts weirdly because of that.
Do you have jQuery onSubmit function or something catching the submit in the Javascript code ?

Related

insert more than one array using one query

I want to insert an array of checkboxes, dropdowns, and dates into database. If I checked all the checkbox, all works fine. However, when I checked certain checkboxes, the value of checkboxes can be inserted but not the value of dropdown and date.
This is code for the checkbox, dropdown, and date:
<div class='field'>
<div class='checkboxes'>
<div class='checkbox'>
<input type='checkbox' id='spesimen$i' name='spesimen[]' value='$JenisSpesimen' required minlength='1'/><label>$JenisSpesimen</label><br>
</div>
<div class='select'>
<select id='bilangan$i' name='bilangan[]' class='med' style='display: none;'>
<option></option>
<option value='Pertama'>Pertama</option>
<option value='Kedua'>Kedua</option>
</select>
</div>
<br>
<div class='input' id='tarikh_ambil$i' style='display: none;'>
<input type='text' id='tarikh_ambil_spesimen$i' name='tarikh_ambil_spesimen[]' class='small' readonly/>
</div>
</div>
</div>
And this the process:
$spesimen = $_POST['spesimen'];
$countSpesimen = count($_POST['spesimen']);
$bilangan = $_POST['bilangan'];
//$countBilagan = count($_POST['bilangan']);
$tarikh_ambil = $_POST['tarikh_ambil_spesimen'];
//$countTarikh = count($_POST['tarikh_ambil_spesimen']);
for ( $x = 0; $x < $countSpesimen; $x++)
{
$xx = $x+1;
$SubIDMohon = $IDMohonx.'-'.$xx;
$dd=substr($tarikh_ambil[$x], 0, 2);
$mm=substr($tarikh_ambil[$x], 3, 2);
$yy=substr($tarikh_ambil[$x], 6, 4);
$tarikh_ambil[$x] = $yy."-".$mm."-".$dd;
if($tarikh_ambil[$x] == '--') { $tarikh_ambil[$x] = '0000-00-00'; }
$pdo->exec("insert into simka_spesimen(IDMohon,SubIDMohon, Nama, LainLain, TarikhAmbil, TarikhHantar, TarikhMakmalTerima)
values ('".$IDMohonx."','".$SubIDMohon."','".$spesimen[$x]."','".$bilangan[$x]."','".$tarikh_ambil[$x]."','".$tarikh_hantar_spesimen."','".$tarikh_terima_spesimen."')");
}
I would recommend to wrap your fields into an common name, so that you can run a foreach over each 'fieldset' and then access its corresponding fields, instead of having them separate and independent as you have them now.
HTML would be something like this: (Implement the counter as you wish, but be sure to increment it before adding another set)
<div class='field'>
<div class='checkboxes'>
<div class='checkbox'>
<label><input type='checkbox' id='spesimen$i' name='fieldset[$counter][spesimen]' value='$JenisSpesimen' required minlength='1'/>$JenisSpesimen</label>
</div>
<div class='select'>
<select id='bilangan$i' name='fieldset[$counter][bilangan]' class='med' style='display:none;'>
<option></option>
<option value='Pertama'>Pertama</option>
<option value='Kedua'>Kedua</option>
</select>
</div>
<div class='input' id='tarikh_ambil$i' style='display:none;'>
<input type='text' id='tarikh_ambil_spesimen$i' name='fieldset[$counter][tarikh_ambil_spesimen]' class='small' readonly/>
</div>
</div>
</div>
and your PHP code as follows:
foreach($_POST['fieldset'] as $i=>$fields){
$SubIDMohon = $IDMohonx .'-' . ($i + 1) ;
//If specimen is checked, the value comes with post, otherwise set it to default ''
$specimen = ( isset($fields['specimen']) ) ? $fields['specimen'] : '';
//check if the date is valid format
$date = '';
if(preg_match('^([0-9]{2}-){2}[0-9]{4}$', $fields['tarikh_ambil_spesimen'])){
$date = implode('-', array_reverse( explode('-', $fields['tarikh_ambil_spesimen']) ) );
}
else{
$date = '0000-00-00';
}
$pdo->exec(
"insert into simka_spesimen(IDMohon,SubIDMohon, Nama, LainLain, TarikhAmbil, TarikhHantar, TarikhMakmalTerima)
values (
'" . $IDMohonx . "',
'" . $SubIDMohon . "',
'" . $spesimen . "',
'" . $fields['bilangan'] . "',
'" . $date . "',
'" . $tarikh_hantar_spesimen . "',
'" . $tarikh_terima_spesimen . "'
)"
);
}
Try doing a print_r to your $_POST so you can see how it is structured.
Good luck!

Drop down list in php only working as a default checkbox

I am trying to convert my search page from using a checkbox styled method to being able to use a drop down box to select each separate title header as a potential search option. However when converting this the title drop down box still acts as its old checkbox style, being that it only shows the data that is stored within the title name no matter which title is selected.
PHP Section:
mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error());
// Set up our error check and result check array
$error = array();
$results = array();
// First check if a form was submitted.
// Since this is a search we will use $_GET
if (isset($_GET['search'])) {
$searchTerms = trim($_GET['search']);
$searchTerms = strip_tags($searchTerms); // remove any html/javascript.
if (strlen($searchTerms) < 3) {
$error[] = "Search terms must be longer than 3 characters.";
}else {
$searchTermDB = mysql_real_escape_string($searchTerms); // prevent sql injection.
}
// If there are no errors, lets get the search going.
if (count($error) < 1) {
$searchSQL = "SELECT sid, sbody, stitle, sdescription FROM simple_search WHERE ";
// grab the search types.
$types = array();
$types[] = isset($_GET['body'])?"`sbody` LIKE '%{$searchTermDB}%'":'';
$types[] = isset($_GET['title'])?"`stitle` LIKE '%{$searchTermDB}%'":'';
$types[] = isset($_GET['desc'])?"`sdescription` LIKE '%{$searchTermDB}%'":'';
$types = array_filter($types, "removeEmpty"); // removes any item that was empty (not checked)
if (count($types) < 1)
$types[] = "`sbody` LIKE '%{$searchTermDB}%'"; // use the body as a default search if none are checked
$andOr = isset($_GET['matchall'])?'AND':'OR';
$searchSQL .= implode(" {$andOr} ", $types) . " ORDER BY `stitle`"; // order by title.
$searchResult = mysql_query($searchSQL) or trigger_error("There was an error.<br/>" . mysql_error() . "<br />SQL Was: {$searchSQL}");
if (mysql_num_rows($searchResult) < 1) {
$error[] = "The search term provided {$searchTerms} yielded no results.";
}else {
$results = array(); // the result array
$i = 1;
while ($row = mysql_fetch_assoc($searchResult)) {
$results[] = "{$i}: {$row['stitle']}<br />{$row['sdescription']}<br />{$row['sbody']}<br /><br />";
$i++;
}
}
}
}
function removeEmpty($var) {
return (!empty($var));
HTML Section:
<body>
<?php echo (count($error) > 0)?"The following had errors:<br /><span id=\"error\">" . implode("<br />", $error) . "</span><br /><br />":""; ?>
<form method="GET" action="<?php echo $_SERVER['PHP_SELF'];?>" name="searchForm">
Search For: <input type="text" name="search" value="<?php echo isset($searchTerms)?htmlspecialchars($searchTerms):''; ?>" /><br />
Search In:<br />
Body: <input type="checkbox" name="body" value="on" <?php echo isset($_GET['body'])?"checked":''; ?> /> |
Title: <form action="form_action.asp">
<select name="title">
<option value="Test Simple Search 1">Test Simple Search</option>
<option value="Searching Made Easy 101">Search Made Easy</option>
<option value="Gateway to Information">Gateway to Information</option>
<option value="The Gaming World as we Know it">Gaming World</option>
<option value="Hundreds of Ants Attacking">Ants Attacking</option>
<?php echo isset($_GET['title'])?"checked":''; ?> </select> |
Description: <input type="checkbox" name="desc" value="on" <?php echo isset($_GET['desc'])?"checked":''; ?> /><br />
Match All Selected Fields? <input type="checkbox" name="matchall" value="on" <?php echo isset($_GET['matchall'])?"checked":''; ?><br /><br />
<input type="submit" name="submit" value="Search!" />
</form>
<?php echo (count($results) > 0)?"Your search term: {$searchTerms} returned:<br /><br />" . implode("", $results):""; ?>
The option values that are used are the name as the titles stored within stitle within the mysql database. Have I simply implemented them wrong or is my php used after title completely incorrect?
Any advice on what I can do or any code snippets from yourselves would be very appreciated.
Ok I think I get your issue.
First if you want to select more than one item in a dropdown, then you need to add the multiple attribute to the select tag like this <select name="title" multiple>
Now when the user holds the CTRL key down and clicks entries, each clicked entry gets selected.
Secondly the data identifying the selected items will now be returned as an array in $_GET['title'] so if the first 2 options are selected the $_GET['title'] array would look something like this :-
0 - "Test Simple Search 1"
1 - "Searching Made Easy 101"
Now in order to re-select the items that were selected by the user when they submitted the form you have to set the selected="selected" attribute on each of the <option> tags that equate to the selected rows of the dropdown so they look selected when the user sees the form again.
<?php
function was_i_selected($selected_options, $value) {
if ( in_array($value, $selected_options, true) ) {
return 'selected="selected"';
} else {
return NULL;
}
}
?>
<select name="title" multiple>
<option <?php echo was_i_selected($_GET['title'], 'Test Simple Search 1');?> value="Test Simple Search 1">Test Simple Search</option>
<option <?php echo was_i_selected($_GET['title'], 'Searching Made Easy 101');?> value="Searching Made Easy 101">Search Made Easy</option>
<option <?php echo was_i_selected($_GET['title'], 'Gateway to Information');?> value="Gateway to Information">Gateway to Information</option>
<option <?php echo was_i_selected($_GET['title'], 'The Gaming World as we Know it');?> value="The Gaming World as we Know it">Gaming World</option>
<option <?php echo was_i_selected($_GET['title'], 'Hundreds of Ants Attacking');?> value="Hundreds of Ants Attacking">Ants Attacking</option>
</select>
Now that look very clumsy and we have not checked that $_GET['title'] actually exists, so I would probably do it like this :-
<?php
$options = array(
'Test Simple Search 1' => 'Test Simple Search',
'Searching Made Easy 101' => 'Search Made Easy',
'The Gaming World as we Know it' => 'Gaming World',
'Hundreds of Ants Attacking' => 'Ants Attacking'
);
<select name="title" multiple>
<?php
foreach ( $options as $val => $label ) {
if ( ! empty($_GET['title'] ) {
$sel = in_array($val, $_GET['title'], true) ? 'selected="selected"' : '';
echo '<option ' . $sel . ' value="' . $val . '">' . $label . '</option>';
} else {
echo '<option value="' . $val . '">' . $label . '</option>';
}
}
?>
</select>

Display a set value from a mysqli_query in Select list

I have a form that captures username and type (controls what the user has access to), and writes it to the database. The type is controlled by a select box. Presently there are only three values possible: 1, 4 and 5.
<?php
$sql1 = "SELECT * FROM `usertype` ORDER BY `id`";
$result1 = mysqli_query($con, $sql1);
?>
<form action="" method="post">
<ul>
<li>
Username:<br>
<input type="text" name="username">
</li>
<li>
User Type:<br>
<select name="type">
<?php
while ($data1 = mysqli_fetch_assoc($result1)) {
echo '<option value="' . $data1['id'] . '">' . $data1['type'] . '</option>';
}
?>
</select>
</li>
</ul>
</form>
I have another page on which I want to retrieve a single existing user so that their username or type can be changed. The problem I'm having is with the select box. It's not showing what is in the database. For the particular user I'm testing with, the select box should be showing a type of 4. Instead it is showing a type of 5. Code of the second page is below. What am I doing wrong?
<?php
$user_id = 47;
$sql1 = "SELECT * FROM `usertype` ORDER BY `id`";
$result1 = mysqli_query($con, $sql1);
$sql2 =
"SELECT *
FROM `users`
WHERE `users`.user_id = $user_id";
$result2 = mysqli_query($con, $sql2);
$user_details = mysqli_fetch_assoc($result2);
print_r_html($user_details);
?>
<form action="" method="post">
<ul>
<li>
Username:<br>
<input type="text" name="username" value="<?php echo $user_details['username'];?>">
</li>
<li>
<select name="type">
<?php
while ($data1 = mysqli_fetch_assoc($result1))
{
echo '<option value="' . $data1['id'] . '" success="' . $user_details['type'] . '">' . $data1['type'] . '</option>';
}
?>
</select>
</li>
</ul>
</form>
Here is the array dumb of $user_details:
Array
(
[user_id] => 47
[username] => paul
[password] => 5f4dcc3b5aa765d61d8327deb882cf99
[first_name] => Paul
[last_name] => Smith
[email] => paul#somewhere.com
[email_code] => dda1f2a2c5b29f3b28827716c2dffe61
[active] => 1
[password_recover] => 0
[type] => 4
[allow_email] => 1
[profile] => images/profile/6dc76117b3.jpg
[acct_nbr] => XXXXXXXXX (intentionally masked)
)
The select list does have all the values in it, just the wrong one is displaying as selected.
p.s. I know I don't have a submit button in the form yet.
Thanks.
Thanks to showdev for pointing me in the right direction. The code below accomplished what I needed. It replaces the form in the second block of code posted in the question.
<form action="" method="post">
<ul>
<li>
Username:<br>
<input type="text" name="username" value="<?php echo $user_details['username'];?>">
</li>
<li>
<select name="type">
<?php
while ($data1 = mysqli_fetch_assoc($result1))
{
if ($data1['id'] == $user_details['type']) {
echo '<option value="' . $data1['id'] . '" selected="selected">' . $data1['type'] . '</option>';
} else {
echo '<option value="' . $data1['id'] . '">' . $data1['type'] . '</option>';
}
}
?>
</select>
</li>
</ul>
</form>
I'd do something like this. You want to check if the user type = to the data type. Not sure what the 'success=' is.
<form action="" method="post">
<ul>
<li>
Username:<br>
<input type="text" name="username" value="<?php echo $user_details['username'];?>">
</li>
<li>
<select name="type">
<?php
while ($data1 = mysqli_fetch_assoc($result1))
{
$selected = ($user_details['type'] == $data1['type']) ? 'selected="selected"' : false;
echo '<option value="' . $data1['id'] . '" '.$selected.'>' . $data1['type'] . '</option>';
}
?>
</select>
</li>
</ul>
</form>

php mysql based on user input form

I am having trouble using a checkbox to select one or multiple fields of data for PHP/AJAX to process and display. I have the PHP/AJAX working great on my <select>s but as soon as I try setting up the checkbox all hell breaks lose.
I also am very unsure on how to further prevent SQL injection on the site so if anyone could fill me in a little more about this I would GREATLY appreciate it! I read the link I was provided and just don't understand how bid_param or PDO works exactly.
The ajax script:
(I can't seem to insert the ajax/js so I'll leave a link to the live site)
Link to Agent search page
My php page that displays the data:
<div id="bodyA">
<h1>Find a Local OAHU Agent.</h1>
<!-- This is where the data is placed. -->
</div>
<div id="sideB">
<div class="sideHeader">
<em>Advanced Search</em>
</div>
<form class="formC">
<label for="last">Last Name</label><br />
<select id="last" name="Last_Name" onChange="showUser(this.value)">
<?php
include 'datalogin.php';
$result = mysqli_query($con, "SELECT DISTINCT Last_Name FROM `roster` ORDER BY Last_Name ASC;");
echo '<option value="">' . 'Select an Agent' .'</option>';
while ($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['Last_Name'].'">'.$row['Last_Name'].'</option>';
}
?>
</select>
<label for="company">Company</label><br />
<select id="company" name="users" onChange="showUser(this.value)">
<?php
include 'datalogin.php';
$result = mysqli_query($con, "SELECT DISTINCT Company FROM `roster` ORDER BY Company ASC;");
echo '<option value="">' . 'Select a Company' .'</option>';
while ($row = mysqli_fetch_array($result)) {
if ($row['Company'] == NULL) {
} else {
echo '<option value="'.$row['Company'].'">'.$row['Company'].'</option>';
}
}
?>
</select>
<label for="WorkCity">City</label><br />
<select id="WorkCity" name="WorkCity" onChange="showUser(this.value)" value="city">
<?php
include 'datalogin.php';
$result = mysqli_query($con, "SELECT DISTINCT WorkCity FROM `roster` ORDER BY WorkCity ASC;");
echo '<option value="">' . 'Select a City' .'</option>';
while ($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['WorkCity'].'">'.$row['WorkCity'].'</option>';
}
?>
</select>
<label for="WorkZipCode">Zip Code</label><br />
<select id="WorkZipCode" name="WorkZipCode" onChange="showUser(this.value)">
<?php
include 'datalogin.php';
$result = mysqli_query($con, "SELECT DISTINCT WorkZipCode FROM `roster` ORDER BY WorkZipCode + 0 ASC;");
echo '<option value="">' . 'Select a Zip Code' .'</option>';
while ($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['WorkZipCode'].'">'.$row['WorkZipCode'].'</option>';
}
?>
</select>
<label for="agent">Agent Expertise</label><br />
<label for="ancillary"><input type="checkbox" value="Ancillary" name="Ancillary[]" id="ancillary" />Ancillary</label><br />
<label for="smallgroup"><input type="checkbox" value="Smallgroup" name="Smallgroup[]" id="smallgroup" />Small Group</label><br />
<label for="largegroup"><input type="checkbox" value="LargeGroup" name="LargeGroup[]" id="largegroup" />Large Group</label><br />
<label for="medicare"><input type="checkbox" value="Medicare" name="Medicare[]" id="medicare" />Medicare</label><br />
<label for="longterm"><input type="checkbox" value="LongTerm" name="LongTerm[]" id="longterm" />Long Term Care</label><br />
<label for="individual"><input type="checkbox" value="Individual" name="Individual[]" id="individual" />Individual Plan</label><br />
<label for="tpa"><input type="checkbox" value="TPASelfInsured" name="TPASelfInsured[]" id="tpa" />TPA Self Insured</label><br />
<label for="ppaca"><input type="checkbox" value="CertifiedForPPACA" name="CertifiedForPPACA[]" id="ppaca" />Certified for PPACA</label><br />
</form>
</div>
My php page that pulls the info and places it into a container on the page:
$q = (isset($_GET['q'])) ? $_GET['q'] : false; // Returns results from user input
include 'datalogin.php'; // PHP File to login credentials
$sql="SELECT * FROM `roster` WHERE Company = '".$q."' OR Last_Name = '".$q."' OR WorkCity = '".$q."' OR WorkZipCode = '".$q."' ORDER BY Last_Name ASC";
$result = mysqli_query($con,$sql) // Connects to database or die("Error: ".mysqli_error($con));
echo "<h1>" . "Find a Local OAHU Agent." . "</h1>";
while ($row = mysqli_fetch_array($result)) { // Gets results from the database
echo "<div class='agentcon'>" . "<span class='agentn'>" . "<strong>".$row['First_Name'] . " " .$row['Last_Name'] . "</strong>" . "</span>" . "" . "<span class='email'>".$row['Email'] . "</span>" . "" ."<div class='floathr'></div>";
if ($row['Company'] == NULL) {
echo "<p>";
}
else {
echo "<p>" . "<strong>" .$row['Company'] . "</strong>" . "<br>";
}
echo $row['WorkAddress1'] . " " .$row['WorkCity'] . "," . " " .$row['WorkStateProvince'] . " " .$row['WorkZipCode'] . "<br>";
if ($row['Work_Phone'] !== NULL) {
echo "<strong>" . "Work" . " " . "</strong>" .$row['Work_Phone'] . "<br>";
}
if ($row['Fax'] !== NULL) {
echo "<strong>" . "Fax" . " " . "</strong>" .$row['Fax'] . "<br>";
}
echo "<strong>" . "Agent Expertise:" . "</strong>";
if ($row['Ancillary'] == 1) {
echo " " . "Ancillary" . "/";
}
if ($row['SmallGroup'] == 1) {
echo " " . "Small Group" . "/";
}
if ($row['IndividualPlans'] == 1) {
echo " " . "Individual Plans" . "/";
}
if ($row['LongTermCare'] == 1) {
echo " " . "Long Term Care" . "/";
}
if ($row['Medicare'] == 1) {
echo " " . "Medicare" . "/";
}
if ($row['LargeGroup'] == 1) {
echo " " . "LargeGroup" . "/";
}
if ($row['TPASelfInsured'] == 1) {
echo " " . "TPA Self Insured" . "/";
}
if ($row['CertifiedForPPACA'] == 1) {
echo " " . "Certified For PPACA";
}
echo "</p>" . "</div>";
}
mysqli_close($con);
?>
I appreciate any and all help on this topic! Any time I add the checkbox values to my php file it ends up displaying everyone in the database for all fields in the form.
I am also trying to prevent sql injection on this but how can a user do this if I don't have a field the user can input text into?
EDIT As of today I gave a try with using jQuery to activate the checkboxes and then call some AJAX.
Here is the script I wrote and it is pulling an agent, just not everyone that has that "expertise".
$('input').click(function() {
$.ajax({
url: "process.php",
data: { value: 1},
success: function (data) {
$('#bodyA').html(data);
}
});
});
Here's a quick example of something I recently worked on in which I needed to loop through multiple checkboxes and pass those values into a SQL statement. Although this example happens on a button click, hopefully its something along the lines of what you are trying to accomplish, or at least at start... :)
<?php
$array = array();
if (isset($_POST['medicare'])) {
foreach ($_POST['medicare'] as $value) {
array_push($array, $value);
}
}
// this will return the value of each selected checkbox, separating each with a comma
$result = implode(",", $array);
// if you want to loop through each individually (for example pass each into a SQL statement)
foreach ($_POST['medicare'] as $value) {
// Do your SQL here
// $value will be the value of each selected checkbox (Smallgroup, Largegroup, etc.)
$sql = "insert into tablename(fieldname) values ('$value')"; // just an example
}
?>
<input type="checkbox" name="medicare[]" id="smallgroup" value="Smallgroup" />
<label for="smallgroup">Small Group</label>
<br />
<input type="checkbox" name="medicare[]" id="largegroup" value="Largegroup" />
<label for="largegroup">Large Group</label>
<br />
<input type="checkbox" name="medicare[]" id="medicare" value="Medicare" />
<label for="medicare">Medicare</label>
<br />
<input type="checkbox" name="medicare[]" id="individualplan" value="IndividualPlan" />
<label for="individualplan">Individual Plan</label>
<br />
<input type="submit" value="Submit" id="btnSubmit" name="btnSubmit" />
UPDATE
Instead of setting one variable, try setting a variable for each select control and putting your SQL statement in a foreach loop. I just tested this with some dummy data and didn't have any issues with it.
<?php
$lastname = (isset($_GET['Last_Name'])) ? $_GET['Last_Name'] : false;
$users = (isset($_GET['users'])) ? $_GET['users'] : false;
$workCity = (isset($_GET['WorkCity'])) ? $_GET['WorkCity'] : false;
$WorkZipCode = (isset($_GET['WorkZipCode'])) ? $_GET['WorkZipCode'] : false;
foreach ($_GET['medicare'] as $value) {
//echo $value;
$sql="SELECT * FROM roster WHERE Company = '$users' OR Last_Name = '$lastname' OR WorkCity = '$workCity' OR WorkZipCode = '$WorkZipCode' OR Ancillary = '$value' ORDER BY Last_Name ASC";
}
...continue as you were...
?>
I DID IT!! Wohoo! I ended up just making a separate php page called expertise.php to process the checkboxs using jquery/ajax.
The jQuery that achieved this: (Thank god I went onto the jQuery website to look up functions!)
$('input').click(function() {
$.ajax({
url: "expertise.php",
data: { value: 1},
success: function (data) {
$('#bodyA').html(data);
}
});
});
The PHP page is the same as my process.php page except for the sql:
$sql="SELECT * FROM `roster` WHERE Ancillary = '1' AND SmallGroup = '1' AND CertifiedForPPACA = '1' ORDER BY Last_Name ASC";
If anyone would enlighten me more on making this better protected against sql injections, feel free to!
Agent Search Page
Well I at least got both parts of the search working but a new problem has arose :p
Now in the sql I can use AND or OR, with AND it pulls only agents that have everyone of those expertise and with OR it seems to pull everyone. Any ideas?

List Box Should be Drop down

to every one
I have some values in my data base i Want to display them with check boxes.
those values should be display when i click at the button. This should not in combo box.
because I want to post multiple values at one time.
Please help with thanks
<?php
$womenlist=mysql_query("select * from tbl_cycleduraion where user_id=$_SESSION[user_id]");
$gs=0;
while($girlslist=mysql_fetch_array($womenlist))
{
$gs++;
?>
<li style="background-color:#CCC; width:150px;"><label for="chk1"><input type="checkbox" name="chk_<?php echo $gs?>" id="chk<?php echo $gs?>" value="<?php echo $girlslist['calName'];?>" <?php if($_REQUEST['chk_'.$gs]==$girlslist['calName']){?> checked="checked"<?php }?>><?php echo $girlslist['calName']." ".$girlslist['calDesc']; ?> </label></li>
<?php }?>
You could limit the number of columns in your query (not SELECT * ...). You've put the <input> inside the <label>. The <label>'s for="" attribute is hardcoded as chk1. You could take out the inline style="" on the <li> and put it into a stylesheet. I've "tidied" it up a bit (untested):
$womenlist = mysql_query("select * from tbl_cycleduraion where user_id=$_SESSION[user_id]");
$gs = 0;
while( $girlslist = mysql_fetch_array($womenlist) )
{
$gs++;
echo '<li style="background-color:#CCC; width:150px;">'
. '<label for="chk' . $gs . '">' . $girlslist['calName'] . ' ' . $girlslist['calDesc'] . '</label>'
. '<input type="checkbox" name="chk_' . $gs . '" id="chk' . $gs . '" value="' . $girlslist['calName'] . '"
. (($_REQUEST['chk_'.$gs]==$girlslist['calName']) ? 'checked="checked"' : '') . '></li>';
}
Not sure entirely what you're asking for here (as it looks like you already have this working with checkboxes), but you can in fact post multiple values with a select box. You just use the multiple attribute, and specify the name as an array with the square brackets:
<form action="yourscript.php" method="post">
<select name="women[]" multiple="multiple">
<option value="woman1_name">Woman 1</option>
<option value="woman2_name">Woman 2</option>
<option value="woman3_name">Woman 3</option>
</select>
<input type="submit" />
</form>
If you post a form with this, selecting woman 2 & 3, var_dump($_POST); yields:
array(1) {
["women"]=>
array(2) {
[0]=>
string(11) "woman2_name"
[1]=>
string(11) "woman3_name"
}
}
Alternatively, if you want the values of your checkboxes to come through in a similar fashion, change them so they all have the same name, but with the square brackets on the end. This HTML would yield similar POST data:
<input type="checkbox" name="women[]" value="Woman 1" />
<input type="checkbox" name="women[]" value="Woman 2" />
<input type="checkbox" name="women[]" value="Woman 3" />
So, to create a dropdown using this, here's an adaptation of your code. I believe this is what you're after:
<?php
$options = '';
$womenlist=mysql_query("select * from tbl_cycleduraion where user_id=$_SESSION[user_id]");
while($woman=mysql_fetch_array($womenlist)) {
$options .= '<option value="'.$woman['calName'].'"'.((!empty($_REQUEST) && in_array($woman['calName'],$_REQUEST['women'])) ? ' selected="selected"' : '').'>'.$woman['calName'].' '.$woman['calDesc'].'</option>';
}
?>
<label for="women">Women:</label>
<select id="women" name="women[]" multiple="multiple">
<?php echo $options; ?>
</select>

Categories