Retrieving a date from MYSQL in a html form - php

Hi I have a form to add members with their birth date. The input field for birth date is:
<div class="form-group">
<label for="data_nascita" class="col-sm-3 control-label">Birth Date</label>
<div class="col-sm-9">
<input name="data_nascita" type="date" class="form-control" id="data_nascita" placeholder="gg/mm/aaaa" />
</div>
</div>
Data are correctly uploaded to MYSQL and date format is
$data_nascita = ($_POST['data_nascita']);
var_dump($data_nascita); => string(10) "2003-04-15"
In the database is stored correctly, and it appears as
2018-12-14 18:50:48
I want to have the possibility to edit the information about the person (i.e. changing the birth date), and I created an edit file where all the database information is retrieved and appears in form fields that can be edited and updated in MYSQL.
Everything works fine except for dates, which appears as gg/mm/aaaa
The code I used for retrieving data is as usual:
<?php
$query = "SELECT data_nascita FROM volontari WHERE id_volontari = '$id'";
$res = $mysqli ->query($query);
$row = $res->fetch_array (MYSQLI_ASSOC);
$data_nascita = gira_data_db($row['data_nascita']);
function gira_data_db($data)
{
$array = explode( "-" , $data);
$array2 = array($array[2], $array[1], $array[0]);
$testo = implode( "/" , $array2);
return $testo;
}
?>
<div class="form-group">
<label for="data_nascita" class="col-sm-3 control-label">Birth Date</label>
<div class="col-sm-9">
<input name="data_nascita" type="date" class="form-control" id="data_nascita" value="<?php echo $data_nascita ?>" />
</div>
</div>
The date retrieved is
var_dump(gira_data_db($row['data_nascita']);) => string(10) "15/04/2003"
However in my form field the data appears as 00/00/0000. If I echo the date in an input field type=text, it appears correct.
Am I doing something wrong?

The problem is when you explode by '-' array[2] is '14 18:50:48' and it's not valid value for input with date type.
simply change gira_data_db function as follows:
function gira_data_db($data)
{
return date("YYYY-MM-DD", strtotime($data));
}
I hope it would help you

Related

How to have show error and not allow two inputs to be submitted in form PHP

