I can't get checkboxes values - php

I got this and I have no idea what I'm missing here:
<?php
//Some validation for the SUBMIT form
if(isset($_POST['submit'])&&$_POST['submit']=='add'){
$_POST = array_map("mysql_real_escape_string", $_POST); //This little fella is responsible for the mess ¬¬
$campus_string = $_POST['campus']; //To get a checkboxes Array
....
print_r($campus_string); //to see if I am getting the checkboxes when submitting
}
?>
....
//Now inside <body> of the HTML
<form action="" method="post" name="filosofal">
//A little loop to create the checkboxes from a DB
foreach($campi as $keyCampi => $valueCampi){
echo '<tr>
<td>
<input type="checkbox" id="campus[]" name="campus[]" value="'.$value['Id'].','.$valueCampi['Id'].'" />'.$valueCampi['Nombre'].'<br />
</td>
</tr>';
}
</form>
But print_r doesn't show anything, the array is not being stored when submitting via POST. Hope you can help me to pinpoint where I'm screwing it.
EDIT: Solved
Well, I finally figured it out, it's kind of embarrasing.
In my code, I use:
$_POST = array_map("mysql_real_escape_string", $_POST);
to avoid some encoding conflicts (like names with 's on them), security and such.
I commented the line and it works now (didn't add that part since I wasn't aware its relevance on the issue), no changes needed to be done.
Don't know why it took me five days to find that little thing over there, but now is done. Anyways, thanks everyone.

Try adding
<input type="hidden" name="submit" value="add" />
Into your form, at the moment your if statement will be returning false...

Try dumping the post data:
echo "<pre>";
print_r($_POST);
//if you check the radio then it will be listed in your $_POST dump
//add action to your form
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
foreach($campi as $keyCampi => $valueCampi){
?>
<tr>
<td>
<input type="checkbox" id="campus[]" name="campus[]" value="<?php echo $valueCampi['Id'].','.$valueCampi['Id']; ?>" /><?php echo $valueCampi['Nombre'].'<br />
</td>
</tr>';
<? php } ?>
</form>

Generally speaking, the way I see it is that checkbox is either ON or OFF. Therefore, in my mind, the name of the checkbox is the value. For instance:
<input type="checkbox" name="single"> Single?
If that checkbox is checked (value="on"), then the answer is yes. If it is not checked (value="off" or no value), then the answer is no. Therefore, my PHP code looks something like:
if ($_POST['single'] == 'on')
$single = true;
else
$single = false;
Basically, as far as I'm concerned, the "value" of a checkbox should never be set. That's my particular preference though, and it's worked well for me. It may not suit your needs, though.
Good luck.

Related

PHP send array to another PHP file

This may be a stupid question but I'm lost here. I need to send array with some data in it to another PHP file using POST variable. This is my form:
<form action="test.php" method="post">
<label name="html[]" hidden><?php echo $array; ?></label>
<input type="submit" value="submit">
</form>
And this is test.php
<?php
$html = $_POST['html'];
for($i = 1; $i<=9; $i++){
echo $html[$i];
}
?>
So this is what I tried, but it's not displaying anything. please help
You need to create a number of input elements with the same name, each of which will have one array item as its value:
<?php foreach ($array as $item) : ?>
<input type="hidden" name="html[]" value="<?= htmlspecialchars($item); ?>" />
<?php endforeach; ?>
Important points to keep in mind:
$item must always be a scalar value (string, integer, etc). You cannot pass in arrays piecemeal with this technique.
Never forget that since you are injecting variables into HTML output you must escape and/or sanitize them properly. In this case this is done with htmlspecialchars, which must know about your output encoding to work correctly in general (look up its third parameter).
There is also an alternative approach that can be used to pass arrays piecemeal through serialization:
<input type="hidden" name="html"
value="<?= htmlspecialchars(serialize($array)); ?>" />
And you would then unserialize it on the receiving end:
$html = unserialize($_POST['html']);
I 'm mostly including this option for completeness, as in practice session variables are a much better way of passing complex state between requests.
Is it necessary to put the data of the array in a hidden field? You can store the array in $_SESSION and access it. Btw, I think you have a problem, labels can be submitted, in that case you must put the data into an input field with type="hidden".

HTML form acting as get instead of post

I'm pretty new to the whole PHP/HTML deal, and I've run into a problem that I don't know how to fix. It's a pretty simple form that lets you enter data into database. The PHP code is as following:
<?
include("../sqlcontext.php");
$foo = mysql_query("SELECT*FROM users WHERE checksum='".$_COOKIE['userCookie']."'");
if($_COOKIE['userCookie'] == '' || !mysql_num_rows($foo)){
echo 'Du er ikke logget ind :( log ind her';
}
else{
if($_POST['genreKnap']){
$nameGenre = $_POST['nameGenre'];
$textGenre = $_POST['textGenre'];
$succes = mysql_query("INSERT INTO genre VALUES('null','$nameGenre','$textGenre')");
if($succes){
echo 'Yay!';
}else {
echo 'Oh no';
}
}
?>
The form is as following:
<form name="form1" method="post" enctype="text/plain" action="">
<table>
<tr>
<td>Genre navn:</td>
<td><input type="text" name="nameGenre" id="nameGenre" style="width:100%; padding-right: 1px" /></td>
</tr>
<tr>
<td>Genre beskrivelse:</td>
<td><textarea name="textGenre" id="textGenre" style="width:100%; padding-right: 1px"></textarea></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="genreKnap" id="genreKnap" value="Go!"/></td>
</tr>
</table>
</form>
Whenever I press the submit button, it seems as though it acts as if it was a get method and not a post.
Aha!!!
You are not posting the form correctly.
Set the
action=""
to
action="code.php"
Assuming your php page is called code.php. Just change it to the name/path of the php page and the form will send the data to your php code to process.
When you leave action="" to blank, it posts the data to itself (the same page). It is not acting as GET, it is still acting as POST, but posting to the wrong place. I think you worded the title of the question wrong.
What do you mean it is acting like get instead of post.
Can you not read $_POST variables in your PHP?
remove the 'enctype="text/plain"' in your form code.
enctype="text/plain"
Take that out. It is provided for debugging purposes only and doesn't generate anything that is sane to parse with a machine.
Valid form enctypes:
application/x-www-form-urlencoded: This is the default content type
multipart/form-data
The content type "application/x-www-form-urlencoded" is inefficient
for sending large quantities of binary data or text containing
non-ASCII characters. The content type "multipart/form-data" should be
used for submitting forms that contain files, non-ASCII data, and
binary data.
Source: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.3.4
You're all ignoring the primary question and focusing on irrelevent items.
First of all more than anything he's using a short php opener <? not <?php now not every web server accepts short openers first up check that.
Echo out your $_POST vars and see if they're returning the correct items
echo "POSTS BELOW<br />";
echo $_POST['nameGenre']."<br />";
echo $_POST['textGenre']."<br />";
echo "<br />GETS BELOW<br />";
echo $_GET['nameGenre']."<br />";
echo $_GET['textGenre']."<br />";
Put this block of code directly below your php opener see what data it returns.
Also this if($_POST['genreKnap']){ is generally a bad way of doing it as its user input the safest way is a hidden field <input type="hidden" name="action" id="action" value="dopost" /> and change your if clause to if($_POST['action']=="dopost && isset($_POST['action'])){
Also set your form action="" to the actual page name not blank
Give all that a try and if its still not working we'll try something different
If you are send normal data without any files by the form .
Then enctype is not always needed .
But even if you want to include it
The correct way is :
enctype="multipart/form-data"
Also give a url in the action method of the form : <form action='example.php'>
I hope it solves the problem .

kohana parse $_POST data

i have a kohana application, and i have a form with several checkboxes, and the user is supposed to check his preferences there in the form. so i have a relation 1:n between the user table and the preferences table. my problem is that i want to save those preferences, selected in the form, and i don;t know how.
i have the form:
<form id="address" method="POST" action="<?= Route::url('Save user preferences' , array('user_id' => $user));?>">
<? foreach ($prefered_products as $pp): ?>
<input type="checkbox" name="user_preferences_preference[]" value="<?= $pp ?>" /><?= $pp->product; ?><br />
<? endforeach; ?>
<button type="submit">Salveaza preferintele tale</button>
</form>
and i save the data:
foreach ($_POST['user_preferences_preference'] as $up) {
$user_preferences->prefered = $up;
$user_preferences->user = $this->user;
$user_preferences->save();
}
$this->view->message = __('Thank you for your feedback!');
but seems like the way i parse the preferences is not correct, i am getting: ErrorException [ Warning ]: Invalid argument supplied for foreach()
any idea about how am i supposed to get the multiple $_post preferences?
thank you!
I have a slightly different way of doing this.
When I create a checkbox I also create an identical hidden field set to zero
<input type="hidden" name="my_check" value="0" />
<input type="checkbox" name="my_check" value="$value" />
The checkbox, if ticked, will override the hidden value. This way when you send the form you end up with $_POST['checkbox]=1 or 0, but it always exists in the $_POST.
The nice thing about this method is you can extend the Form::checkbox helper so that it's always present and you don't have to worry about it for every form / controller.
p.s. in you above example you would probably want to do it like this:
<input type="hidden" name="user_preferences_preference[$pp->id]" value="0" />
<input type="checkbox" name="user_preferences_preference[$pp->id]" value="<?= $pp ?>" />
<?= $pp->product; ?><br />
Or use a $key value instead of $pp->id.
The problem is that a checkbox will only post data when set. You should reverse check the values. Ie;
Fetch all preference (id's) from the database
Check if a value is found in the $_POST var
If not, update to false (or 0 or whatever) in db, if set, read out the value.

Basic problem of getting values of my textbox

I am just trying to learn PHP and want to get the value of the textbox using $_post function, but its not working. I am using wamp 2.1 and the code is simple as below
<form method="POST" action="c:/wamp/www/test/try.php">
<input type="text" name="nco" size="1" maxlength="1" tabindex="1" value="2">
<input
tabindex="2" name="submitnoofcompanies" value="GO"
type="submit">
</form>
<?php
if (!isset($_POST['nco']))
{
$_POST['nco'] = "undefine";
}
$no=$_POST['nco'];
print($no);
However in no way I get the value of the textbox printed, it just prints undefined, please help me out.
You first assigned the word "undefine" to the variable $_POST['nco'].
You then assigned the value of the variable $_POST['nco'] (still "undefine" as you stored there) to the variable $no.
You then printed the value stored in the variable $no.
It should be clear that this will always print the word "undefine".
If you want to print the value of the textbox with the name nco, fill out the form with that textbox, and in the page that process the form,
echo $_POST['nco'];
...is all you do.
You need to setup a form or something similar in order to set the $_POST variables. See this short tutorial to see how it works. If you click the submit button, your $_POST variables will be set.
what for you are using this line $_POST['nco'] = "undefine"; } ..?
and please cross check whether you are using form method as post and make sure that your text name is nco ... or else use the below code it will work.
<?php
$no = $_POST['nco'];
echo $no;
?>
<form name='na' method='post' action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type='text' name='nco'>
</form>
thanks
Your action is wrong.
Change it to
action="try.php"

Deleting a database record using $_POST with Codeigniter

I've been doing it all wrong, I used to take the value from the URI segment and didn't realize it wasn't the ideal way. So I changed my approach and now have everything via a $_POST. I'm not sure if I'm doing this correctly, could someone shed some light? My view contains tabular data listing items pulled from the DB. Each item has two links, "View" and "Delete." The code seems to work but was wondering if it could be coded better. I forgot that the form name wasn't unique, so when I went to go delete a record, it would always delete the newest record (the last hidden field was set).
myview.php (snippet)
<?php foreach($records as $record): ?>
<form method="POST" name="myform<?php echo $location->id;?>" action="/location/delete">
View Delete
<br />
<input type="hidden" name="location_id" value="<?php echo $location->id;?>">
</form>
<?php endforeach ?>
Viewing/Deleting via uri id is perfectly fine, I wouldn't venture to say that using $_POST is wrong, but creating a new unique form for every delete element is terribly messy, and weighed against what you are gaining (no exposed id i guess?), I believe it is more 'correct' to use the uri for delete functions.
If you only want certain people to be able to delete certain records, handle that programmatically in the delete function itself, don't depend on the fact that the request is only sent via $_POST. This is not dependable, anyone can generate a post request.
For anyone who comes across this later, here's how I solved my issue.
In my controller I have a method called delete that checks to see if the form field was submitted via a $_POST. If there's no variable, redirect them somewhere with an error message. If the field was passed, then go through the normal checks to make sure the record can be deleted.
if(!isset($_POST['item_id']))
{
$this->session->set_flashdata('message', 'item cannot be removed!');
redirect("/item");
}
if($this->input->post('item_id')) {
... code ....
... code ....
}
Your syntax error is with this line:
<?php foreach($records as $record): ?>
<form method="POST" name="myform<?php echo $location->id;?>" action="/location/delete">
View <a href="#" onclick="document.myform<?php echo
$location->id;?>.submit();">Delete</a>
<br />
<input type="hidden" name="location_id" value="<?php echo $location->id;?>">
</form>
<?php endforeach ?>
You can not do looping for a form. Instead, use the following code:
<form method="POST" name="myform<?php echo $location->id;?>" action="/location/delete">
<?php foreach($records as $record): ?>
a href="/location/view/<?php echo $location->id;?>">View</a> Delete
<br />
<input type="hidden" name="location_id" value="<?php echo $location->id;?>">
<?php endforeach ?>
</form>

Categories