cannot insert the desired data to wpdb - php

the inserted data always result to Upland even though I selected either the tab-pane Irrigated or Rainfed, result is still the same using echo. Sorry for posting a common problem. I am new in array insertion to database.
$types = array(
'irrigated' => 'Irrigated',
'rainfed' => 'Rainfed',
'upland' => 'Upland'
);
$seed_types = array(
'hybrid_' => 'Hybrid',
'taggedSeeds_' => 'Tagged Seeds from (RS/FS/CS)',
'goodSeedsTagged_' => 'Good Seeds from Tagged FS/RS',
'goodSeedsStarter_'=>'Good Seeds from Starter RS/CS',
'goodSeedsTraditional_'=>'Good Seeds of Traditional',
'farmSaved_'=>'Farm Saved Seeds'
);
foreach($types as $type){
echo '<div id="'.$type.'" class="tab-pane fade tab-title">';
echo "<br/>".$type."<hr/>";
echo "<input type='hidden' name='ecosystem' value='".$type."'>";
foreach($seed_types as $seed_name => $seed_type){
echo '<div class="row form-group">';
echo '<div class="col-md-4 table-body">'.$seed_type.'</div>';
for ($x = 0; $x <= 3; $x++) {
echo '<div class="col-md-2"><input type="number" class="form-control" name="'.$seed_name.''.$x.'" /></div>';
}
echo "</div>";
}
echo '</div>';
}echo '<div class="row" style="border-top:dashed 1px #eaeaea;padding-top:15px;">
<div class="col-md-11" style="text-transform:initial;">Note: Kindly check all the data before saving. Thank You.</div>
<div class="col-md-1">
<input type="submit" name="save-report" value="Save Data!" class="btn btn-success">
</div>
</div>';
echo '</div>';
<?php
if (isset($_POST['save-report'])) {
// Process
global $wpdb;
$ecosystem = $_POST['ecosystem'];
$result = $wpdb->insert('wp_sample', array (
'eco_system' => "$ecosystem",
'type' => "$seed_type",
));
}

Try like this.
$types = array(
'irrigated' => 'Irrigated',
'rainfed' => 'Rainfed',
'upland' => 'Upland'
);
$seed_types = array(
'hybrid_' => 'Hybrid',
'taggedSeeds_' => 'Tagged Seeds from (RS/FS/CS)',
'goodSeedsTagged_' => 'Good Seeds from Tagged FS/RS',
'goodSeedsStarter_'=>'Good Seeds from Starter RS/CS',
'goodSeedsTraditional_'=>'Good Seeds of Traditional',
'farmSaved_'=>'Farm Saved Seeds'
);
foreach($types as $type){
echo '<div id="'.$type.'" class="tab-pane fade tab-title">';
echo "<br/>".$type."<hr/>";
echo "<input type='hidden' name='ecosystem[]' value='".$type."'>";
foreach($seed_types as $seed_name => $seed_type){
echo '<div class="row form-group">';
echo '<div class="col-md-4 table-body">'.$seed_type.'</div>';
for ($x = 0; $x <= 3; $x++) {
echo '<div class="col-md-2"><input type="number" class="form-control" name=[number]["'.$seed_name.''.$x.']" /></div>';
}
echo "</div>";
}
echo '</div>';
}echo '<div class="row" style="border-top:dashed 1px #eaeaea;padding-top:15px;">
<div class="col-md-11" style="text-transform:initial;">Note: Kindly check all the data before saving. Thank You.</div>
<div class="col-md-1">
<input type="submit" name="save-report" value="Save Data!" class="btn btn-success">
</div>
</div>';
echo '</div>';
<?php
if (isset($_POST['save-report'])) {
// Process
global $wpdb;
foreach($_POST['ecosystem'] as $key => $value){
$ecosystem = $value;
$result = $wpdb->insert('wp_sample', array (
'eco_system' => $ecosystem,
'type' => $seed_type,
));
}
}

Related

My PHP form isn't returning anything from $_POST