One my form I have the option to choose from a select box, or to manually enter the information.
I want to prevent user from entering both. They should either choose from the select OR enter manually if their selection is not already there.
html code
<div class="row">
<div class="form-group col-sm-4">
<div class="row">
<div class="col-sm-3">
<label for="selectComplvl" class="regions" >Region</label></div>
<div class="col-sm-8">
<select class="form-control regionbox" id="region" value="" name="region">
<option>---Select---</option>
<?php
$region_sql = "SELECT * FROM `regions`";
$region_res = mysqli_query($con, $region_sql);
if(mysqli_num_rows($region_res) > 0){
while($region_row = mysqli_fetch_array($region_res)){
echo "<option value='".$region_row[id]."'>".$region_row[region]."</option>";
}
}
?>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="form-group col-sm-4">
<div class="row">
<div class="col-sm-4">
<label for="feisEntered" class="feis">Feis Entered</label></div>
<div class="col-sm-8">
<select class="form-control feisbox" id="feisEntered" name="feisEntered">
<option>First choose a Region</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="form-group col-sm-4">
<div class="row">
<div class="col-sm-3">
<label for="feisEntered" class="enterfeis">Or Enter</label></div>
<div class="col-sm-8">
<input id="inputfeis" type="text" name="feisEntered" class="form-control" placeholder="Feis name - MM/DD/YYYY">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
</div>
And my query:
if(isset($_POST['submit'])){
$dancer=$_POST['dancer'];
$dancer = mysqli_real_escape_string($con,$dancer);
$level=$_POST['level'];
$level = mysqli_real_escape_string($con,$level);
$feisEntered=$_POST['feisEntered'];
$feisEntered = mysqli_real_escape_string($con,$feisEntered);
$danceName=$_POST['danceName'];
$danceName = mysqli_real_escape_string($con,$danceName);
$compNum=$_POST['compNum'];
$compNum = mysqli_real_escape_string($con,$compNum);
$competitor = $_POST['competitor'];
$competitor = mysqli_real_escape_string($con,$competitor);
$danceScore = $_POST['danceScore'];
$danceScore = mysqli_real_escape_string($con,$danceScore);
$placement = $_POST['placement'];
$placement = mysqli_real_escape_string($con,$placement);
$firstScore = $_POST['firstScore'];
$firstScore = mysqli_real_escape_string($con,$firstScore);
$secondScore = $_POST['secondScore'];
$secondScore = mysqli_real_escape_string($con,$secondScore);
$thirdScore = $_POST['thirdScore'];
$thirdScore = mysqli_real_escape_string($con,$thirdScore);
$judge = $_POST['judge'];
$judge = mysqli_real_escape_string($con,$judge);
$comments = $_POST['comments'];
$comments = mysqli_real_escape_string($con,$comments);
$query = "INSERT INTO reports (user_id, dancer_id1, dancer_name, competition_level1, feis_entered, dance_name1, competition_number1, number_competitors1, dancer_score1, dancer_placement1, firstpl_score1, 2ndpl_score1, 3rdpl_score1, judge_name1, judge_comment1) VALUES ('$id','$dancerID', '$dancer', '$level', '$feisEntered', '$danceName', '$compNum', '$competitor', '$danceScore', '$placement', '$firstScore', '$secondScore', '$thirdScore', '$judge', '$comments')";
$result = mysqli_query($con, $query);
}
So what I want to happen is a error message appears if they fill out both saying "Please choose only one". That way only one enters into database.
Never rely on just JS to validate input. Use JS to implement the behavior you speak of and then handle all possible outcomes in PHP. If someone is fiddling with your JS and bypasses the behavior you implement, you need to be able to handle that in your PHP code as well to make sure DB doesnt get unexpected input and break everything. Just like Justin said above, you could select one or the other, or throw an error. I recommend throwing an error and telling the user to make sure they have JS enabled.
In your HTML document, you should use Javascript to validate the user input before submitting the form to the PHP script. Then, in the PHP script, you should double-check that values were not received for both the select and the input (this could happen if the user does not have Javascript enabled, or they somehow bypass the validation) and determine what you want to do in that case (select one over the other, or exit with an error).

Trying to pass a value to a model using Codeigniter

Trying to learn Coedigniter here and struggling a little bit from the start. I basically want to create a query in my model using a value in the url.
Controller (Customer.php)
public function customer_edit($id) {
$this->load->model( 'Customers_model' ); //loads model
$data[ 'results' ] = $this->Customers_model->edit_customers($id);
$this->load->view( 'customers/customer_edit', $data );
}
Model (customers_model.php)
public function edit_customers($id)//This function returns an array
{
$this->load->database('default', TRUE); //connect to database
$this->db->where(['idcustomers'=>$id]); //creates where statement from url
$query = $this->db->get('customers');//create query
return $query->result_array(); //creates array from query
}
View (customer_edit.php)
<div class="form-group">
<label class="control-label col-sm-2">First Name:</label>
<div class="col-sm-3"><input type="text" class="form-control" name="txtfname" value="<?php echo $results['fname'];?>">
</div>
<label class="control-label col-sm-2">Last Name:</label>
<div class="col-sm-3"><input type="text" class="form-control" name="txtlname" value="">
</div>
</div>
When I go to http://blahblah.com/customers/customer_edit/454 I get the following error:
Message: Undefined index: fname
Filename: customers/customer_edit.php
Line Number: 10
This is what I know:
On other pages where I am just displaying all the records in a table it works fine so I am not having a database connection problem. fname and idcustomers are the correct column names in the database.
Thanks in advance for your help.
Here is how I solved the problem. I added a foreach at the beginning of the form like this:
<div class="form-group">
<label class="control-label col-sm-2">First Name:</label>
<div class="col-sm-3"><input type="text" class="form-control" name="txtfname" value="<?php echo ucwords(strtolower($object['fname']));?>">
</div>
Thanks Ghost for helping answer this question.

Can you assign values to hidden fields in a form, through a php function, to be stored in a database?

