I have a system project where I can create fuel expenses records, so the process to create an expenses records, I fill up the first form with names of employee,
here's my first form:(using this form, I can access all employee's name from database)
<div class="form-group">
<label>Employee Name</label>
<select name="employee" onchange="getEmp(this.value)" class="form-control">
<option value="">Select Employee</option>
<?php foreach($emps as $emp) : ?>
<option value="<?php echo $emp["employee_id"]; ?>"><?php echo $emp["surname"] . ', ' . $emp["firstname"]; ?></option>
<?php endforeach; ?>
</select>
<div class="help-block with-errors"></div>
</div>
the name of employee is already stored in the table named tbl_employee, each names are provided with codename and issued with vehicle. so in other words, I have two tables in my database named, tbl_employee and tbl_vehicle.
the tbl_employee has attribute: employee_id(primary key), carid(foreign key) surname, firstname and codename,
the tbl_vehicle has attribute: carid(primary key) and reg_num(registration number or plate number)
what I want is, when I select a names from the form stated above, I want to automatically fill the form (stated below) with its codename and a reg_num(plate number):
<div class="form-group">
<label>Employees Code Name</label>
<input class="form-control" name="codename" type="text"/>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label>Plate Number</label>
<input class="form-control" name="reg_num" type="text"/>
<div class="help-block with-errors"></div>
</div>
I also using this SQL statement to access the employees name directly from the database:
$emp = query("SELECT * FROM tbl_employee");
render("./fuel/list.php", ["title" => "Fuel Expenses List", "fuels" => $rows, "emps" => $emp]);
as you see, there is no javascript written on my codes, that's one of the reason why I need everyone's help.
You try this:
onkeyup(getEmp(this.value));
Related
I am quite new in PHP and all web development. I am wondering if someone could help me with data flow. I am trying to send form data to a PHP file and then call the function from the class to send data to the sql database. Right now, I don't have any PHP extensions in VS Code so I could debug it and see what is not working. And ofcourse in DOM there is only JS file and PHP which holds HTML code.
This is my code in JavaScript where it takes all user given data and sends it to php. But in form it consists of three static inputs, and then there is a switcher, which displays a user defined view.
`
//Function check for correct input with .value() call
//If it returns 'true' it proceedss with further validation of additional fields that change dynamically.
//When all fields have passed validation function begins to POST FormData to PHP file for backend work.
if(validate.test(sku) && validate.test(name) && validatePrice.test(price)){
if(validateAdditional(this.switcher)){
let xml = new XMLHttpRequest();
xml.open("POST", "./backend/product.php", true);
xml.onload = () => {
if(xml.readyState == 4 && xml.status == 200){
let response = xml.response;
alert(response);
form.reset()
history.back();
}
};
let formData = new FormData(form);
xml.send(formData);
}
}else{
alert("Please check if there is not any spaces or special characters added");
}
}
Then I created a class that will hold all of the network calls to post/read/edit/delete data from the sql database.
class DatabaseCalls{
private $servername = "localhost";
private $username = "root";
private $password = "";
private $dbname = "scandiweb";
public function insertData($dataQuery){
$connection = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if(!$connection){
return die("Connection failed" . $connection->connect_error);
}
if($connection->query($dataQuery)){
return "Done";
}else{
echo "Error: " . $dataQuery . "<br>" . $connection->connect_error;
}
$connection->close();
}
}
And then where there are model call network functions to send it to sql. JS file post data to models file. And then procedurally create the Product object and call the first function where I populate the input data.
<?php
include("netowking.php");
$sku = $_POST['sku'];
$name = $_POST['name'];
$price = $_POST['price'];
$memory = $_POST['dvd-memory'];
$dvdProduct = new Product($sku, $name, $price, $memory);
echo $dvdProduct->insertQuery();
class Product extends DatabaseCalls{
private $sku;
private $name;
private $price;
private $memory;
public function __construct($sku, $name, $price, $memory){
$this->sku = $sku;
$this->name = $name;
$this->price = $price;
$this->memory = $memory;
}
public function insertQuery(){
$sql = "INSERT INTO dvd (SKU, Name, Price, Memory)
VALUES ('$sku', '$name', '$price', '$memory')";
$response = $this->insertData($sql);
return $response;
}
}
And for context I will all also HTML code.
<form class="input" name="input">
<div>
<label for="sku">SKU:</label>
<input id="sku" type="text" name="sku" placeholder="#SKU">
</div>
<div>
<label for="name">Name:</label>
<input id="name" type="text" name="name" placeholder="#name">
</div>
<div>
<label for="price">Price ($):</label>
<input id="price" type="text" name="price" placeholder="#price">
</div>
<div class="switcher">
<h3>Type Switcher</h3>
<select name="select" id="select">
<option selected disabled>Choose a type</option>
<option value="dvd">DVD</option>
<option value="furniture">Furniture</option>
<option value="book">Book</option>
</select>
</div>
<div class="switchContent">
<div class="dvd-mem", id="dvd">
<p>DVD-disc</p>
<label for="dvd-memory">Size(MB):</label>
<input id="dvd-memory" type="text" name="dvd-memory" placeholder="Please enter MB amount here">
<p>Please enter amount of disc memory in MB.</p>
</div>
<div class="furniture" id="furniture">
<p>Furniture</p>
<div>
<label for="height">Height(CM):</label>
<input id="height" type="text" name="height" placeholder="Enter height in here">
</div>
<div>
<label for="width">Width(CM):</label>
<input id="width" type="text" name="width" placeholder="Enter width in here">
</div>
<div>
<label for="lenght">Height(CM):</label>
<input id="lenght" type="text" name="lenght" placeholder="Enter lenght in here">
</div>
<p>Please enter all dimensions of furniture</p>
</div>
<div class="book" id="book">
<p>Book</p>
<label for="weight">Weight(KG):</label>
<input id="weight" type="text" name="weight" placeholder="Please enter weight in KG">
<p>Please enter weight of book</p>
</div>
</div>
</form>
I have a Payments table, which has 3 fields (id, item, amount) with the following query, with which I fill a combobox with all items, now I want to make that every time I select an item, the amount is automatically filled in an imput that I have in the form.
<div class="form-group">
<label class="col-sm-2 control-label" for="Old">Tipo de pago* </label>
<div class="col-sm-10">
<select class="form-control" id="pagos" name="pagos" >
<option value="" >Selecciona pago</option>
<?php
$sql = "select id, rubro, monto from pagos";
$q = $conn->query($sql);
while($r = $q->fetch_assoc())
{
echo '<option value="'.$r['id'].'" '.(($pagos==$r['id'])?'selected="selected"':'').'>'.$r['rubro'].'</option>';
}
?>
</select>
</div>
</div>
If I understood what you want, you could use jQuery to do that:
Let's suppose you have you have an Input:text with the id="MyInput"
$('#pagos').change(function() {
$('#MyInput').val($('#pagos').val());
})
I know php is a server-side language and html a client-side language and to do this i would use javascript but i don't know how to do.
Can someone help me to write the script called changeFunction()?
This is my form in index.php:
<form method="POST">
<div class="row"style="margin-top: 5%;">
<div class="col-3">
</div>
<div class="col-6">
<label for="inputUsername">Insert username</label>
<input type="text" class="form-control" name="inputUser" style="margin-bottom: 2%">
<div class="input-group mb-3">
<div class="input-group-prepend">
<label class="input-group-text" for="inputGroupSelect01">Convert account type to: </label>
</div>
<select class="custom-select" id="inputGroupSelect01" name="inputSelected">
<option selected>Choose...</option>
<option value="admin">Admin</option>
<option value="user">User</option>
</select>
<button type="button" class="btn btn-outline-primary" onclick="changeFunction()">Submit</button>
</div>
</div>
<div class="col-3">
</div>
</div>
</form>
This is my query in query.php:
<?php
$var1= $_POST["inputGroupSelect01"];
$var2= $_POST["inputUser"];
require 'connection.php';
$sql = "UPDATE user SET typeAcc =".$var1." WHERE username=".$var2;
?>
I hope this is the solution you want .
First add the following div in you html form <div id='resultDiv' ></div>
so your html form code be like this
<form method="POST" >
<div class="row"style="margin-top: 5%;">
<div class="col-3">
<h2>Testing Form</h2>
</div>
<div class="col-6">
<label for="inputUsername">Insert username</label>
<input type="text" class="form-control" name="inputUser" style="margin-bottom: 2%" id="inputUser">
<div class="input-group mb-3">
<div class="input-group-prepend">
<label class="input-group-text" for="inputGroupSelect01">Convert account type to: </label>
</div>
<select class="custom-select" id="inputGroupSelect01" name="inputSelected">
<option selected>Choose...</option>
<option value="admin">Admin</option>
<option value="user">User</option>
</select>
<button type="button" class="btn btn-outline-primary" onclick="changeFunction()">Submit</button>
</div>
<!-- this need to be added -->
<div id='resultDiv' ></div>
</div>
<div class="col-3">
</div>
</div>
</form>
Second add the jQuery and following script to your code
two jquery variable define userName and role which is later passed as data
and if server response is SUCCESS then success condition executed or you can send data or particular error message by setting ERROR with YOUR ERROR TEXT
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script type='text/javascript'>
function changeFunction(){
var userName = $('#inputUser').val();
var role =$('#inputGroupSelect01').val();
$.ajax({
method: "POST",
url: "server.php",
data: JSON.stringify( { "userId": userName, "userRole": role } ),
dataType: "text",
success: function (response){
if(response=='SUCCESS'){
$('#resultDiv').append('<br/>Successful Updated'+response);
}else{
$('#resultDiv').append('<br/>Error'+ response);
}
}
});
}
</script>
**Third ** you have to write the new server.php file with following code
<?php
$var1= $_POST["userId"]; // change here userId as used in jquery block
$var2= $_POST["userRole"];// change here userRole as used in jquery Block
//require 'connection.php';
$sql = "UPDATE user SET typeAcc =".$var1." WHERE username=".$var2;
//suppose query is executed successfull then
//it will return no of rows updated
$query_result = mysql_query($query);
//SUCCESS_CONDITION is normally if number of row updated is 1 in return
///of query execution so kindly define by your own way
$num_rows = mysql_num_rows($query_result);
//if($num_rows==1 || define your own SUCCESS_CONDITION){
if($num_rows ==1){
$result ='SUCCESS';
}else{
$result ='ERROR';
}
echo $result;
?>
I hope it will help
Thanks
Ask for help if needed
You can do this using PHP but you need to check $_POST data.
if(isset($_POST['inputGroupSelect01']) && isset($_POST['inputUser;]){
$var1= $_POST["inputGroupSelect01"];
$var2= $_POST["inputUser"];
require 'connection.php';
$sql = "UPDATE user SET typeAcc =".$var1." WHERE username=".$var2;
}
By the way, that code is entirely vulnerable. You are taking 2 inputs from users and placing them directly, and placing them into a SQL query.
What if my input for var2 was '; DROP TABLE user; ?
I have used the code below elsewhere in my site and it works. For the life of me I can't understand why it doesn't work here. PROBLEM: keeps throwing alert message.
My HTML:
<form action="processForms.php" method="post" id="joinCommitteeForm" class="headForm shadow">
<div class="outerBlue" style="background:white">
<button type="button" id="cancelForm" class="button" title="Cancel">X</button>
<br><br>
<h3>Get involved—join a committee!</h3>
<?php if(empty($name)||empty($email)||empty($workPhone)){
echo "<p class='red'>All fields must be filled out...</p><br><br>";
}?>
<label for="name" style="width:40px">Name</label><input type="text" name="name" id="name"/><br>
<label for="email" style="width:40px" class="clear">Email</label><input type="text" name="email" id="email"/><br>
<label for="phone" style="width:40px;margin-bottom:20px" class="clear">Phone</label><input type="text" name="dayPhone" id="phone"/>
<hr>
<p class="clear">Please select a committee from the list below</p><br><br>
<select name="comName" id="comName" style="width:215px;margin-left:50px;float:left">
<option value="">Select one...</option>
<?php
$sql = mysql_query("SELECT committeeName FROM committeeName ORDER BY committeeName");
while ($row = mysql_fetch_assoc($sql)){
echo "<option value = '".$row['committeeName']."'>".$row['committeeName']."</option>";
}
echo "</select>";?>
<input type="submit" name="submitCommitteeInterest" class="button orange-button clear" value="Submit" style="margin-top:40px"/>
<div class="clear"></div>
<p class="small white" style="line-height:1em;margin-top:20px">NSGP never sells or gives away your personal information</p>
</div>
</form>
My JS:
$("#joinCommitteeForm").submit(function() {
if ($.trim($("#email").val()) === "" || $.trim($("#name").val()) === "") {
alert('All fields are required');
return false;
}
});
What I suspect the problem is here, is that you are testing if $name or $email is empty, but since you never define them, they will always be empty, per PHP empty() docs: "A variable is considered empty if it does not exist or if its value equals FALSE".
To fix that, you'll need to change your PHP if-statement to:
<?php if(empty($_POST['name'])||empty($_POST['email'])||empty($_POST['dayPhone'])){
echo "<p class='red'>All fields must be filled out...</p><br><br>";
}?>
Also, your POST parameter $workPhone doesn't seem to exist in your form. I've changed it to dayPhone here.
The variable $_POST will contain all parameters in the POST request from the form that's submitted.
I am creating a form that allows the user to supply additional addresses they are located at. I have a drop down that asks "How many additional locations do you have?" based on the number they select I clone the fields "Address, City, State, Zip" and place them directly underneath of each other inside the same form.
What I described above is working but now I am attempting to retrieve the data from these additional fields I added. When the user clicks the submit button the form submits to the same page where I have PHP listening to see if the form has been submitted or not. If it has been submitted I echo the values of the form to the screen.
Now here is the problem. If I leave the dropbox alone so that it is at the default value of "1" fill out the form and click submit I see what I entered. But if I select any other value from the drop down and submit the information from all of the forms I only see the information from the last form and not all of them. Why is this? I have included my code below.
Here is the form :
<form id="blah" method="post">
<div class="Page" id="AdditionalLocations">
<fieldset name="first" class="additional">
<legend>Additional Locations</legend>
<p><label for="Address">Address</label> <input name="Address" type="text" id="Address" /><br /></p>
<p><label for="City">City</label> <input type="text" name="City" id="City" /></p>
<p>
<label for="State">State</label>
<select id="State" name="State">
<option selected="selected">Select your state...</option>
<?php foreach($states as $key=>$value) { ?>
<option value="<?php echo $key; ?>"><?php echo $value; ?></option>
<?php } ?>
</select>
</p>
<p><label for="Zip">Zip Code</label><input type="text" name="Zip" maxlength="6" /></p>
<p><label for="Country">Country</label><select id="Country" name="Country">
<option value="US" selected="selected">United States</option>
<option value="CA">Canada</option>
</select></p>
<input type="submit" value="SUBMIT FORM" />
</fieldset>
</div>
</form>
This is how the fields are created based on the dropdown
var cloneIndex = 0,
cloneObj = $('.additional').eq(0);
$(document).on('change', "#NumberOfLocations", function() {
if ( $(this).val() !== "" ) {
for( var x = 2; x < $(this).val(); x++ ) {
$('#AdditionalLocations').append( cloneObj.clone( true ).attr('' ,'data-index', ++cloneIndex) )
}
}
});
This is how I echo the results of the form. It works if I don't create new additional fields based on the drop down.
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
var_dump($_POST);
foreach( $_POST as $field ) {
if( is_array( $field ) ) {
foreach( $field as $field2 ) {
echo $field2;
}
} else {
echo $field2;
}
}
}
?>
If I select 2 as the value in the number of locations field this is the html output I get:
<form id="blah" method="post">
<div class="Page" id="AdditionalLocations">
<fieldset name="first" class="additional"></fieldset>
<fieldset name="first" class="additional" data-index="1"></fieldset>
</div>
</form>
Inside the fieldset all of the fields are identical. Why do I not get both fieldsets echoed when I click submit?
UPDATE:
So I changed the names of the second field set by adding a "1" at the end inside the chrome inspector and submitted now I see all of the values I need. So I guess every field in the form has to have a unique name.
your field names should have array notation at the end of their names:
<input type="text" name="City[]" id="City" />
<select id="State" name="State[]">
when php gets these values they will then be in array so you will need to loop over each of the arrays to get the info
for($i=0; $i<count($_POST['City']); $i++){
$city = $_POST['City'][$i];
$state = $_POST['State'][$i];
...
}
There is probably a better way of getting the info out of the arrays, but this is quick and dirty