I have a relatively simple PHP form. When I'm using print_r($_POST); I'm not receiving anything back. Just this result:
`Array
(
)
1`
My form is pretty simple:
<form action="" method="post" enctype="multipart/form-data" class="zip-<?php echo $atts['class']; ?>">
<div class="row ">
<div class="<?php echo $column1; ?>" <?php echo $inlineStyle ?>>
<div class="lds-facebook hide"><div></div><div></div><div></div><div></div><div></div></div>
<input type="text" name="zip" class="zip">
</div>
<div class="<?php echo $column2 ?>">
<button type="submit" class="submit" name="submit">
<?php echo $buttonValue; ?>
<i class='fa fa-caret-right' aria-hidden='true'></i>
</button>
</div>
</div>
</form>
The goal of the form is to simply post and then redirect to a page depending on the value received from the input. Any thoughts?
public static function find_zip_widget( $atts, $content = null ) {
ini_set('display_errors', '1');
extract(shortcode_atts(array(
'class' => 'class'
), $atts));
// Set classes for rows
if($atts['class'] == 'home'){
$column1 = 'col-md-6 col-12 my-auto text-center border-underline';
$column2 = 'col-md-6 col-12';
$buttonValue = 'FIND HELP RIGHT NOW';
$inlineStyle = '';
}
if($atts['class'] == 'widget'){
$column1 = 'col-md-5 col-5 offset-2 offset-md-0 my-auto';
$column2 = 'col-md-7 col-5 my-auto';
$buttonValue = 'SUBMIT';
$inlineStyle = 'style="border-bottom: 3px solid #9EA2A4 !important;min-height: 30px;"';
}
?>
<form action="" method="post" enctype="multipart/form-data" class="zip-<?php echo $atts['class']; ?>">
<div class="row ">
<div class="<?php echo $column1; ?>" <?php echo $inlineStyle ?>>
<div class="lds-facebook hide"><div></div><div></div><div></div><div></div><div></div></div>
<input type="text" name="zip" class="zip">
</div>
<div class="<?php echo $column2 ?>">
<button type="submit" class="submit" name="submit">
<?php echo $buttonValue; ?>
<i class='fa fa-caret-right' aria-hidden='true'></i>
</button>
</div>
</div>
</form>
<?php
echo "<pre>";
echo "Before if: ";
echo print_r($_POST);
echo "</pre>";
?>
<?php
$states = get_categories( array(
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
'taxonomy' => 'endeavors_location_state'
) );
if (isset($_POST['submit'])) {
$postalZip = $_POST["zip"];
echo "<pre>";
echo "After if: ";
echo print_r($_POST);
echo "</pre>";
echo '<br> <br> PostalZip: ' . $postalZip;
///REDIRECT FOR CITY, STATE, or other/////
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://maps.googleapis.com/maps/api/geocode/json?address='.$postalZip.'&key=AIzaSyBX_0qZmGBtiHrZMcjZfv6yL7NAbLiwnjc");
// curl_setopt($ch, CURLOPT_URL, "https://maps.googleapis.com/maps/api/geocode/json?address=78210&key=AIzaSyBX_0qZmGBtiHrZMcjZfv6yL7NAbLiwnjc");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
$jsonResults = json_decode($output, true);
$cityName = $jsonResults['results'][0]['address_components'][1]['long_name'];
$stateName = $jsonResults['results'][0]['address_components'][3]['long_name'];
$cityName = strtolower(str_replace(" ","-",$cityName));
$stateName = strtolower(str_replace(" ","-",$stateName));
$args = array(
'post_type' => 'endeavors_locations',
'post_status' => 'publish',
'numberposts' => -1
);
$cityFound = 0;
$allCityLocations = get_posts( $args );
foreach ($allCityLocations as $location) {
$eachCity = strtolower(str_replace(" ","-",$location->post_name));
echo $eachCity;
if ($location->post_name === $cityName) {
$cityFound = 1;
echo $cityFound;
}
}
if ($cityFound === 1) {
wp_safe_redirect('/locations/'.$cityName);
} else {
foreach ($states as $state) {
if ($state->slug === $stateName) {
$stateFound = 1;
}
}
if ($stateFound === 1) {
wp_safe_redirect('/state/'.$stateName);
} else {
wp_safe_redirect('/all-locations/');
}
}
}
///END OF REDIRECT FOR CITY, STATE, or other/////
} //end function
Your script post to the server just fine, but before hitting the print_r($_POST) it gets redirect to the same location. so print_r($_POST) was not executed . Please refer below image for additional info. There are two requests , one is post with 302 redirect. I suspect there maybe a javascript redirect involved.
I just ran your script,(xampp , php 7.1.26 , mac Mojave) and it prints
Array ( [zip] => testvalue [submit] => )
I added <?php print_r($_POST); ?> on top of the tag.( you might have done the same) and for me it worked as expected.
silly but did just wanted to know whether you submitted the form? if not it will show an empty array

Undefined index: imagedescription[n] (array problem)

