insert more than one array using one query - php

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!

Related

PHP - unable to get $_POST variables [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 2 years ago.
I am trying to make a posting system for a project I am working on. Problem is, for some reason, all $_POST values are null, even if they are supposed to be set. As a result, my PHP script does not work.
I can't tell why this is the case, as it was working fine just yesterday. How can I fix this?
<?php
function show_posts($posts, $parent_id = -1) {
$html = '';
if ($parent_id != -1) {
// If the posts are replies sort them by the "submit_date" column
array_multisort(array_column($posts, 'submit_date'), SORT_ASC, $posts);
}
$resultCount = 0;
// Iterate the posts using the foreach loop
foreach ($posts as $post) {
if (($_GET['search_query']) != "") {
if ($post['parent_id'] == $parent_id) {
if (strpos(implode($post), $_GET['search_query'])) {
$resultCount++;
//check if optional variables are not set
$screenshot = $post['screenshot'];
if ($screenshot.trim() == "") {
$screenshot = "https://ppcplanet.org/images/noscreenshot.png";
}
$serial = $post['serial'];
if ($serial.trim() == "") {
$serial = "n/a";
}
$source = $post['source'];
if ($source.trim() == "") {
$source = "n/a";
}
$html .= '
<div class="post">
<br><br>
<div>
<h3 style="color: white;" class="name"><b>By ' . htmlspecialchars($post['postauthor'], ENT_QUOTES) . '</b></h3>
<span class="date">' . time_elapsed_string($post['submit_date']) . '</span>
</div>
<br>
<img class="image" style="width: 256px; height: 256px; overflow: hidden; object-fit: cover;" src=' . nl2br(htmlspecialchars($screenshot, ENT_QUOTES)) . ' alt="Screenshot"/>
<br><br>
<h2 class="content"><b>' . nl2br(htmlspecialchars($post['name'], ENT_QUOTES)) . '</b></h2>
<br>
<p class="content"><b>Description: </b>' . nl2br(htmlspecialchars($post['content'], ENT_QUOTES)) . '</p>
<p class="content"><b>Serial: </b>' . nl2br(htmlspecialchars($serial, ENT_QUOTES)) . ' </p>
<p class="content"><b>Original Source: </b> ' . nl2br(htmlspecialchars($post['source'], ENT_QUOTES)) .'</p>
<p class="content"><b>Type: </b>' . nl2br(htmlspecialchars($post['type'], ENT_QUOTES)) . ' </p>
<p class="content"><b>Category: </b>' . nl2br(htmlspecialchars($post['category'], ENT_QUOTES)) . ' </p>
<a class="reply_post_btn" href="#" data-post-id="' . $post['id'] . '">Add on... (ex. another version, manual, etc.)</a>
' . show_write_post_form($post['id']) . '
<div class="replies">
' . show_posts($posts, $post['id']) . '
</div>
</div>
<br><br><br>
';
ob_clean();
echo(strval($resultCount) . ' result(s) found for "' . $_GET['search_query'] . '"'); //display number of results
}
}
}
else
{
//add each post to HTML variable
if ($post['parent_id'] == $parent_id) {
//check if optional variables are not set
$screenshot = $post['screenshot'];
if ($screenshot.trim() == "") {
$screenshot = "https://ppcplanet.org/images/noscreenshot.png";
}
$serial = $post['serial'];
if ($serial.trim() == "") {
$serial = "n/a";
}
$source = $post['source'];
if ($source.trim() == "") {
$source = "n/a";
}
$html .= '
<div class="post">
<h2></h2>
<br><br>
<div>
<h3 style="color: white;" class="name"><b>By ' . htmlspecialchars($post['postauthor'], ENT_QUOTES) . '</b></h3>
<span class="date">' . time_elapsed_string($post['submit_date']) . '</span>
</div>
<br>
<img class="image" style="width: 256px; height: 256px; overflow: hidden; object-fit: cover;" src=' . nl2br(htmlspecialchars($screenshot, ENT_QUOTES)) . ' alt="Screenshot"/>
<br><br>
<h2 class="content"><b>' . nl2br(htmlspecialchars($post['name'], ENT_QUOTES)) . '</b></h2>
<br>
<p class="content"><b>Description: </b>' . nl2br(htmlspecialchars($post['content'], ENT_QUOTES)) . '</p>
<p class="content"><b>Serial: </b>' . nl2br(htmlspecialchars($serial, ENT_QUOTES)) . ' </p>
<p class="content"><b>Original Source: </b> ' . nl2br(htmlspecialchars($post['source'], ENT_QUOTES)) .'</p>
<p class="content"><b>Type: </b>' . nl2br(htmlspecialchars($post['type'], ENT_QUOTES)) . ' </p>
<p class="content"><b>Category: </b>' . nl2br(htmlspecialchars($post['category'], ENT_QUOTES)) . ' </p>
<a class="reply_post_btn" href="#" data-post-id="' . $post['id'] . '">Add on... (ex. another version, manual, etc.)</a>
' . show_write_post_form($post['id']) . '
<div class="replies">
' . show_posts($posts, $post['id']) . '
</div>
</div>
<br><br><br>
';
}
}
}
return $html;
}
// This function is the template for the write post form
function show_write_post_form($parent_id = -1) {
$rand = randomIdentifier(); //generate random identifier string
$html = '
<div class="write_post" data-post-id="' . $parent_id . '">
<form>
<h2 style="color: white;">New Post</h2>
<br>
<input name="parent_id" type="hidden" value="' . $parent_id . '">
<label for="name">Title:</label>
<input style="width: 100%;" id="name" name="name" type="text" placeholder="Enter a title..." required>
<br><br>
<label for="screenshot">Screenshot (if applicable):</label>
<input style="width: 100%;" id="screenshot" name="screenshot" type="url" placeholder="Screenshot URL">
<br><br>
<label for="type">URL:</label>
<input style="width: 100%;" id="url" name="url" type="url" placeholder="Download URL" required>
<br><br>
<label for="type">Description:</label>
<textarea name="content" id="content" placeholder="Write a description..." required></textarea>
<br><br>
<label for="type">Original Source (if known):</label>
<input style="width: 100%;" id="source" name="source" type="url" placeholder="Original Source URL">
<br><br>
<label for="type">Serial (if applicable):</label>
<input style="width: 100%;" id="serial" name="serial" type="text" placeholder="Serial">
<br><br>
<label for="name">Your Name/Nickname:</label>
<input style="width: 100%;" id="postauthor" name="postauthor" type="text" placeholder="Enter your name..." required>
<br><br>
<br>
<label for="type">Choose a type:</label>
<select name="type" id="type">
<option value="freeware">Freeware</option>
<option value="abandonware">Abandonware</option>
<option value="self-made">I wrote it myself</option>
</select>
<label for="category">Category:</label>
<select name="category" id="category">
<option value="app">App</option>
<option value="game">Game</option>
<option value="driver">Driver</option>
<option value="manual">Manual</option>
<option value="setup">Setup</option>
<option value="ROM">ROM</option>
<option value="other">Other</option>
</select>
<br><br>
<h2 style="color: white;">Post identifier string</h2>
<input name="identifier" id="identifier" style="width: 100%;" readonly="true" type="text"" value="' . $rand . '">
<br>
<p style="color: red;">This is your post identifier string. It can be used to delete this post in the future without having to contact an admin. <b>Make sure you do not lose it!</b></p>
<br><br>
<h2 style="color: white;">Make sure your submission meets the following criteria:</h2>
<br>
<p>๐Ÿ™‚ This submission is appropriate and doesn\'t have any mature content. - We want PPC Planet to be a safe place for people of all ages. Inappropriate submissions will be removed!</p>
<p>๐Ÿ‘ This submission is either freeware, abandonware, or self-made. - No piracy! It\'s not fair to the developer(s).</p>
<p>๐Ÿ’ป This submission has been tested, and works as advertised. - We don\'t want to have a bunch of broken software on the archive.</p>
<p>๐Ÿงพ This submission is not already on the archive. - Be sure that you are posting something unique!</p>
<p>๐Ÿ“ฑ This submission is related to Pocket PCs. - Remember, this is an archive of Pocket PC software.</p>
<br>
<p><b>By following these rules, we can make the archive a fun (and totally rad) place for everyone!</b></p>
<br><br>
<p style="color: red; font-size: xx-large; "><b>Make sure you have proofread your post, as you will not be able to edit it once it has been posted. Additionally, make sure you write your down identifier string somewhere if you have not already.</b></p>
<br><br>
<button type="submit">Create Post</button>
<br><br>
</form>
</div>
';
return $html;
}
if (isset($_GET['search_query'])) {
// Check if the submitted form variables exist
if (($_POST['name']).trim() != "") {
$stmt = $pdo->prepare('INSERT INTO posts (page_id, parent_id, name, screenshot, url, content, serial, type, category, identifier, source, postauthor, submit_date) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,NOW())');
$stmt->execute([ 1, $_POST['parent_id'], $_POST['name'], $_POST['screenshot'], $_POST['url'], $_POST['content'], $_POST['serial'], $_POST['type'], $_POST['category'], $_POST["identifier"], $_POST["source"], $_POST["postauthor"] ]);
exit('Your post has been submitted! You can reload the page to see it.');
}
else
{
// Get all posts by the Page ID ordered by the submit date
$stmt = $pdo->prepare('SELECT * FROM posts WHERE page_id = ? ORDER BY submit_date DESC');
$stmt->execute([ 1 ]);
$posts = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Get the total number of posts
$stmt = $pdo->prepare('SELECT COUNT(*) AS total_posts FROM posts WHERE page_id = ?');
$stmt->execute([ 1 ]);
$posts_info = $stmt->fetch(PDO::FETCH_ASSOC);
}
} else {
exit('No search query specified!');
}
function randomIdentifier() {
$pass = 0;
$complete = false;
while (!$complete)
{
//generate random identifier string until it is unique
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()';
$pass = array();
$alphaLength = strlen($alphabet) - 1;
for ($i = 0; $i < 100; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
include('mysqlconnect.php');
$pdo = new PDO('mysql:host=' . $DATABASE_HOST . ';dbname=' . $DATABASE_NAME . ';charset=utf8', $DATABASE_USER, $DATABASE_PASS);
$data = implode($pass);
$stmt = $pdo->prepare( "SELECT identifier FROM posts WHERE identifier =:id" );
$stmt->bindParam(':id', $data, PDO::PARAM_STR);
$stmt->execute();
$myIdentifier = $stmt->fetch();
if (!$myIdentifier) {
//identifier is unique
$complete = true;
}
}
return $data;
}
?>
<?=show_write_post_form()?>
<?=show_posts($posts)?>
You can try it out for yourself here. All help is appreciated!
$_POST in PHP collects any variables submitted in the body of a HTTP POST request.
However your HTML form is submitting a GET request (which is the default if you don't specify the method). You can fix this by specifying the method attribute of the form:
<form method="post">
$_POST superglobal is only available in POST requests. You seem to be rendering your content in a GET request.

Using ISSET with checkboxes

I am working on a wordpress search form to refine the current search and what Im trying to do is have the search results page with the search from and it's values set based on the query.
So far I've been successful in doing so with single select drop downs and single checkboxes like so --
<!-- SINGLE SELECT -->
<select name="baths" class="form-control">
<?php if (isset($_GET['baths'])) {
$bths = $_GET['baths']; ?>
<option value="<?php echo $bths; ?>"><?php echo $bths; ?></option>
<?php } else { ?>
<option value="Any">Any</option>
<?php } ?>
<option value="Any">Any</option>
<option value="1">1+</option>
<option value="2">2+</option>
<option value="3">3+</option>
<option value="4">4+</option>
<option value="5">5+</option>
<option value="6">6+</option>
<option value="7">7+</option>
<option value="8">8+</option>
<option value="9">9+</option>
<option value="10">10+</option>
</select>
<!-- SINGLE CHECKBOX -->
<input type="checkbox" name="dogs" class="styled" value ="yes" <?php if (isset($_GET['dogs'])) { ?>checked<?php } ?>>
That works, but for the multiple values it doesn't. This is my function to generate a set of checkboxes to select amenities -
<?php
$amenity_array = array();
$id = get_query_var('site');
if (!empty($id)) {
$property_amenities = get_post_meta($id, 'imic_property_amenities', true);
global $imic_options;
foreach ($property_amenities as $properties_amenities_temp) {
if ($properties_amenities_temp != 'Not Selected') {
array_push($amenity_array, $properties_amenities_temp);
}
}
}
global $imic_options;
if (isset($imic_options['properties_amenities']) && count($imic_options['properties_amenities']) > 1) {
foreach ($imic_options['properties_amenities'] as $properties_amenities) {
$am_name = strtolower(str_replace(' ', '', $properties_amenities));
$check = '';
if (in_array($properties_amenities, $amenity_array)) {
$check = 'checked="checked"';
}
<!-- HERE I TRY TO FIND THE SELECTED CHECKBOXES AND CHECK THEM OFF -->
if (isset($_GET['p_am'])) {
$ams = $_GET['p_am'];
echo '<div class="checkbox"><input type="checkbox" name="p_am" ' . $check . ' class="styled" value ="' . $properties_amenities . '"><label for="' . $am_name . '">' . $properties_amenities . '</label></div>';
} else {
echo '<div class="checkbox"><input type="checkbox" name="p_am" ' . $check . ' class="styled" value ="' . $properties_amenities . '"><label for="' . $am_name . '">' . $properties_amenities . '</label></div>';
}
<!-- END ISSET -->
}
} else {
_e('There is no Properties Amenities', 'framework');
}
?>
For the multi select drop down I am using bootstrap multiselect, so on my template the code looks like this --
<select name="property_type[]" id="pt-multi" class="form-control multi-select2" multiple="multiple">
<?php
$terms = get_terms( "property-type", array( 'hide_empty' => 0 ) );
$count = count($terms);
if ( $count > 0 ){
echo "<option value='Any'>All</option>";
foreach ( $terms as $term ) {
echo "<option value='" . $term->slug . "'>" . $term->name . "</option>";
}
}
?>
</select>
On the page it renders out as ---
<select name="property_type[]" id="pt-multi" class="form-control multi-select2 iOSselect" multiple="multiple" style="display: none;">
<option value="Any">All</option>
<option value="co-op">Co-Op</option>
<option value="condo">Condo</option>
</select>
<div class="btn-group" style="width: 100%;">
<button type="button" class="multiselect dropdown-toggle btn btn-default form-control multi-select2" data-toggle="dropdown" title="Property Type" style="width: 100%; overflow: hidden; text-overflow: ellipsis;">
<span class="multiselect-selected-text">Property Type</span>
<b class="caret"></b></button>
<ul class="multiselect-container dropdown-menu pull-right">
<li class="multiselect-item multiselect-all">
<a tabindex="0" class="multiselect-all">
<label class="checkbox"><input type="checkbox" value="multiselect-all"> Select all</label>
</a>
</li>
<li>
<a tabindex="0"><label class="checkbox">
<input type="checkbox" value="Any"> All</label>
</a>
</li>
<li>
<a tabindex="0"><label class="checkbox"><input type="checkbox" value="co-op"> Co-Op</label>
</a>
</li>
<li>
<a tabindex="0"><label class="checkbox"><input type="checkbox" value="condo"> Condo</label>
</a>
</li>
</ul>
</div>
Any ideas?
UPDATE
Using my code from above my amenities checkbox renders out on the page like so ---
<div>
<label>amenities</label>
<div class="checkbox">
<input type="checkbox" name="p_am" class="styled" value="Doorman (Full Time)">
<label for="doorman(fulltime)">Doorman (Full Time)</label>
</div>
<div class="checkbox">
<input type="checkbox" name="p_am" class="styled" value="Doorman (Part Time)"><label for="doorman(parttime)">Doorman (Part Time)</label>
</div>
<div class="checkbox">
<input type="checkbox" name="p_am" class="styled" value="Laundry (In-Unit)"><label for="laundry(in-unit)">Laundry (In-Unit)</label>
</div>
<div class="checkbox">
<input type="checkbox" name="p_am" class="styled" value="Fitness Center"><label for="fitnesscenter">Fitness Center</label>
</div>
</div>
This works with my search function allowing users to check off which amenities to include in the query string --
p_am=Doorman+%28Full+Time%29&p_am=Indoor+Pool
My search function is extensive but as far the relevant parts to the amenities -
$amenities = isset($_GET['p_am'])?$_GET['p_am']:'';
$amenities = ($amenities == __('Any', 'framework')) ? '' : $amenities;
// .....
if (!empty($amenities)) {
array_push($meta_query,array(
'key' => 'imic_property_amenities',
'value' => $amenities,
'compare'=>'LIKE'
));
}
UPDATE
In regards to setting the dropdown options for the bootstrap multiselect, I'm trying to set the options using the following code -
<?php
$taxonomyName = "city-type";
$parent_terms = get_terms( $taxonomyName, array( 'parent' => 0, 'orderby' => 'slug', 'hide_empty' => false ) );
echo "<select name='property_nhb[]' class='form-control multi-select' id='p-nhb' multiple>";
foreach ( $parent_terms as $pterm ) {
// echo "<option data-val='" . $pterm->slug . "' value='Any' " . $selected . ">Any</option>";
//Get the Child terms
$terms = get_terms( $taxonomyName, array( 'parent' => $pterm->term_id, 'orderby' => 'slug', 'hide_empty' => false ) );
foreach ( $terms as $term ) {
if(isset($_GET['property_nhb[]'])) {
$pnhb = $_GET['property_nhb'];
$selected = 'selected';
}
echo "<option data-val='" . $pterm->slug . "' value='" . $term->slug . "' " . $selected . " >" . $term->name . "</option>";
}
}
echo "</select>";
?>
My current search function code
This seems a little backwards for creating a search form - it seems more like you're generating a form for each individual result? Annotated code and comments below. I've tried to keep to your coding style in my answer.
$amenity_array = array();
$id = get_query_var('site');
// this first section gets the selected meta properties for the queried property (if available)
// [skipping for brevity ]
global $imic_options;
if (isset($imic_options['properties_amenities']) && count($imic_options['properties_amenities']) > 1) {
// this loops over all of the globally defined properties
foreach ($imic_options['properties_amenities'] as $properties_amenities) {
// gets the name of the property
$am_name = strtolower(str_replace(' ', '', $properties_amenities));
// and sets up to check the box if the property has the defined amenity
// if this is for a search form, why check boxes based on a result?
$check = '';
if (in_array($properties_amenities, $amenity_array)) {
// note: this only really needs to be 'checked'
$check = 'checked="checked"';
}
Here's where things go a little cross-purposes, though.
if (isset($_GET['p_am'])) {
$ams = $_GET['p_am'];
echo '<div class="checkbox"><input type="checkbox" name="p_am" ' . $check . ' class="styled" value ="' . $properties_amenities . '"><label for="' . $am_name . '">' . $properties_amenities . '</label></div>';
} else {
echo '<div class="checkbox"><input type="checkbox" name="p_am" ' . $check . ' class="styled" value ="' . $properties_amenities . '"><label for="' . $am_name . '">' . $properties_amenities . '</label></div>';
}
This says that all checkboxes have the same name ("p_am") instead of using the loop name for the amenity ($am_name) or some form combination if you want all amenities in the same search input array (e.g. "p_am[$am_name]").
Each checkbox would also change the value of $check if supplied to the $_GET array.
$ams = $_GET['p_am'];
if (isset($ams[$am_name])) {
$check = 'checked';
}
Each checkbox would have name="p_am['.$am_name.']" as the name.
echo '<div class="checkbox"><input type="checkbox" name="p_am[' . $am_name . ']" ' . $check . ' class="styled" value ="' . $properties_amenities . '"><label for="' . $am_name . '">' . $properties_amenities . '</label></div>';
If you want each of the amenities to have unique names (looking at the original checkbox which isn't called p_am at all) and not be in an array in PHP, then you would just use the loop name for the amenity ($am_name), like so:
if (isset($_GET[$am_name])) {
$check = 'checked';
}
Each checkbox would have name="'.$am_name.'" as the name.
UPDATE: after the OP was updated, it looks like every checkbox needs to have the same name, but not be keyed values. For this situation, your checkboxes should be called p_am[] (on both search page an original page), and you need to use something like in_array() instead of isset() to check the result, like so:
if (in_array($properties_amenities, $_GET['p_am'])) {
$check = 'checked';
}
Additional note - you're also using $am_name for the label, without actually setting the id attribute on the checkbox to match to, as well as not stripping out non-id characters (like parentheses), so the label association won't work.
echo '<div class="checkbox"><input type="checkbox" name="' . $am_name . '" ' . $check . ' class="styled" value ="' . $properties_amenities . '"><label for="' . $am_name . '">' . $properties_amenities . '</label></div>';
For the bootstrap select, you're just missing a check for which options are selected:
<select name="property_type[]" id="pt-multi" class="form-control multi-select2" multiple="multiple">
<?php
$terms = get_terms( "property-type", array( 'hide_empty' => 0 ) );
$count = count($terms);
if ( $count > 0 ){
echo "<option value='Any'>All</option>";
foreach ( $terms as $term ) {
// if the option is 'checked', you need to add the 'selected' atttibute here
echo "<option value='" . $term->slug . "'>" . $term->name . "</option>";
}
}
?>
</select>
So the inside of the loop would look something like this instead:
// for efficiency's sake should live outside the loop as a one-off, but here for illustrative purposes
$types = $_GET['property_type'];
$selected = isset($types[$term->slug]) ? 'selected' : '';
echo "<option value='" . $term->slug . "'" . $selected . ">" . $term->name . "</option>";
If you're using an older version of bootstrap select, you may need to have the selected string be 'selected="selected" or data-selected="true", depending on the version you're using. For a current version, the above string should be fine.
If the <select> isn't meant to be an array of options either (i.e. not multiple), then the [] should be removed from the name, and would operate similarly to the checkbox code:
<select name="property_type" id="pt-multi" class="form-control multi-select2">
<?php
$terms = get_terms( "property-type", array( 'hide_empty' => 0 ) );
$count = count($terms);
if ( $count > 0 ){
echo "<option value='Any'>All</option>";
foreach ( $terms as $term ) {
$type = $_GET['property_type'];
$selected = isset($type) && $type == $term-slug ? 'selected' : '';
echo "<option value='" . $term->slug . "'" . $selected . ">" . $term->name . "</option>";
}
}
?>
</select>
The original HTML for the <select> doesn't actually 'work' as such either - all it's doing is adding a duplicate <option> to the top of the options list, and because nothing is selected, the form will treat the duplicate created at the top as 'selected' for the <select>.
UPDATE 2: the reason that the search function is breaking with an array of checkbox inputs is because you are using the LIKE comparison for your meta query. From the documentation on WordPress Meta Query:
It can be an array only when compare is 'IN', 'NOT IN', 'BETWEEN', or 'NOT BETWEEN'.
The documentation also shows examples of how to join these together. Since you haven't supplied how you're actually making the search query this is guessing a little, but it looks like for an array of checkboxes your code should be something similar to:
if (!empty($amenities)) {
foreach ($amenities as $amenity) {
array_push($meta_query, array(
'key' => 'imic_property_amenities',
'value' => $amenity,
'compare' => 'LIKE'
));
}
}
As with the examples in the documentation, you'll need to make sure there's a relation => 'OR' or relation => 'AND' to define how you want your search to operate.
what Fred's meant in the comment is something like this:
<input type="checkbox" value="condo" name="var_name[]">
the [] at the end of the name attribute is to tell PHP that it should treat the variable as an array.
and then in the PHP script, you can just check for the array length using somthing like:
$arr = $_POST['var_name']; echo count($arr);
based on leith's comment, if it is auto generated, then you should not be bothered to check the checkboxes manually.
instead, just make the selected options be selected, for example:
<?php
$selections = $_GET['property_type']; // or something similar
?>
<select name="property_type[]" id="pt-multi" class="form-control multi-select2" multiple="multiple">
<?php
$terms = get_terms( "property-type", array( 'hide_empty' => 0 ) );
$count = count($terms);
if ( $count > 0 ){
echo "<option value='Any'>All</option>";
foreach ( $terms as $term ) {
$selected = in_array($term->slug, $selections);
echo "<option value='" . $term->slug . "' " . ($selected?' selected':'') . ">" . $term->name . "</option>";
}
}
?>
</select>
see this fiddle https://jsfiddle.net/u1w158tp/
in it you just selected the options and it will automatically checked the checkboxes
Your checkboxes has the same name. Try to add different name or use "p_am[]" to treat them as array.

Trying to update mysql database form in php

My database manages to retrieve values when I navigate from the previous page.
When I click the 'Update Product' button, the line Update product appears. What I want is when I click the 'Update Product' button, and have modified a record beforehand, I would hope to update the database with the values as well and a confirmation message is displayed to confirm this.
Code:
<form id="updateForm" name="updateForm" action="<?php echo "?mode=update&ID=" . $productDetails["ID"]; ?>" method="post">
<div>
<label for="updateFormProductCostPrice">ID</label>
<input id="updateFormProductCostPrice" name="ID" type="text" readonly
value="<?php echo $productDetails["ID"]; ?>">
</div>
<div>
<label for="updateFormProductName">Film Name</label>
<input id="updateFormProductName" name="FilmName" type="text"
value="<?php echo $productDetails["FilmName"]; ?>">
</div>
<div>
<label for="updateFormProductDescription">Producer</label>
<input id="Producer" name="productDescription" type="text"
value="<?php echo $productDetails["Producer"]; ?>">
</div>
<div>
<label for="updateFormProductPrice">Year Published</label>
<input id="updateFormProductPrice" name="YearPublished" type="text"
value="<?php echo $productDetails["YearPublished"]; ?>">
</div>
<div>
<label for="updateFormProductStock">Stock:</label>
<input id="updateFormProductStock" name="Stock" type="text"
value="<?php echo $productDetails["Stock"]; ?>">
</div>
<div>
<label for="updateFormProductEan">Price:(&#163)</label>
<input id="updateFormProductEan" name="Price" type="text"
value="<?php echo $productDetails["Price"]; ?>">
</div>
<div>
<input id="updateSubmit" name="updateSubmit" value="Update product" type="submit">
</div>
</form>
PHP:
if (((!empty($_GET["mode"])) && (!empty($_GET["ID"]))) && ($_GET["mode"] == "update")) {
echo "<h1>Update product</h1>";
if (isset($_POST["updateSubmit"])) {
if ((!empty($_POST["ID"])) && (!empty($_POST["FilmName"]))
&& (!empty($_POST["Producer"])) && (!empty($_POST["YearPublished"]))
&& (!empty($_POST["Stock"])) && (!empty($_POST["Price"]))) {
$query = "UPDATE ProductManagement "
. "SET FilmName = '" . $_POST["FilmName"] . "', "
. "Producer = '" . $_POST["Producer"] . "', "
. "YearPublished = '" . $_POST["YearPublished"] . "', "
. "Stock = " . $_POST["Stock"] . ", "
. "Price = '" . $_POST["Price"] . "' "
. "WHERE ID=" . $_GET['ID'] . ";";
$result = mysqli_query($connection, $query);
if ($result == false) {
echo "<p>Updating failed.</p>";
} else{
echo "<p>Updated</p>";
}
}
}
}
So I need the database to update what new value I have entered and it once the 'Update product' Button is pressed, the original value appears and the value is not updated on the database. Why is this? I don't get any error messages. Thanks
The error is that you dont POST the ID but you GET the ID value. input boxes with the readonly attribute don't post values.
change:
if ((!empty($_POST["ID"])) && (!empty($_POST["FilmName"]))
to:
if ((!empty($_GET["ID"])) && (!empty($_POST["FilmName"]))
Edit: Total changes to make to make this work:
HTML:
<form id="updateForm" name="updateForm" action="<?php echo "?mode=update&ID=" . $productDetails["ID"]; ?>" method="post">
<div>
<label for="updateFormProductID">ID</label>
<input id="updateFormProductID" name="ID" type="text" readonly
value="<?php echo $productDetails["ID"]; ?>">
</div>
<div>
<label for="updateFormProductName">Film Name</label>
<input id="updateFormProductName" name="FilmName" type="text"
value="<?php echo $productDetails["FilmName"]; ?>">
</div>
<div>
<label for="updateFormProductProducer">Producer</label>
<input id="updateFormProductProducer" name="Producer" type="text"
value="<?php echo $productDetails["Producer"]; ?>">
</div>
<div>
<label for="updateFormProductYearPublished">Year Published</label>
<input id="updateFormProductYearPublished" name="YearPublished" type="text"
value="<?php echo $productDetails["YearPublished"]; ?>">
</div>
<div>
<label for="updateFormProductStock">Stock:</label>
<input id="updateFormProductStock" name="Stock" type="text"
value="<?php echo $productDetails["Stock"]; ?>">
</div>
<div>
<label for="updateFormProductPrice">Price:(&#163)</label>
<input id="updateFormProductPrice" name="Price" type="text"
value="<?php echo $productDetails["Price"]; ?>">
</div>
<div>
<input id="updateSubmit" name="updateSubmit" value="Update product" type="submit">
</div>
</form>
PHP:
if (((!empty($_GET["mode"])) && (!empty($_GET["ID"]))) && ($_GET["mode"] == "update")) {
echo "<h1>Update product</h1>";
if (isset($_POST["updateSubmit"])) {
if ((!empty($_GET["ID"])) && (!empty($_POST["FilmName"]))
&& (!empty($_POST["Producer"])) && (!empty($_POST["YearPublished"]))
&& (!empty($_POST["Stock"])) && (!empty($_POST["Price"]))) {
$query = "UPDATE ProductManagement "
. "SET FilmName = '" . $_POST["FilmName"] . "', "
. "Producer = '" . $_POST["Producer"] . "', "
. "YearPublished = '" . $_POST["YearPublished"] . "', "
. "Stock = " . $_POST["Stock"] . ", "
. "Price = '" . $_POST["Price"] . "' "
. "WHERE ID=" . $_GET['ID'] . ";";
$result = mysqli_query($connection, $query);
if ($result == false) {
echo "<p>Updating failed.</p>";
} else{
echo "<p>Updated</p>";
}
}
}
}
Try setting the name and id of your input fields to the same respective values. I see you call id from one and name from another input field in your php and it might be causing the function to fail.
Like so for example:
<label for="ID">ID</label>
<input id="ID" name="ID" type="text" readonly value="<?php echo $productDetails["ID"]; ?>">
you should be fine using $_POST[], since the method of your form is POST. (If you change it to GET it will put all the values in the url)

PHP show data from Oracle database in a listbox

I want to show data from a Oracle database into a listbox.
, but I don't no how to do that.
Now I'm using a textbox and that works good.
This is my HTML code
<form name="form1" method="get" action="Get_opdracht.php"
Opdrachtnummer: <br /> <input id="Password1" type="number" name="nummer1" required="required"/>
<input type="submit" name="submit1" value="Zoeken" />
<hr />
</form>
PHP code (get_opdracht.php)
// database connect
$conn = oci_connect('username', 'password', 'connect');
// variable textbox
$username = $_GET['nummer1'];
// SELECT query
$array = oci_parse($conn, "SELECT * FROM OPD_VW, MDW_VW WHERE OPD_OPDRACHTNUMMER = '$username'");
$query = oci_execute($array);
//show data on page
while (($row = oci_fetch_array($array, OCI_BOTH)) != false) {
echo "<h1>Opdrachtnummer: " . $row['OPD_OPDRACHTNUMMER'] . "</h1><p> <b>Status: </b>" . $row['OPD_STATUS'] . "<p><b>Registratiedatum: </b>" . $row['OPD_REGISTRATIEDATUM'] . "<p><b>Einddatum: </b>" . $row['OPD_EINDDATUM'] . "<p><b>BTW tarief: </b>". $row['OPD_BTW_TARIEF'] . "<p><b>Totale contractsom: โ‚ฌ</b>" . $row['OPD_TOTALE_CONTRACTSOM'] . "<p><b>Percentage gerealiseerd: </b>" . $row['OPD_PERCENTAGE_GEREALISEERD'] . "%";
oci_free_statement($array);
oci_close($conn);
To create a listbox you need to use the select multiple as shown below.
<select name="myselect" multiple="multiple">
<option value="value">OPTION</option>
<option value="value">OPTION</option>
</select>

Second Select Won't POST

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 ?

Categories