I created a form you know; text fields, radio buttons and the submit button
within the said form, I have a div enclosing a section of the radio buttons hidden and a text field upon page load using inline CSS display:none;
If the end user chose yes, the hidden fields will be displayed using a jquery function. If the user chose No or Not Sure, the form will remain hidden or become hidden using the same jquery function.
If the user chose No or Not Sure, i want to automatically assign values for the hidden fields and store them in database.
Here is my form:
<div id = "relation" style = "display: none;">
<p class= "form-p" >Who are you related o?</p>
<div class="form-group">
<label class="col-sm-2 control-label"></label>
<div class="col-sm-4">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default">
<input type="radio" autocomplete="off" name="family" value="Bride" required />Bride
</label>
<label class="btn btn-default">
<input type="radio" autocomplete="off" name="family" value="Groom" required />Groom
</label>
<label class="btn btn-default">
<input type="radio" autocomplete="off" name="family" value="Friend" required />Friend
</label>
<span class="error"><?php echo $famErr;?></span>
</div>
</div>
</div>
<p class = "form-p">Guests in your party, including yourself: </p>
<div class = "form-group">
<label class="control-label col-sm-4"></label>
<div class="col-xs-2">
<input type = "text" class = "form-control" name="num" placeholder = "0" required />
<span class="error"><?php echo $numErr;?></span>
</div>
</div>
</div> <!-- end of id relation-->
Here are the functions:
// function to add RSVP user entry to the database
public function user_attending_storage_RSVP($name, $email, $attend, $fam, $num){
$replies = "INSERT INTO rsvp (name, attending, family, total) VALUES (:name,:attending,:family,:total)";
try{
$query = $this->conn->prepare($replies);
$results = $query->execute(array(":name"=>$name, ":attending"=>$attend, ":family"=>$fam, ":total"=>$num));
}
catch(PDOException $e){
die($e->getMessage());
}
}
// function to add RSVP user entry to the database
public function user_not_attending_storage_RSVP($name, $email, $attend){
$replies = "INSERT INTO rsvp (name, attending, family, total) VALUES (:name,:attending,:family,:total)";
try{
$query = $this->conn->prepare($replies);
$results = $query->execute(array(":name"=>$name, ":attending"=>$attend, ":family"=>$fam, ":total"=>$num));
}
catch(PDOException $e){
die($e->getMessage());
}
}
Here's how I call the function on the webpage
// check for data in fields
if(isset($_POST['name']) ==true && isset($_POST['email']) ==true && isset($_POST['attending']) && isset($_POST['family']) && isset($_POST['num'])){
$name=test_input($_POST['name']);
$email=test_input($_POST['email']);
$attend=test_input($_POST['attending']);
$fam=test_input($_POST['family']);
$num=test_input($_POST['num']);
if($attend == "No" || $attend == "Not Sure"){
$fam = "nothing";
$num = 0;
//inserting user data from form into database
$genQuery->user_Not_attending_storage_RSVP($name, $email, $attend);
}
else{
//inserting user data from form into database
$genQuery->user_attending_storage_RSVP($name, $email, $attend, $fam, $num);
}
// send mail to user
$genQuery->user_invite_confirmation_RSVP($name, $email, $attend,$fam, $num);
}
You can use the getElementById() method...
if(getElementById('input_id').value() == 'no' || getElementById('user_id').value() == 'not sure'){getElementById('input_you_want_to_change).value('Defualt value')}
This will change the value if the user selects no or not sure. Then use PHP to store this new value in the database.

Insert date into SQL database from Angular form

I have a form in my HTML file that allows the user to choose a date, this input binds to an Angular value. The value is then sent into a PHP file to be inserted into a database. Below is the code that shows how i currently have it set up.
HTML input form
<input class="input" ng-model="release" type="date" />
Angular controller
$http.post("php/addEpisode.php", {
'release': $scope.release})
PHP file
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
#$release = $request->release;
$query = "INSERT INTO episode ( release )
VALUES ( '{$release}' )";
$result = mysqli_query($connection, $query);
All the other values (which are not shown here) that are inserted into the table work fine. It is just this value that is an issue.
In the database the 'release' value is stored as a date with a format of 'yyyy-mm-dd'.
<---EDIT--->
I have found the reason it was not working. The name of the column in the table could not be set to 'release', it had to be something different as 'release' is a key word.
this work for me very well
in html
<div class="form-group col-md-6">
<label class="col-md-4 control-label">*Fecha Radicacion</label>
<div class="col-md-8 inputGroupContainer">
<div class="input-group">
<md-datepicker
ng-model="formulario.fechaRadicacion"
disabled
>
</md-datepicker>
</div>
</div>
</div>
in the controller
$scope.fechaRadicacion = new Date();
$scope.fechaActual=function(){
$scope.formulario.fechaRadicacion=$scope.fechaRadicacion.toISOString().slice(0, 10);
console.log("esta es la fecha en radicacion JS ",$scope.fechaRadicacion);
console.log("esta es a fecha en formulario.fechaRadicacion",$scope.formulario.fechaRadicacion);
}
in the PHP
//echo 'el dato es :<pre>'.$r->formulario->fechaRadicacion.;

Cant get values of checkboxes in codeigniter

Im trying to insert multiple checkboxes but cant get their values in codeigniter 2
this is my code in View
<!-- Multiple Checkboxes (inline) -->
<div class="form-group">
<div class="col-md-4">
<label class="checkbox-inline" for="checkboxes-0">
<input type="checkbox" name="checkboxes[]" id="checkboxes-0" value="22">
Пентхаус
</label>
<br>
<!-- Text input-->
<div class="form-group">
<div class="col-md-8">
<input id="cena" name="cena[]" type="text" placeholder="Въведи цена" class="form-control input-md">
</div>
</div>
<label class="checkbox-inline" for="checkboxes-1">
<input type="checkbox" name="checkboxes[]" id="checkboxes-1" value="21">
Гараж/Паркомясто
</label>
<br>
<!-- Text input-->
<div class="form-group">
<div class="col-md-8">
<input id="cena" name="cena[]" type="text" placeholder="Въведи цена" class="form-control input-md">
</div>
</div>
This is my Model:
public function InsertCheckbox() {
$property_typesRequest = $this->input->post('checkboxes');
foreach($property_typesRequest as $value){
$this->db->insert_batch('property_type_details', $property_typesRequest);
}
}
in Controller i just use this:
$this->estate_m->InsertCheckbox();
And this going insert 0 in database, when i var_dump $property_typesRequest theres shows bool(false). I cant get values of checkboxes...
EDIT...
I have try to edit my code but still no result:
public function edit()/*this is controller */
{
$data=array('column_name'=>$this->input->post('checkboxes');
$result=$this->estate_m->InsertCheckbox($data);
if($result==true)
{
echo "Success";
}
else
{
echo "Fail";
}
}
public function InsertCheckbox($data) /*this is Model */
{
$this->db->insert('property_type_details', $data);
return ($this->db->affected_rows() != 1 ) ? false : true;
}
With this edited code always gives me Succes
Form submitted values should be in multi dimension array
To achieve that your form inputs should be in multi dimension.
For insert_batch() function, the array should be in multi dimension.
In array every key must be field names in db table and value must be the form input value.
So change the form structure like the below array.
array(
array(
'checkboxes' => 'checkboxe value' ,
'cena' => 'cena values'
),
array(
'checkboxes' => 'checkboxe value' ,
'cena' => 'cena values'
)
);
Form inputs should be like below:
<input name="data[1][checkbox_columnname]" type="checkbox" value="21">Пентхаус
<input name="data[1][textbox_columnname]" type="text">
<input name="data[2][checkbox_columnname]" type="checkbox" value="22">Гараж/Паркомясто
<input name="data[2][textbox_columnname]" type="text">
And the model should not have foreach loop.
Simply pass the data as below.
$data=$this->input->post('data');
$this->db->insert_batch('mytable', $data);
Please use this code in model.
public function InsertCheckbox() {
$property_typesRequest = $this->input->post('checkboxes');
foreach($property_typesRequest as $value){
$data['columnename'] = $value;
$this->db->insert('tablename', $data);
}
}
Hope it inserts into the database
Thank you

Categories