I'm trying to get the value of an array but I can't.
I've got this page to upload a variable number of photos and their relative descriptions (to be stored in a DB)
for ($i=1; $i<$val; $i++)
{
echo '<div class="row">';
echo '<div class="col-xl-4 col-lg-4 col-md-6 mt-2">';
echo '<div class="file-field" style="margin-bottom: 10px;">';
echo '<div class="z-depth-1-half mt-3" id="thumb-output'.$i.'"></div>';
echo '<div class="d-flex justify-content-center">';
echo '<div class="custom-file">';
echo '<input type="file" data-index="'.$i.'" name="imageupload[]" class="custom-file-input" aria-describedby="inputGroupFileAddon'.$i.'">';
echo '<label class="custom-file-label" for="inputGroupFile'.$i.'">IMG '.$i.'</label>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '<div class="col-xl-8 col-lg-8 col-md-6 mt-4">';
echo '<label for="imagedescription'.$i.'">Description IMG '.$i.'</label>';
echo '<input type="text" name="imagedescription[]" class="form-control mt-2" id="imagedescription'.$i.'" aria-describedby="ImageDescription'.$i.'" style="margin-bottom: 0px;">';
echo '<input type="hidden" name="imgcount" value="'.$i.'">';
echo '</div>';
echo '</div>';
}
and this page that "take" and process the datas.
for($i = 0; $i < $count_tmp_name_array; $i++){
$extension = pathinfo($name_array[$i] , PATHINFO_EXTENSION);
$j=$i+1;
$imgname = $albumtitle."-".$j.".".$extension;
if(move_uploaded_file($tmp_name_array[$i], $target_dir.$imgname)){
$photo_decription = $_POST['imagedescription['.$i.']'];
print_r ($photo_decription);
echo "</br>";
}
Basically what I need to do is to assign the varous values of the array imagedescription[] to the relative image (to be upoaded to the DB).
Something like:
[...]
imagedescription[1] -> imageupload[1];
imagedescription[2] -> imageupload[2];
imagedescription[3] -> imageupload[3];
[etc]
The rest is working good but when I try to print the value of $photo_decription or $_POST['imagedescription['.$i.']'] (either with echo or print_r, it doesn't make difference) I recieve the error "Undefined Index for imagedescription[1]", "Undefined Index for imagedescription[2]", "Undefined Index for imagedescription[3]", etc.

How do I send this dynamic form in PHP?

I have a Wordpress loop and I have built a dynamic form from it, how would I now grab all the form data and send it?
$items = array();
$queryBasket = "SELECT * FROM baskets";
$gotBasket = $connect->query($queryBasket);
while ($basket = $gotBasket->fetch_assoc()) {
//echo $basket['item'];
$items[] = $basket['item'];
}
$args = array(
'post_type' => array('product' ),
'order' => 'ASC',
'orderby' => 'title',
'post__in' => $items
);
$loop = new WP_Query($args);
$i = 0;
if ( $loop->have_posts() ) {
echo '<ul id="basket" class="row">';
while ( $loop->have_posts() ) {
$loop->the_post();
$i++;
?>
<li class="col-sm-12">
x
<?php the_title(); ?>
Quantity: <input type="number" name="item-<?php echo $i; ?>-count" id="item-<?php echo $i; ?>-count" class="item-count"/>
<input type="hidden" name="item-<?php echo $i; ?>-name" id="item-<?php echo $i; ?>-name" value="<?php the_title(); ?>">
<?php }
echo '</ul>';
} else {
}
wp_reset_postdata();
?>
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
make it an array:
name="item[<?php echo $i; ?>][name]"
you can then iterate over it
foreach ($_POST['item'] as $i => $values) {
echo "Name for $i: " . $values['name'];.
}

Updating database based on checkbox Codeigniter

I'm trying to update a database column using a checkbox. The idea is that I want to only display certain things on the homepage, so the checkbox should send either 0 or 1 to the DB. If the record has 0 in the first page column, it shouldn't appear on the homepage, if it has 1 it should appear.
I tried setting something up, but it doesn't work as intended (it just refreshes the page with no effect)
The checkbox:
<?php echo form_checkbox(array('name' => 'first_page', 'class'=>'checkbox-inline', 'value' => 1)); ?>
Controller:
if(null != ($this->input->post('first_page'))) {
$first_page = 1;
$book_id= $this->input->post('id'); (the id is sent to the controller via an extra hidden input field)
$this->book_model->first_page($first_page, $book_id);
}
Model:
$this->db->set ( "first_page", $first_page);
$this->db->where ( "book_id", $book_id);
$this->db->update ( "books" );
return;
Full form:
<?php echo form_open('admin/modifica_autor'); ?>
<?php echo form_hidden('id', $item->id_carte); ?>
<?php echo form_hidden('id_autor', $item->id_autor)?>
<label for="titlu_nou">Titlu:</label>
<?php echo form_input(array('name' => 'titlu_nou_carte', 'class'=>'form-control', 'value' => $item->titlu)); ?> <br>
<label for="autor_nou">Autor:</label>
<select name='autor_nous' class="form-control"><?php
foreach ( $autori2 as $row ) {
echo '<option value="' . $row->id_autor . '">' . $row->nume_autor . '</option>'; }
?></select><br>
<label for="domeniu_nou">Domeniu:</label>
<select name='domeniu_nou' class="form-control"><?php
foreach ( $domenii as $row ) {
echo '<option value="' . $row->id_domeniu . '">' . $row->nume_domeniu . '</option>';
}
?></select><br>
<label for="pret_nou">Pret:</label>
<?php echo form_input(array('name' => 'pret_nou', 'class'=>'form-control', 'value' => $item->pret.' LEI')); ?><br>
<label for="descriere_noua">Descriere:</label>
<?php echo form_textarea(array('name' => 'descriere_noua', 'class'=>'form-control textarea', 'value' => $item->descriere)); ?><br>
<label for="prima_pagina">Afisare pe prima pagina:</label>
<?php echo form_checkbox(array('name' => 'prima_pagina', 'class'=>'checkbox-inline', 'value' => 1)); ?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<?php echo form_submit(array('name'=>'submit_autor','value' => 'Modifica', 'class'=>'btn btn-default')); ?>
<?php echo form_close(); ?>

Creating row using php loop

I want to create a row if columns greater than 3 using PHP loop because i am using wordpress
My code is here
<div class="row">
<div class="column">column1</div>
<div class="column">column2</div>
<div class="column">column3</div>
</div>
If columns are greater than 3, then it should create a new row like this
<div class="row">
<div class="column">column1</div>
<div class="column">column2</div>
<div class="column">column3</div>
</div>
<div class="row">
<div class="column">column1</div>
</div>
Any help will be highly appreciated.
Thanks in advance
Sure - just use modulus:
<?php
$elements = array('foo', 'bar', 'rab', 'oof');
echo '<div class="row">';
foreach ($elements as $i => $element) {
if ($i > 0 && $i % 3 == 0) {
echo '</div><div class="row">';
}
echo '<div class="column">' . $element . '</div>';
}
echo '</div>';
?>
DEMO
Output:
<div class="row">
<div class="column">foo</div>
<div class="column">bar</div>
<div class="column">rab</div>
</div>
<div class="row">
<div class="column">oof</div>
</div>
You need something like this:
<?
echo '<div class="row">';
for ($i=0; $i<15;$i++){
if ($i%3 == 0 && $i != 0){
echo '</div><div class="row">';
}
echo '<div class="column">column '.($i+1).'</div>';
}
echo '</div>';
?>
WORKING CODE
There is alternative solution with function.
<?php
// Managing the Code -- Functions: Handling a Variable Number of Parameters
// building a row of 10 <td> columns with a variable number of items
function preferencesRow()
{
// initialize $output
$output = '';
// use "func_get_args()" to collect all parameters into an array
$params = func_get_args();
// used to make sure 10 columns are filled
$maxCols = 10;
// loop through the parameters
foreach ($params as $item) {
$output .= "<td width='80px' align='center'>$item</td>\n";
$maxCols--;
}
// fill in the rest of the row with empty columns
for ($x = 0; $x < $maxCols; $x++) {
$output .= "<td width='80px'> </td>\n";
}
return $output;
}
// NOTE: you can use "." or "," with echo
echo '<h1>Preferences</h1><hr />' . PHP_EOL;
echo '<table border=1>' . PHP_EOL;
echo '<tr><th>Tarzan</th>';
echo preferencesRow('Africa', 'jungles', 'tantor', 'mangani', 'cabin in the woods',
'hunting', 'swinging in trees', 'Jane');
echo '</tr>';
echo '<tr><th>Jane</th>';
echo preferencesRow('London', 'parties', 'dancing', 'social events', 'lavish estates');
echo '</tr>';
echo '</table>' . PHP_EOL;

Categories