I need to setup A form where a user would be signing up to an event but while doing that it will collect the data of the user from their database table automatically while also taking information from the events table and inserting it into another table
What are you using primarily to achieve this at the moment? Are you using PHP? In case of PHP,
if you have a user id on whichever user that is going to fill out the form, then you can use that user id to fetch the information from whatever table that you need, and retrieve the information of the user. You then put those into PHP variables for later use. The only way to know which user is which, is by using sessions. This session can be their user id, which I will go by in this example, simply because it's simple and easy.
The handling of form data can be done by a classic form tag with post method and a submit button. You tell the form whichever page it is to supposed to post to.
It can also be handled by AJAX.
You then put those posts into PHP variables, or use them directly, but I personally prefer to put them into variables for clarification. It can look a bit messy using the post variables directly into your query, as well as the security risks it involves.
What it could look like is something like this:
<?php
/*
Firstly we need our session (this should be set upon logging by using $_SESSION['userId'].
As mentioned before, I am using a user id as our session variable in this example.
*/
/*
Carry over the session.
Use session_start() before anything else in a file to get the session of a user.
*/
session_start();
//Put session into a php variable
//mysql_ syntax:
$userId = mysql_real_escape_string($_SESSION['userId']);
mysqli_ syntax, with $conn being your database connection variable:
$userId = mysqli_real_escape_string($conn, $_SESSION['userId']);
mysqli_ syntax, with $conn being your database connection variable:
$userId = mysqli_real_escape_string($conn, $_SESSION['userId'])
?>
Now what is left, is to construct our form and send that data. Since I personally would prefer to handle the data in another file than the file that contains the form, we're going to tell the form to post to another file. This file will contain our form data, as well as our user data. How we will go by getting our user data is by using the session variable, which conveniently happens to be the user id (which is unique to every user). We can post this with everything else in our form by using a hidden input field carrying the user id variable (just as an example).
<!--
What we do here is make a form that that tells which page it is going to go to
on submit
-->
<form action="/another_page.php" method="POST">
<!-- Our hidden input field, carrying the user id -->
<input type="hidden" name="userId" value="<?php echo $userId; ?>" />
What brand is your current car?:<br />
<input type="text" name="carBrand" placeholder="Brand of your car" />
Tell us a little about yourself:
<textarea rows="4" cols="50" name="summary"></textarea>
Rate your experience, 1-5:
<select name="rating">
<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>
</select>
<br /><br />
<button type="submit" name="submitButton">Submit form!</button>
</form>
Now we go to the other file to handle our data, which we will later put into the second table as per your request.
<?php
//This is our POST variables from our form:
$userId = $_POST['userId'];
$car_brand = $_POST['carBrand'];
$summary = $_POST['summary'];
$rating = $_POST['rating'];
//Now to our SQL, to get there data of our user:
//Put SQL command into a variable
$sql = "SELECT * FROM name_of_user_table WHERE userId='$userId'";
//Put query into a variable with mysql_ syntax:
$result_set = mysql_query($sql);
//Put query into a variable with mysqli_ syntax:
//$conn still being your connection variable
$result_set = mysqli_query($conn, $sql);
//The rows in your table in mysql_ syntax:
$row = mysql_fetch_array($result_set);
//The rows in your table in mysqli_ syntax:
$row = mysqli_fetch_array($conn, $result_set);
/*
Now we can start using our data from the database, and store them into variables.
The variables depends on your fields names in the database.
We basically have the data stored into an array,
where we need to tell the array exactly which index we'd like to use
(in this case which field we'd like to store into a variable).
*/
//Examples:
$variable1 = $row['name_of_field'];
$variable2 = $row['name_of_another_field'];
[...]
?>
Now what is left, is to put everything into your second table, using our variables. Hope this helps :)
It is also very important that you use prepared statements before firing your SQL commands into your database, or at least sanitize the inputs to prevent SQL-injections.
Martin wrote a really comprehensive answer; I'm not saying that it is wrong (how could I? I don't speak PHP); however, as the OP tagged it as Oracle Application Express (not PHP), it might not be the best fit.
Anyway: that looks like a simple task: if signing up to the event is done by pushing a button (why wouldn't it be?), you'd create a process which does the rest of the job. Either write it in the appropriate process property, or create a stored procedure which collects data & inserts it elsewhere and - in the Apex process - call that procedure.
Related
I have an 'array type' dropdown field in my form, e.g:
<select name="category_id[]">
<option value="">Please Select</option>
// more options
</select>
There are 3 of these same fields (hence it being an array type) and they are all optional, but if a value is selected it checks whether it is a valid value as follows:
$rules['category_id'] = 'exists:universities,id';
The problem I'm having is that if the empty option is selected, it is still giving me a validation error, e.g "The selected category is invalid." If I select a valid value I don't get any errors (as expected).
I have tried adding both nullable and sometimes to the validation rule but they don't make any difference. Do I need to do something different with it being an array type field?
If you use "array-like" name for your select, you should use array validation like so:
$rules['category_id.*'] = ['nullable', 'exists:universities,id'];
But if it's not multi select, you can change the name to category_id to make it work
Can you try <option value="" selected disabled>Please select</option>. Also what does dumping $request->category_id give you when no selections are made?
I have a page with 3 combos, 6 dependents inputs text ( if a special value is selected in combo, it will show, otherwise it will hide)
Then, I will have A text fields that is a computed property. Each time an input is changed, it will reevaluate this field value.
So, For instance, My fields are:
GradeIni, GradeFin, Category, AgeCategory, AgeIni, AgeFin , Gender (selects)
isTeam ( Checkbox )
CategoryFullName
So, for example, There is 5 predefines AgeCategory,and the 6th is Custom, when Selected, it show AgeIni and AgeFin
Each time a value is change, CategoryFullName is reevaluated.
My first answered question was how to get values from server.
I knew how to do it with Ajax, but in this case, it was easier to just use Server variable sent by Laravel when pages load.
So, the answer was 2 options:
#foreach ($grades as $grade)
<option ...>{{ $grade }}</option>
#endforeach
Or
<grades :grades="{{ $grades }}"></grades>
So, I would like to use the second one, but it means I have to create a component for each Select Option in my page, which seems a little heavy.
So, I'm a little bit confused about how should I make this page. Is it better by AJAX, is it better to be able to get data from laravel, and o make a component for each list, or is there a better way to do it????
You dont need to use many components. One component and one variable to keep the selected grade are fine.
You can create a component template to display all the grades.
I have created one template with dummy data to show you how you can do it.
<template id="grades-list">
Curently selected: Title {{selected.title}} Value: {{selected.value}}
<select v-model="selected">
<option v-for="grade in grades" :value="grade">{{grade.title}}</option>
</select>
</template>
The component should be registered like this:
Vue.component('grades', {
props: ['grades', 'selected'],
template: '#grades-list'
})
The tricky part is how you will select a default value and keep it synced with the parent. To do so, you can use .sync
<!-- you can use :grades="{{ grades }}" with Blade too-->
<grades :grades="grades" :selected.sync="selectedGrade"></grades>
To set default value you can update the selectedGrade variable when the document is ready, using vm.$set.
new Vue({
el: 'body',
data: {
'selectedGrade': ''
},
ready() {
this.$set('selectedGrade', this.grades[1])
}
})
I have created an example with dummy data here.
I'm using the following code to insert a single register of address in the database:
$this->db->insert('address', $address);
The command above inserts with:
Inesert into table(columns) values(values)
I would like to know, is there command to insert without having to specify the field names, using CodeIgniter framework and if possible, without having to handwrite the insert sql query? Like:
Insert into table values(values)
Yes it can be done with raw sql But not on CI's db->insert function,
Why? because the function/method needs 2 parameters first is the table name and second an array of key and values where the keys is the DB table's column name and value is the column value.
Unless you create one or modify the existing function, but until that NO it cannot be done.
Try a different approach like using $this->db->query('..query ..'); where you put your own SQL
Late for party, i have tricky that with this code. With some note, just be sure <input name="..."> have same name, with field name inside your table.
<input type="text" name="field_1">
Maybe can help somebody,
Example Controller :
function post() {
if (isset($_POST['submit'])) {
$this->model_name->post_data();
redirect('to_page_view');
}
}
Example Model :
function post_data() {
unset($_POST['submit']);
$this->db->insert('table_name', $this->input->post());
}
First of all, I have already readed this: Validating form dropdown in CodeIgniter
But it doesnt solve my problem:
As you know, <option> value can be faked for example using firebug.
My select options looks like this:
<option value="ger">Germany</option>
<option value="uk">United Kingdom</option>
<option value="usa">United States of America</option>
[...]
Now, how can I validate if the choosen and posted value is correct?
These values are builded on the large array. It looks following:
$countries = array (
'ger' => 'Germany',
'uk' => 'United Kingdom',
'usa' => 'United States of America'
);
So how can I validate, of choosen value is correct? Will I have to use the array_key_exist with function callback on form validation?
What in case if my select options looks like this?
<option value="0">Choose Something</option>
<option value="1">Select-1</option>
<option value="2">Select-2</option>
[..]
How can I validate the above using the form validator, so I could check if the posted value is correct and not faked, also how to prevent from choosing the 0 value?
The best idea for this in my opinion is creating the function callback, which will look following:
public function validate_values($input)
{
$allowed = array(1, 2, 3, 4); //[..]
if ( !in_array( $input, $allowed ) )
{
//throw error, and do the rest...
}
}
Are my ideas "ok" or there are any better solutions for these cases?
The callback is exactly what you need. I think that's why they were created. In user guide:
"The validation system supports callbacks to your own validation
functions. This permits you to extend the validation class to meet
your needs."
So if your need is to check if submitted values are from defined range, use it.
Of course it should return false or true depending on result. user guide for callbacks
For me it's the best solution. Especially because you need to check those values after form is submitted.
As for preventing from choosing 0, don't put 0 to in_array or check first if $input is !empty for example and set correct error message. If you're creating your own callback you can validate that $input for whatever you want.
can anyone give me an example on how to create Sessions and write data to it. I've seen syntax on how to write data to a session using write command. But how to create a session and retrieve the values in it.
In my application, I have two data, form_id and user_id that needs to be used in all the page requests. So how do I save it as a session variable and use it across the application?
EDIT
function register()
{
$userId=$this->User->registerUser($this->data);
$this->Session->write('User.UserId',$userId);
//echo "session".$this->Session->read('User.UserId');
$this->User->data=$this->data;
if (!$this->User->validates())
{
$this->Flash('Please enter valid inputs','/forms' );
return;
}
$this->Flash('User account created','/forms/homepage/'.$userId);
}
How to use the session variable 'User.UserId' instead of $userId in $this->Flash('User account created','/forms/homepage/'.$userId);
And can I use this variable in all my view files,because in all the page requests I also pass the userId?
EDIT 2
I have 2 controllers,user and form. I write the userid to a session variable in the users_controller. I have a view file called homepage.ctp,whose action is in the forms_controller. Now how can I use the session variable defined in the users_controller in the homepage? Sorry if I am asking silly questions. I went through the cakebook,but my doubts weren't cleared. I'm also trying trial and error method of coding,so please help me.
EDIT 3
I have a session variable 'uid' which is the user id in the home page action of a controller.
$this->Session->write('uid',$this->data['Form']['created_by']);
I need the same variable in the design action method of the same controller.
When I give
$uid=$this->Session->read('uid');
echo "uid: ".$uid;
the value is not echoed.
Can't I use the session variable in the same controller?
The bakery is your best friend:
http://book.cakephp.org/view/398/Methods
All your session read/writes belong in the controller:
$this->Session->write('Person.eyeColor', 'Green');
echo $this->Session->read('Person.eyeColor'); // Green
In cake php you can create session like this
$this->request->session()->write('user_id', 10);
and you can read session value like this
echo $this->request->session()->read('user_id');
Super Simple!
You don't have to write any code to create session, they are already built in. Then you just use the read and write sessions as mentioned above. Also see here for more details:
http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html
Used in Controllers
http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html
Used in Views
cakephp 4 example of session usage in controllers, views and cells
$session = $this->request->getSession();
$session->write('abc', 'apple');
echo $session->read('abc');
In this case it would be:
$this->Flash('User account created','/forms/homepage/'.$this->Session->read('User.UserId'));
and your second question is anwered by Jason Miy (http://api.cakephp.org/class/session-helper). You can simply use this in your view:
$userId = $session->read('User.UserId');
Reading the appropriate cookbook pages slowly and carefully usually helps a lot...
I found out the reason why the uid wasn't being echoed(edit 3 part of the question).
It is due to a silly mistake, had a white space after the end tag ?> in the controller. Now it is working fine.
when I have strange session behavior, and this help me.
MODEL:
function clearAllDBCache() {
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$db->_queryCache = array();
}
`
Acess your Helper SessionHelper in lib/Cake/View/Helper/SessionHelper.php and add the method:
public function write($name = null) {
return CakeSession::write($name);
}