I am using Zend framework. In this i create a model and put my database connection in this model.
Here is my code so far :-
public function getTagusers(){
try {
$stat = $this->db->query("select a.tagCode child, b.tagCode parent " .
"from tag a, tag b where a.tagParentId=b.tagId");
$aResultData = $stat->fetchall();
}
catch(Exception $e){
error_log('Exception in '.__FUNCTION__.' : line '.__LINE__.' : '
. $e->getMessage());
}
return $aResultData;
}
Now I am using action in controller. My code is so far :-
public function listAction()
{
$tagusers =new Admin_Model_DbTable_Tagusers();
$this->view->taguser =$tagusers->fetchall();
}
Now finally i want to echo my data in view list.html. My code is so far :-
<script>
<!-- Begin
function Check(chk)
{
if(document.myform.Check_ctr.checked==true){
for (i = 0; i < chk.length; i++)
chk[i].checked = true ;
} else {
for (i = 0; i < chk.length; i++)
chk[i].checked = false ;
}
}
// End -->
</script>
<?php foreach($this->taguser as $taguser) ?>
<form name="myform" action="checkboxes.asp" method="post">
<b>Select Allowed keywords below:</b><br>
<input type="checkbox" name="Check_ctr" value="yes"
onClick="Check(document.myform.check_list)"><b>Select all keywords</b>
<br>
<input type="checkbox" name="check_list" value="1">
<?php echo $this->escape($taguser->tagCode);?><br>
<input type="checkbox" name="check_list" value="2">
<?php echo $this->escape($taguser->tagParentId);?><br>
</form>
But I am not able to echo the data properly. Can anyone explain me what I can do to echo the result according to my query.
first if you using Zend Framework as a framework as it appears... your first error is it normal for viewscripts to have the .phtml extension (i know you may have changed this).
next your php is incorrect:
<?php foreach($this->taguser as $taguser): //need to colon for alternate loop syntax ?>
<form name="myform" action="checkboxes.asp" method="post">
<b>Select Allowed keywords below:</b><br>
<input type="checkbox" name="Check_ctr" value="yes"
onClick="Check(document.myform.check_list)"><b>Select all keywords</b>
<br>
<input type="checkbox" name="check_list" value="1">
<?php echo $this->escape($taguser->tagCode);
//if this causes errors use
//array notation $taguser['tagCode']?><br>
<input type="checkbox" name="check_list" value="2">
<?php echo $this->escape($taguser->tagParentId);?><br>
</form>
<?php endforeach //need to end the foreach statement alternate syntax?>
I'm not going to critique your form, if you want built a separate form for each record that's your business.
Well, you're printing N forms (where N = count($this->taguser)), each one containing 3 checkboxes with the same value ('yes', '1' and '2', respectively), which makes no sense at all.
If I'm correct, your form should look like this:
<form name="myform" action="checkboxes.asp" method="post">
<b>Select Allowed keywords below:</b><br>
<input type="checkbox" name="Check_ctr" value="yes"
onClick="Check(document.myform.check_list)"><b>Select all keywords</b>
<br>
<?php foreach($this->taguser as $taguser): ?>
<input type="checkbox" name="check_list" value="<?php echo $this->escape($taguser->tagCode);?>">
<br>
<input type="checkbox" name="check_list" value="<?php echo $this->escape($taguser->tagParentId);?>">
<br>
<?php endforeach; ?>
Still, you should read about Zend_Form. It will be hard to understand it in the beginning, but it's totally worth it.
Related
Sorry for what is probably quite an easy question, but I'm trying to pick up some info from my php form:
This is my current code which works for the post name, but what if I want to also grab the colours boxes that were selected too?
main.php
<?php
if (isset($_POST['submit'])) {
$data = $_POST['name']; // the data from the form input.
}
$colour_array = [
"red" => "#9E2A2B",
"blue" => "#3E5C76",
"green" => "#335C67",
];
?>
...
<form action="/" method="post">
<input type="text" name="name" placeholder="Acme Corp"/>
<input name="colour" type="checkbox" value="red">Red<br>
<input name="colour" type="checkbox" value="blue">Blue<br>
<input name="colour" type="checkbox" value="green">Green<br>
<input type="submit" name="submit" value="Submit">
</form>
<img src="pngfile.php?data=<?php print urlencode($data);?>"
alt="png php file">
I guess I confused because currently it is calling this:
pngfile.php
<?php
require_once 'functions.php'; // Requires and includes do not need brackets.
$inputData = urldecode($_GET['data']);
process($inputData);
exit;
?>
Which calls functions.php
<?php
function process($inputdata)
{
...
The issue is I want to be able to separate out the values from the form, so I get both the input box and the colour selection in separate variables.
EDIT: What I have tried:
main.php
$data = $_POST['name'] && $_GET['colour']
functions.php
process($inputdata, $colours)
But I'm not really sure where to go from there.
In HTML, change name="colour" to name="colour[]"
To access the value of colour in php do something like below
<?php
if(!empty($_POST['colour'])) {
foreach($_POST['colour'] as $check) {
echo $check; //echoes the value set in the HTML form for each checked checkbox.
}
}
?>
This question already has answers here:
PHP Text Field value shows incomplete data, only 1 word
(5 answers)
Closed 11 months ago.
I want to create a page which allows a user to select colours (among the listed ones, via checkboxes). When the user clicks on the submit button, all the selected colours should get displayed with their corresponding colours as their font colour.
Here is my code:
<?php
if(!isset($_POST['button'])) {
?>
Colours<br>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method=post>
<input type="checkbox" name="colours[]" value="Red">Red<br>
<input type="checkbox" name="colours[]" value="Blue">Blue<br>
<input type="checkbox" name="colours[]" value="Green">Green<br>
<input type="checkbox" name="colours[]" value="Yellow">Yellow<br>
<input type="checkbox" name="colours[]" value="Pink">Pink<br>
<input type="submit" name="button" value="Show"> </form>
<?php
} else {
if (isset($_POST['colours'])) {
echo "Colours selected are:<br><UL type=circle>";
foreach($_POST['colours'] as $color)
echo "<LI><font color='echo $color'; >$color</font>";
echo"</UL>";
} else {
echo "No colour selected";
}
}
?>
There is a bug somewhere, the font colors are not as expected.
I want it like this image below:
Simply write
echo "<li><font color='$color'> $color </font></li>"; // complete li tag
other mistakes:-
a) form method attrubute should be method='post'
b) UL type=circle should be ul type='circle'
When appending a string to variable or another string, you must concatenate the values with a . (dot). for example:
echo("<li><font color=".$color.">".$color."</font>");
Try this;
echo "Colours selected are:<br><UL type=circle>";
foreach($_POST['colours'] as $color) {
echo " <LI><font color='".$color."'>'".$color."'</font></LI>";
}
echo"</UL>";
so i have this code fragment here..
if($numTF > 0)
{
echo "TRUE-AND-FALSE QUESTIONS: Enter them below followed by their correct answer.";
echo "<br>";?>
<form method="post" action="" name="quizform">
<?php for ($i=1; $i<=$numTF; $i++)
{
echo "Question"." ".$i;
?>`
<p><textarea name='question<?php echo $i; ?>' rows=3 cols=90></textarea></p>
<input type="radio" name="answer<?php echo $i; ?>" value="True"> True
<input type='radio' name="answer<?php echo $i; ?>" value="False"> False<br><br><br>
<?php
}
}
... i am making a quiz maker in php...
the first thing to do is to set up the desired number of questions, so the value entered will go on the $numTF variable. Depending on the entered value, the textarea part will be printed. and there will be different names for each text area. AND THE CODE ABOVE IS WHERE U PRINT THE FORMS AFTER U ENTER THE DESIRED VALUE.
The next thing is to save that in a database. since the name of each textarea will be based on a variable value($i) that is used in a loop (name="answer") , HOW CAN I USE IT IN $_POST??? Like, would i do it like this?? ($_POST['question']).
HOW CAN I SAVE THESE QUESTIONS IN A DATABASE??
PLEASE HELP ME ....
I WOULD BE SO MUCH MUCH MUCH GRATEFUL FOR A LIL HELP.
<?
var_dump($_POST);
?>
<form method="post">
<?
$numTF=4;
if($numTF > 0)
{
echo "TRUE-AND-FALSE QUESTIONS: Enter them below followed by their correct answer.";
echo "<br>";?>
<form method="post" action="" name="quizform">
<?php for ($i=1; $i<=$numTF; $i++)
{
echo "Question"." ".$i;
?>`
<p><textarea name='question[<?php echo $i; ?>]' rows=3 cols=90></textarea></p>
<input type="radio" name="answer[<?php echo $i; ?>]" value="True"> True
<input type='radio' name="answer[<?php echo $i; ?>]" value="False"> False<br><br><br>
<?php
}
}
?>
<input type="submit" name="submit" value="submit"/>
</form>
Use $_POST['question'][1] // To get first question
Use $_POST['answer'][1] // To get first answer
Use loop to get all question and answers
I agree with Sachin as far as using name='question[]'. To answer question a little more as far as storing it in a database. Personally I would use a JSON array.
$store_answers = json_encode($_POST['answer']);
$store_questions = json_encode($_POST['question']);
Then just store $store_string in a TEXT field in your database. Then when you pull it back out of the database you can simple use:
$answers = json_decode($store_answers);
$questions = json_decode($store_questions);
Then you can loop through using a foreach like so:
foreach($questions as $key=>$question) {
echo "Question $key = {$answers[$key]} <br />";
}
This will display the results for each question.
i'm new to php , i have been searching for a tutorial regarding inserting form's input(text) , radio and selection data to MySQL database's table using php. i found some tutorials but most are confusing. So i decided to ask.
Okay here's what i want to do. I have a form which have two types of input and a selection
1. input type text
2. input type radio
3. selection
Here's the HTML code :
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
<input type="submit" name="submit" value="Submit">
</form>
I have set the form action to blank because the php code will be in the same file as the HTML (it's a php file btw)
MySQL table : info
structure :
1. name
2. class
3. agree
I want the php code to insert myname into name , selection's selected data into class , radio selected data into agree
P/S Yes i have added a connect to database php script , i just want to know how to get the form data into mysql.
Can someone write a php code example on how can i do this?
Thanks and have a nice day . I hope i have provided enough information. Thanks again if you help.
1. There is a problem with your radio element. The name should be the same for both options.
It should be like this:
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
2. You can access everything in the $_POST array, since you are using the method post for the form.
$name = $_POST['myname'];
$selection = $_POST['selection'];
$agree = $_POST['agree'];
3. If you are not using parametrized SQL with a library such as PDO, MySQLi, etc... you must always escape the data, which will be used in query using mysql_real_escape_string(), in order to protect against SQL injection.
This would be a sample code, to do the escaping and the query.
// write a function somewhere, to use as a shortcut
// for escaping data which will be used in a query
function sql_escape($str){
return "'".mysql_real_escape_string($str)."'";
}
// build the query
$query = sprintf('INSERT INTO table_name(name, class, agree) VALUES(%s, %s, %s)',
sql_escape($_POST['myname']),
sql_escape($_POST['selection']),
sql_escape($_POST['agree']));
// finally run it
$result = mysql_query($query);
I've taken it a little further here, there is still plenty more that can be done and many way's to do it, for instance you could extend the $errors array to include a field id and then highlight the HTML form field so the user can see exactly where they went wrong.
Considering your form is fairly simple you would not need this.
#Shef's code would certainly do the job but I thought you might be interested in some more.
<?php
// check the form has been submitted
if (isset($_POST['submit'])) {
// escape the form fields and assign them to variables
// validate myname to ensure the user entered data
if (isset($_POST['myname']) && $_POST['myname']!='') {
$myname = mysql_real_escape_string($_POST['myname']);
} else {
// create an error variable array to store errors to display
$errors[] = 'Please enter your name';
}
// no need to validate selection here as it alway's has a value
$classtype = mysql_real_escape_string($_POST['selection']);
// validate agree unless you want to add 'checked' to one of the values
if (isset($_POST['agree']) && $_POST['agree']!='') {
$agree = mysql_real_escape_string($_POST['agree']);
} else {
$errors[] = 'Please tell us if you agree?';
}
//if errors found tell the user else write and execute the query
if ($errors) {
$message = '<p class="error">We found a problem:</p><ul>';
foreach($error as $msg){
$message .= '<li>'.$msg.'</li>';
}
$message .= '</ul><p>Please fix the error/s to continue.</p>';
} else {
// write the query
$query = "INSERT INTO table (myname, classtype, agree) VALUES ";
$query .= "('$myname','$classtype','$agree')"
// run the query
mysql_query($query);
$message = '<p class="sucessful">Thanks '.htmlspecialchars($myname).'. Your selection has been saved.</p>';
}
}
// print the message
// show the variables in the form field so they don't need re-input
if ($message!='') { echo $message; }
?>
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="<?php echo htmlspecialchars($myname) ?>" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A"<?php if ($classtype=='A') { echo ' selected'; } ?>>A</option>
<option value="B"<?php if ($classtype=='B') { echo ' selected'; } ?>>B</option>
<option value="C"<?php if ($classtype=='C') { echo ' selected'; } ?>>C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"<?php if ($agree=='Yes') { echo ' checked'; } ?>> or
<input type="radio" name="agree" value="No"<?php if ($agree=='No') { echo ' checked'; } ?>>
<input type="submit" name="submit" value="Submit">
</form>
Also: #sqwk, Don't point people towards w3schools, see this: http://w3fools.com/
Check whether there is any data in the $_POST array and get the values from it.
Have a look here—the second example down is what you need: http://www.w3schools.com/php/php_mysql_insert.asp
(You do have to make the changes that Shef suggested, though.)
Also remember to check your data-integrity, otherwise people could use your insert to run malicious code.
check this simple example:
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Sname: <input type="text" name="sname" />
<input type="submit" />
</form>
after you submit form, you can take name and sname.
welcome.php::
<?php
$name= $_POST["name"];
$sname= $_POST["sname"]; ?>
now you can use this variables as if you want.
I am setting up a form using this PHP that loops through all records a user may have:
<?php foreach ($items as $row): ?>
<tr>
<td>
<?php echo form_hidden('id', $row->id); ?>
</td>
<td>
<?php echo '<strong>' . $row->name . '</strong>'; ?>
</td>
<td>
<?php echo form_input('number', $number); ?>
</td>
<td>
<?php echo form_input('registry', $registry); ?>
</td>
<td>
<?php echo form_checkbox('OK', $ok, $ok); ?>
</td>
</tr>
<?php endforeach; ?>
This gives me a form with the following look:
The idea here is that each row belongs to a unique ID/row in the database, and I would like to allow the user to edit all on the same page/form, using a single submit button.
What would be the best way of implementing this?
When this data is submitted, there should be a way of looping through each packet of information (from each user) in my controller. Would this be done via ajax/json?
This does not use codeigntier, but you should be familiar with the general technique before attempting to use CI to shortcut this process. Codeigniter will help you with rendering the form elements, performing validation, escaping your input and performing your query - but it will only help you (do anything) if you understand the basic principles involved. Hope this helps
MARKUP
<form action="/process.php">
<div>
<h2>GORDON</h2>
<input type="text" name="user[1][number]" /> <!-- The number corresponds to the row id -->
<input type="text" name="user[1][registry]" />
<input type="checkbox" name="user[1][ok]" value="1" />
</div>
<div>
<h2>ANDY</h2>
<input type="text" name="user[242][number]" />
<input type="text" name="user[242][registry]" />
<input type="checkbox" name="user[242][ok]" value="1" />
</div>
<div>
<h2>STEWART</h2>
<input type="text" name="user[11][number]" />
<input type="text" name="user[11][registry]" />
<input type="checkbox" name="user[11][ok]" value="1" />
</div>
<input type="submit" />
PHP
$users = $_REQUEST['user'];
foreach ($users as $rowId => $info){
// YOU SHOULD MAKE SURE TO CLEAN YOUR INPUT - THIS IS A GUESS AT WHAT YOUR DATA TYPES MIGHT BE
$id = (int) $rowId;
$number = (int) $info['number'];
$registry = mysql_real_escape_string($info['registry']);
$ok = (int) ($info['ok']);
$q = "UPDATE user SET number = $number, registry = '$registry', ok = $ok WHERE id = $id";
mysql_query($q);
// You may want to check that the above query was sucessful and log any errors etc.
}
There's no need to use ajax mate.
For each put a hidden input with the ID of the row in this format:
<input type="hidden" name="id[<?= $row->id ?>]" value="<?= $row->id ?>" ?>
Do the same for each element in the tr, i.e. name them as
name="number[<?= $row->$id ?>]"
name="registry[<?=$row->$id ?>]"
name="ok[<?=$row->$id ?>]"
and once you post the FORM you can iterate each row with:
foreach ($_POST['id'] as $key => $value) {
echo $_POST['name'][$key];
}
You need to set up input-names as array-names, so you will send the whole form and may iterate over the entries.
e.g.
<?php
echo form_input('userdata[' . $row->id . '][number]', $number);
?>
which would possibly create an
<input name="userdata[1][number]" />
(I don't know where those form-functions came from…)
This will result in an array $_POST['userdata'] which may be iterated via:
foreach($_POST['userdata'] as $userId => $userInputFields)
{
$user = new User($userId);
$user->number = $userInputFields['number'];
// …
}