function to check if user text is valid - php

I am trying to make a function so that if the user clicks the Update button AND the text in the textbox is a valid text(only the text from the array should be valid ie. text1, text2, text3). Then, it echo's the number assosiated to the text in the array so if text1 is entered, it should echo 10. I made a function to do it but it says Invalid argument supplied for foreach() on the foreach loop line.
HTML:
<input type='text' id='usertext' name='usertext' size='15' />
<input type='submit' name='update' id='update' value='Update' />
PHP:
public currenttext = 0;
$config['text'] = array(
10 => 'text1',
25 => 'text2',
50 => 'text3'
);
public function set_text($validtext) {
foreach($this->config['text'] as $key => $value) { // <-- foreach loop
if($key == $validtext){
$this->currenttext = $value;
}
}
}
if ($_POST['update') {
$this->set_text($_POST['usertext'));
}

You may try this:
if ( isset($_POST['update']) ) {
$this->set_text( $_POST['usertext'] );
}
Also flip the array;
$config['text'] = array(
'text1' => 10,
'text2' => 25,
'text3' => 50
);
Finally change the set_text method to something like this:
// $validtext could be text1 or text2 or text3 from user
public function set_text($validtext) {
if(array_key_exists($validtext, $this->config['text'])) {
$this->currenttext = $this->config['text'][$validtext];
}
}
Integrate these in your class properly, it'll work. Also check array_key_exists on PHP manual.

Actually, you dont need a foreach loop, alternatively, you could also use array_search() to get the same goal. Consider this example:
<?php
if(isset($_POST['update'])) {
$usertext = $_POST['usertext'];
$config['text'] = array(10 => 'text1', 25 => 'text2', 50 => 'text3');
$key = array_search($usertext, $config['text']);
if($key !== false) {
echo $key;
} else {
// not found
{
exit;
}
?>
<form method="POST">
<input type='text' id='usertext' name='usertext' size='15' /><br/>
<input type='submit' name='update' id='update' value='Update' />
</form>

Related

PHP Multiple Input Text and Input File Array

I have the following code Multiple text and type File Using an array to upload file and Text.
in this code, if I remove type file this code is working. but after use file is not work
Here is the Form
<form method="post" enctype="multipart/form-data">
<?php
$data_array = array('text','text2','file','file2');
foreach($data_array as $data_name){ ?>
<input type="hidden" name="data_name[]" value="<?php echo $data_name; ?>">
<?php if(strpos($data_name,'text') !== false){ ?>
<input name="data_value[]" type="text" />
<?php }
if(strpos($data_name,'file') !== false){ ?>
<input name="data_value[]" type="file" /> <?php }
} ?>
<input type="submit" name="submit" value="Add" />
</form>
Here is The Php Code, I Think More Improvement on $_FILE Part
if(isset($_POST['submit'])){
if(isset($_FILES['data_name'])){
foreach(array_combine($_FILES['data_name'],$_POST['data_value']) as $dataname => $datavalue){
$file_name = $_FILES['data_name']['name'];
echo file_name;
}
}
if(isset($_POST['data_name'])){
foreach(array_combine($_POST['data_name'],$_POST['data_value']) as $dataname => $datavalue){
echo $dataname.' - '.$datavalue;
}
}
}
Here is The Error of File..
Warning: array_combine(): Both parameters should have an equal number
of elements in pagename.php on line 25
Warning: Invalid argument supplied for foreach() in pagename.php on line 25
I Need Output Like This -
text = value
text2 = value2
file = file.jpg
file2 = file2.jpg
As stated explicitly in the error message, $_FILES['data_name'] and $_POST['data_value' are not the same size. (And I'm pretty sure the foreach is failing because the array_combine failed).
That is explained by you here: "if I remove type file this code is working. but after use file is not work".
If you want to use array_combine(), the arrays must be of the same size.
If you add a filter (eg if(strpos($data_name,'file') !== false)) the potential exists that the arrays will not match (as this problem indicates).
One approach would be to filter out the "data_name[]" inputs with the same condition as the "data_value[]" inputs.
Or the other way round: add an else on the above mentioned if that produces <input name="data_value[]" type="hidden" /> (notice the type). This will ensure the arrays are the same size. You will have to figure out what to do with these "dummy" inputs in the php code. Perhaps give them a value (like value="dummy") that you can test on.
replace your php-code with this:
function get_names_for_entity($name, $arr)
{
if (!empty($arr)) {
$ret = array_values(
array_filter(
$arr,
function ($itm) use ($name) {
return strpos($itm, $name) !== false;
}
)
);
} else {
$ret = [];
}
return $ret;
}
$names_a = [
'file' => get_names_for_entity('file', $_POST['data_name']),
'text' => get_names_for_entity('text', $_POST['data_name'])
];
if (isset($_POST['submit'])) {
if (isset($_POST['data_value'])) {
foreach ($_POST['data_value'] as $dataname_idx => $datavalue) {
echo $names_a['text'][$dataname_idx].' - '.$datavalue;
}
}
if (isset($_FILES['data_value'])) {
foreach ($_FILES['data_value']['name'] as $dataname_idx => $datavalue) {
$file_name = $_FILES['data_value']['name'][$dataname_idx];
echo $names_a['file'][$dataname_idx].' - '.$file_name;
}
}
}

cookie value back into input fields

i'm actually new to PHP so i need your help!
I'm using a table within a form, and SQL Server to fill the table rows.
The form starts with an input field for quantity input type="number".
<form name="testform" method="post" action="submit.php">
<?php
$sql="query goes here";
$query=sqlsrv_query( $conn, $sql, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
if ($query) {
while($row = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC) ) {
echo "<td><input type='number' name='quantity[]'></td>";
}
}
?>
</form>
After submitting the form, i want the user to have the possibility to navigate back to the previous page to change the quantity input if possible.
So i need to restore the input values when navigating back (all values are now lost when navigating back).
I found this way by using the Cookies to store the input values so i found a way to store all values of input name='quantity[]' (array) in the cookies. And print them on the page when navigating back. It prints all values correct with the correct array index position as well.
Here's some of the code:
On my form page (form.php) for receiving cookies.
<?php
if (isset($_COOKIE['Cookie_Info'])){
$cookie = $_COOKIE["Cookie_Info"];
$cookie = stripslashes($cookie);
$savedAantArray = json_decode($cookie, true);
echo '<pre>';
print_r($savedAantArray); echo '</pre>';
} else {
$data = array(
'quantity[]' => ''
);
}
?>
On my submit page (submit.php) for setting cookies, with link to return to form.php page.
<?php
if (isset($_POST['submit'])) {
$post_arr = $_POST;
$expire = 8*3600;
setcookie("Cookie_Info", serialize($post_arr), time()+$expire);
}
?>
Make Some Changes..
Result when returning to form.php
Cookies
Array
(
[quantity] => Array
(
[0] => 8
[1] => 8
)
[submit] => Submit
)
Here's my question:
Is there a way to store those values from the array into all the right input fields?
Instead of printing them just as an array (which is not what i want, but i wanted to test the cookie storage).
Thanks in advance!
Thanks Yvon, got it working now.
Again on my second page:
<?php session_start();
$_SESSION['quantity'] = $_POST['quantity'];
foreach($_POST['quantity'] as $key => $value) {
echo "<input name='quantity' value='$value'>\n<br />";
}
?>
Back to first page:
<?php session_start();
$quantity=$_SESSION['quantity'];
print_r($quantity);
echo "<br \>";
foreach($_SESSION['quantity'] as $key => $value) {
echo "<input name='quantity[]' value='$value'>\n<br />";
}
?>
Just a small edit, got it working perfect now (including printing the correct amount of rows).
On the first page:
<form name="form" method="post" action="second.php">
<?php session_start();
include 'db_connect.php';
$quantity=$_SESSION['quantity']; print_r($quantity); echo "<br \>";
$sql ="SELECT * FROM X0ONTDTA.WEBRELGB";
$query = sqlsrv_query( $conn, $sql, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
if($query){
if (isset($_SESSION['quantity'])){
foreach($_SESSION['quantity'] as $key => $value) {
echo "<input name='quantity[]' value='$value'>\n<br />";
}
}
elseif($query){
while($row = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC) ) {
echo "<input name='quantity[]' value=''>\n<br />";
}
}
}
?>
<input type="submit" value="Submit" name="submit"></input>
</form>
On the second page:
<?php session_start();
$_SESSION['quantity'] = $_POST['quantity'];
foreach($_POST['quantity'] as $key => $value) {
echo "<input name='quantity' value='$value'>\n<br />";
}
echo "<pre>";
print_r($_POST['quantity']);
echo "</pre>";
?>
Go Back
Resulting in this:
after submit
going back

Return Single Value Multidimensional Array

I'm trying to build a custom zip code search to find a delivery fee, but I can't seem to get it right.
First up this is how I have my form set up on the front-end:
<form class="delivery-fee" role="search" method="get" action="">
<div class="form-group">
<label>Find Your Delivery Area:</label>
<input class="form-control" type="number" value="" name="zipcode" placeholder="Enter Zipcode" pattern="\d*" />
<input type="submit" value="See Delivery Minimum" />
</div>
</form>
I've got my data set up like this:
$delivery_areas = [
'Rancho Cucamonga' => [
'zipcodes' => [91701, 91729, 91730, 91737, 91739],
'fee' => 100
],
'Upland' => [
'zipcodes' => [91784, 91785, 91786],
'fee' => 150
]
];
This is how I'm looping through my data:
foreach ($delivery_areas as $key => $delivery_area) {
if (is_array($delivery_area)) {
if (in_array($_GET['zipcode'], $delivery_area['zipcodes'])) {
echo $delivery_area['fee'];
} else {
echo 'Error message';
}
}
}
The problem I'm having is if I do a search for say 91701 I do get the correct fee returned, but I'm also getting the error message with it. On the flip side I'll also get two error messages if nothing is found.
Any suggestions on how I could get the desired result?
You can adapt your code by using a var, e.g.:
$fee = -1;
foreach ($delivery_areas as $key => $delivery_area) {
if (is_array($delivery_area)) {
if (in_array($_GET['zipcode'], $delivery_area['zipcodes'])) {
$fee = $delivery_area['fee'];
break;
}
}
}
if($fee == -1)
echo 'Error message';
else
echo $fee;
Test:
$fee = 0;
foreach ($delivery_areas as $key => $delivery_area) {
if (is_array($delivery_area) && in_array($_GET['zipcode'], $delivery_area['zipcodes'])) {
$fee = $delivery_area['fee']; break;
}
}
echo $fee!=0 ? $fee : 'Error Message';

PHP - getting a single key from array, matching it with value, printing both

I have an array where the key is a filename and the value is the name of a fish. Right now, this loop prints out text for a randomly chosen fish, then it loops through the img directory and prints every image. How do I "link" it so that the image of the fish corrsponse with the name? Like, if it outputs Nice one! You caught a small-mouth bass! I would then want it to only output smbass.gif.
The php file is in the root, and the images folder is root/img/smbass.gif, e.g.
<p class="fishes">
<form action="fishing.php" method="post">
<?php
$fish = array('catfish.gif' => 'catfish', 'lmbass.gif' => 'large-mouth bass', 'smbass.gif' => 'small-mouth bass', 'shiner.gif' => 'shiner', 'perch.gif' => 'perch', 'pickerel.gif' => 'pickerel', 'minnow.gif' => 'minnow', 'sunfish.gif' => 'sunfish');
$rand = array_rand($fish);
//link file name (key) to value
echo "Nice one! You caught a " . $fish[$rand] . "!";
$files = scandir('img');
if ($files !== false) {
foreach($files as $f) {
if ($f == '..' || $f == '.' || substr($f, -strlen(".DS_Store")) === ".DS_Store") continue;
echo '<li class="fish_pic"><img src="img/'.$f.'" alt="'.$f.'" title="" class="fish"></li>'."\n";
}
}
?>
</p><!-- close class="fishes" -->
<p><input type="submit" class="btn btn-primary" value="Go Fishing!"></p>
</form>
Try something like this:
<form action="fishing.php" method="post">
<?php
$fish = array(
'catfish.gif' => 'catfish',
'lmbass.gif' => 'large-mouth bass',
'smbass.gif' => 'small-mouth bass',
'shiner.gif' => 'shiner',
'perch.gif' => 'perch',
'pickerel.gif' => 'pickerel',
'minnow.gif' => 'minnow',
'sunfish.gif' => 'sunfish'
);
$rand = array_rand($fish);
$sImageOut = "";
//check the image
// - yes, error supression is normally evil
// - and assigning variables in this way isn't exactly pretty
// ... but it works
if(list($iImgX, $iImgY, $iImgType, $sImgAttr) = #getimagesize(__DIR__ . '/img/' . $rand)) {
$sImageOut = "<div><img src=\"img/{$rand}\" alt=\"{$fish[$rand]}\" style=\"width: {$iImgX}px; height: {$iImgY}px; border: 1px solid #cccccc;\" /></div>\n";
}
//output
echo "<p>Nice one! You caught a {$fish[$rand]}!</p>\n{$sImageOut}";
?>
<p><input type="submit" class="btn btn-primary" value="Go Fishing!"></p>
</form>
Since the image name is the key and array_rand() returns the key ... $rand contains the image filename.
I'm using getimagesize() in there so that if, for some reason your image doesn't exist, it won't create "duff" output - not the tidiest code but it works as an example.

Input custom attribute value : retrieve and loop in PHP

When I click on buttons I generate some inputs field with custom attributes like that :
<input type='text' name='field["+ i++ +"]' value='' data-kind='title' />
<input type='text' name='field["+ i++ +"]' value='' data-kind='video' />
<input type='text' name='field["+ i++ +"]' value='' data-kind='text' />
I retrieve the 'name' value with a foreach loop in PHP :
$result = array_combine($num, $records);
foreach ($result as $rank => $content)
{
$data = array(
'content' => $content,
'post_id' => $post_id,
'rank' => $rank,
'type' => $this->input->post('field_type') // HERE
);
echo '<pre>';print_r($data);echo '</pre>';
}
To get the 'type' I do a $this->input->post('field_type'); which is given by this :
var field_type = $(":input[data-kind]").attr('data-kind');
$("#field_type").val(field_type' ');
and :
echo '<input type="hidden" id="field_type" name="field_type" value="" />';
But it only returns me the last 'data-kind' value not each one :/
Now i just need to loop the 'data-kind' value for each input fields and retrieve them in my foreach loop
Any help would be very very appreciated !!
Many thanks for your answers, it helped me a lot! But now how can I add the result in my current foreach at 'type' data :
$result = array_combine($num, $records);
foreach ($result as $rank => $content)
{
$data = array(
'content' => $content,
'post_id' => $post_id,
'rank' => $rank,
'type' => // HERE I NEED EACH ATTRIBUTE VALUE
);
echo '<pre>';print_r($data);echo '</pre>';
}
If you want to place all of the data-kind values in the #field_type field, you need something like this:
var fieldTypes = [];
$("input[data-kind]").each(function()
{
fieldTypes.push( $(this).attr('data-kind') );
});
$("#field_type").val(fieldTypes.join(','));
Maybe you've missed the plus sign?
$("#field_type").val(field_type' ');
should be $("#field_type").val(field_type+' ');
This code:
http://jsfiddle.net/PKgkU/17/
Does what you want!
$('input').each(function(el) {
switch ($(this).data('kind')) {
case "video":
kind = 'video';
break;
case "image":
kind = 'image';
break;
case "title":
kind = 'title';
break;
default:
break;
}
$(this).after('<input type="hidden" id="field_type" name="field_type" value="' + kind + '" />');
});

Categories