Storing id into database table throw there name - php

I'm working on small project for data entry.
let assume a table named material fields
id , name , visible , position
and other table named received_material fields
id , material_id , quantity , supplier
and one simple html form for receiving materials, structure here
<form method="post" action="<?php echo SERVER['PHP_SELF'] ?>">
<label for="date">date</label>
<input type="text" name="date" />
<label for="name">Material Name</label>
<input type="text" id="name" name="name" />
<label for="quantity">Weight</label>
<input type="text" name="quantity" />
<label for="supplier">Supplier</label>
<input type="text" name="supplier" />
<input type="submil" value="submit"/>
</form>
<script>
$('#name').autocomplete({source : 'supplier_chk.php'});
</script>
the supplier_check.php Script here...
<?php include 'includes/session.php'; ?>
<?php include 'includes/functions.php'; ?>
<?php if(!logged_in()) {
redirect_to('login.php');
}
?>
<?php if ( logged_in_role('administrator') || logged_in_role('store') ) { ?>
<?php echo msg(); ?>
<?php
$search = escape_string($_GET['term']);
$sql = "SELECT id, supplier_name FROM `supplier`
WHERE `supplier_name` LIKE '%$search%'";
$result = mysqli_query($connection,$sql);
confirm_query($sql);
$json = [];
while ( $row = mysqli_fetch_assoc($result) )
{
$json[] = $row['supplier_name'];
}
echo json_encode($json);
}
?>
I'm using JQuery UI For Name Autocomplete. fetching material name throw ajax method. it'll easily autocomplete material name but i've to store material id instead material name.. please help how to do this action using jquery/javascript or php.

add hidden field before name input give id to get element..
here html example
<form method="post" action="<?php echo SERVER['PHP_SELF'] ?>">
<label for="date">date</label>
<input type="text" name="date" />
<label for="name">Material Name</label>
<input type="hidden" id="id" name="id" />
<input type="text" id="name" name="name" />
<label for="quantity">Weight</label>
<input type="text" name="quantity" />
<label for="supplier">Supplier</label>
<input type="text" name="supplier" />
<input type="submil" value="submit"/>
</form>
<script>
$('#name').autocomplete({
minLength: 0,
source : 'material_chk.php',
focus: function( event, ui ) {
$( "#name" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#name" ).val( ui.item.label );
$( "#id" ).val( ui.item.id );
return false;
}
});
</script>
in material_chk.php
<?php
$search = escape_string($_GET['term']);
$size = isset($_GET['size'])? escape_string($_GET['size']): null;
$sql = "SELECT * FROM `materials`
WHERE `name` LIKE '%$search%'";
$result = mysqli_query($connection,$sql);
confirm_query($sql);
$json = [];
while ( $row = mysqli_fetch_assoc($result) )
{
$json[] = array("id"=>$row['id']),"label"=>$row['item_name']);
}
echo json_encode($json);
}

I'm note sure what you're asking, but I do have a tip. This is a general tip, not just restricted to suppliers, but I will use them as an example.
I would use a better solution: a dropdown list with all the supplier names. The value of each list item is the supplier ID. So you directly submit the supplier ID.
<select id="suppliers" name="supplierSelector">
<option value="1">Philips</option>
<option value="2">Sony</option>
<option value="3">Samsung</option>
<option value="4">Akai</option>
</select>
You could additionally put a search text input below the dropdown list. Anything typed into that search box will restrict the dropdown list. This can be done in Javascript.
But basically my solution is to let the user select the correct supplier ID using their names. in PHP that would be:
$sql = 'SELECT id, supplier_name FROM supplier';
$result = mysqli_query($connection,$sql);
echo '<select id="suppliers" name="supplierSelector">'.PHP_EOL;
while ($supplier = mysqli_fetch_assoc($result))
{
extract($supplier);
echo '<option value="'.$id.'">'.$supplier_name.'</option>'.PHP_EOL;
}
echo '</select>'.PHP_EOL;
The added advantage of this method is that the form cannot be submitted without a valid supplier. In general you should try to restrict the input to what you know is allowed.

Related

Inserting data using JQUERY and PHP

Imagine I have 3 data's in my room_table and the column is room_id, image, room_name then I'm going to display the data of my room_table in my html code.
PS: Ignore the text_checkin, text_checkout first. I'm going to explain after the code.
HTML code:
$db = mysqli_connect('xxxxxx', 'xxxx', '', 'xxxx');
$rooms = mysqli_query($db, "SELECT * FROM rooms ORDER BY id ASC;");
<script src = "http://code.jquery.com/jquery-1.9.1.js"></script>
<?php while($row = mysqli_fetch_array($rooms)) { ?>
<div>
<form >
<img src="upload/<?php echo $row['image']; ?>" style="width: 20%;">
<label>Check IN</label>
<input type="date" name="text_checkin" id="text_checkin">
<br>
<label>Check OUT</label>
<input type="date" name="text_checkout" id="text_checkout">
<br>
<label>Room ID</label>
<input type="text" name="text_roomid" id="text_roomid" value="<?php echo $row['id']; ?>">
<br>
<input type="submit" value="submit" name="submit" id="submit" onclick="return chk()">
<br><br><br>
</form>
<p id="msg"></p>
</div>
<?php } ?>
I have table named reservation then the columns are room_id, checkin, checkout.
the 3 data's in my room_table will display. Then the textbox, and the button will be thrice cause of the while loop. Then imagine I clicked the button submit in the 2nd row, then the 2nd row id should insert on my table reservation but the problem is only first row id is inserting on table reservation
Here's my script:
<script type="text/javascript">
function chk()
{
var roomid = document.getElementById('text_roomid').value;
var checkin = document.getElementById('text_checkin').value;
var checkout = document.getElementById('text_checkout').value;
var dataString = 'roomid='+ roomid + '&checkin=' + checkin + '&checkout=' + checkout;
$.ajax({
type: "post",
url: "server.php",
data:dataString,
cache:false,
success: function(html){
$('#msg').html("success");
}
});
return false;
}
</script>
PHP code: server.php
$roomid = $_POST['roomid'];
$checkin = $_POST['checkin'];
$checkout = $_POST['checkout'];
$query = "INSERT INTO reservation (room_id, checkin, checkout) values ('$roomid', '$checkin', '$checkout')";
mysqli_query($db, $query);
echo "success!";
please help me out of this problem, tyia!
The error lies within your while loop. Your printed elements will all have the same id's. When your function is looking for an id to get the value, it will always return the first that it finds, no matter how many instances there are of that id. So you're having conflicting id's. id's should always be unique.
What you could do to avoid this, is to declare a counter outside your while loop and increment it inside your while loop, then attach that onto your id. In that way, you will always have a unique id to parse along.
For instance:
<?php $count=0; while($row = mysqli_fetch_array($rooms)) { $count++;?>
<div>
<form >
<img src="upload/<?php echo $row['image']; ?>" style="width: 20%;">
<label>Check IN</label>
<input type="date" name="text_checkin" id="text_checkin<?php echo $count; ?>">
<br>
<label>Check OUT</label>
<input type="date" name="text_checkout" id="text_checkout<?php echo $count; ?>">
<br>
<label>Room ID</label>
<input type="text" name="text_roomid" id="text_roomid<?php echo $count; ?>" value="<?php echo $row['id']; ?>">
<br>
<input type="submit" value="submit" name="submit" id="submit" onclick="return chk()">
<br><br><br>
</form>
<p id="msg<?php echo $count; ?>"></p>
</div>
<?php } ?>
However, you will then need to change your logic for how you fetch the data from each element, as you don't really know what their id's could end up being due to the incrementor. It's not static.
If you need any further help, let me know.
As Martin said there is the problem with the id's so you have to change the logic a little bit.
$db = mysqli_connect('xxxxxx', 'xxxx', '', 'xxxx');
$rooms = mysqli_query($db, "SELECT * FROM rooms ORDER BY id ASC;");
<script src = "http://code.jquery.com/jquery-1.9.1.js"></script>
<?php while($row = mysqli_fetch_array($rooms)) { ?>
<div>
<form >
<img src="upload/<?php echo $row['image']; ?>" style="width: 20%;">
<label>Check IN</label>
<input type="date" name="text_checkin" class="text_checkin">
<br>
<label>Check OUT</label>
<input type="date" name="text_checkout" class="text_checkout">
<br>
<label>Room ID</label>
<input type="text" name="text_roomid" class="text_roomid" value="<?php echo $row['id']; ?>">
<br>
<input type="submit" value="submit" name="submit" id="submit" onclick="return chk()">
<br><br><br>
</form>
<p id="msg"></p>
</div>
<?php } ?>
Then you can get the values individually and pass them as array to the server.
<script type="text/javascript">
function chk()
{
var roomidArr = $(".text_roomid");
var checkinArr = $(".text_checkin");
var checkoutArr = $(".text_checkout");
/*
You can get value of each element as;
for(var i = 0; i < roomidArr.length; i++){
console.log($(roomidArr[i]).val());
}
*/
//var dataString = Apply your logic here as;
$.ajax({
type: "post",
url: "server.php",
data:dataString,
cache:false,
success: function(html){
$('#msg').html("success");
}
});
return false;
}
</script>

Populate textbox from sql based on other txtboxes values in form

I am doing a registration page where the one input textbox should be populated based on 2 other input textboxes.
tblEntries
Id; firstname; lastname; age; gender; categories
tblCategories
Id; categories; age_from; age_to, gender
Data inserted: 1; Veteran_male; 20; 30; male
frmEntries.php is populated with tblEntries data onload already using localstorage.
(may look like this
Firstname=Peter
Lastname=Trump
Age=25
Gender=male
Categories= ?(from sql)
include("conn.php");
include("categories.php");
<input id="firstname" type="text" name="firstname" value="" />
<input id="lastname" type="text" name="lastname" value="" />
<input id="age" type="text" name="age" value="" />
<input id="gender" type="text" name="gender" value="" />
<input id="categories" type="text" name="categories" value="<?php echo $output; ?>" />
(the 25 fall in between 20 and 30 in the tblCategories and the gender is shown in both tables)
categories.php
<php?
include ('conn.php');
$gender = $_POST["gender"];
$age = $_POST["age"];
$result = $con->query("SELECT categories FROM tblCategories WHERE '$age' BETWEEN age_from AND age_to AND gender='$gender'”);
$result = mysqli_query($con, $query);
$output = '';
while($row = mysqli_fetch_array($result))
{
$output = $row["categories"];
}
echo($output);- //(to be populated inside the frmEntries and the
“categories” field onload)
}
?>
Should i use Ajax with a button?
<script>
$('#updateBtn').click(function(e){
//to disable the click from going to next page
e.preventDefault();
$.ajax(
'categories.php', function(data){
$('#categories').val(data);
}
);
});
</script>
Please advise on how to do this. Should I rather use a button to populate "categories" after onload? I get variable not find errors

Show values in the textboxes

I have a table callled tb_app with fields 'id','name','aic','batchcode'
example: field values '1','james','0001','1'
If type james in the textbox(name) corresponding values for other fields(aic,batchcode) should be displayed in textboxes. Is this possible? can anyone help me...I'm a php beginner ...Please!
Form code:
<form method="post">
<input type="text" name="names" id="query" />
<input type="text" name="aic" />
<input type="text" name="batchcode" />
<input type="submit" name="show" />
</form>
You can do this by Jquery ajax Try in this way by using your exact field names it might help you
Your jquery script should be something like this
function getvalues()
{
var selname = $("input[name='names']:text"").val();
$.ajax({ url: "getuserdata.php",
data: {"selname":selname},
type: 'post',
success: function(output) {
$("#aic").val(output);
$("#batchcode").val(output);
}
});
}
and your Html code
<input type="text" name="names" id="query" onblur="getvalues()"/>
<input type="text" name="aic" id="aic"/>
<input type="text" name="batchcode" id="batchcode" />
The getuserdata.php
<?php
include("database connection file here");
$selname = $_POST['selname'];
$query = "SELECT * FROM table_name WHERE youruser_id = $selname";
$res = mysql_query($query);
$rows = mysql_fetch_array($res);
echo $rows['aic'];
echo $rows['batchcode'];
?>

Load JSON data through jQuery and PHP

I am trying to send a textbox value (invoice number) to a PHP file through jQuery and AJAX. From the PHP file, I am returning the JSON encoded data. I want to display the values fetched from the database in the following textboxes (Total Amount, Balance Amount) and select boxes (Payment mode, Payment status).
I am not getting the output I wish. Where am I going wrong?
HTML:
<form name="inv_payment" method="post" action="" style="margin:0px;width:400px;">
<fieldset>
<legend>Payment details</legend>
<label for=inv_num>Invoice Number</label>
<input id=inv_num name=inv_num type=number placeholder="12345" required autofocus >
<input type=button name="get_details" id="get_details" value="Get Details" >
<label for=tot_amt>Total Amount</label>
<input id=tot_amt name=tot_amt type=text placeholder="12345" disabled > <br/>
<label for=pay_up>Pay Up </label>
<input id=pay_up name=pay_up type=text placeholder="12345" required ><br/>
<label for=bal_amt>Balance Amount </label>
<input id=bal_amt name=bal_amt type=text placeholder="12345" disabled > <br/>
<label id="paymt_mode"><strong>Payment Mode</strong></label>
<select name="pay_mode" style="width: 130px">
<option selected="selected">Cash</option>
<option>Cheque</option>
</select><br/>
<label id="paymt_status"><strong>Payment Status</strong> </label>
<select name="pay_status" style="width: 130px">
<option selected="selected">Pending</option>
<option>Completed</option>
</select><br/>
<input type="submit" value="Payment" name="pay_btn">
</fieldset>
</form>
jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#get_details').click(function() {
//To pass the invoice number and fetch related details
$.getJSON("get_invpay_details.php", {id: $('#inv_num').val()}, function(data){
$('#tot_amt').val(data['Total_Amount']);
$('#bal_amt').val(data['Balance_Amount']);
$('#pay_mode').val(data['Payment_Type']);
$('#pay_status').val(data['Payment_Status']);
});
});
</script>
PHP:
<?php
include('includes/dbfunctions.php');
include('includes/db.php');
if(isset($_GET['id']))
{
$tmp = $_GET['id'];
$sql = mysql_query("select Total_Amount,Balance_Amount,Payment_Type,Payment_Status from invoice where InvoiceNum='$tmp'");
if(mysql_num_rows($sql))
{
$data = mysql_fetch_array($sql);
echo json_encode($data);
}
}
?>
Your json response value populate with object.data like this.
$('#tot_amt').val(data.Total_Amount);
$('#bal_amt').val(data.Balance_Amount);
$('#pay_mode').val(data.Payment_Type);
$('#pay_status').val(data.Payment_Status);
Here data is an object not a array.
I have checked my query.It gave me the correct output in mysql editor.
what i could see is.. you have a typo in your question...
missing }); for document.ready..which might be breaking your script..(this should have error in your console though..)..anyways something to check about..
$(document).ready(function() {
$('#get_details').click(function() {
//To pass the invoice number and fetch related details
$.getJSON("get_invpay_details.php", {id: $('#inv_num').val()}, function(data){
$('#tot_amt').val(data['Total_Amount']);
$('#bal_amt').val(data['Balance_Amount']);
$('#pay_mode').val(data['Payment_Type']);
$('#pay_status').val(data['Payment_Status']);
});
});
});
//^^--here

jQuery: find id of of a form field

I am creating a dynamic form where the user will have the ability to add a set of inputs to the form. The html looks like this:
<form>
<input id="title1" class="title" name="title1" type="text" value="">
<input id="productionCompany1" name="productionCompany1" type="text" value="">
<input id="year1" name="year1" type="text" value="">
<input id="role1" name="role1" type="text" value="">
<div id="newCredit"> </div>
add another credit
</form>
When the user clicks the link with the id of "addCredit" the following jQuery script is called:
$(document).ready(function() {
var $ac = $('#addCredit');
$ac.click(function() {
/* the following two lines are where the problem lies? */
var $credInt = $(this).prev(".title");
$.get("addCredit.php", {num: $credInt},
function(data){
$('#newCredit').append(data);});
return false;
});
});
The jQuery function queries a php file called "addCredit.php", which looks like this:
<?php
$int = $_GET["num"];
$int = substr($int, -1);
$int++;
?>
<input id="title<?php echo $int;?>" class="title" name="title<?php echo $int;?>" type="text" value="">
<input id="productionCompany<?php echo $int;?>" name="productionCompany<?php echo $int;?>" type="text" value="">
<input id="year<?php echo $int;?>" name="year<?php echo $int;?>" type="text" value="">
<input id="role<?php echo $int;?>" name="role<?php echo $int;?>" type="text" value="">
My problem is getting the javascript variable $credInt set properly so that it can be sent to the addCredit.php page and update the form fields accordingly. I also need to be sure that every time the form is appended, the next value sent is the incremented value.
Any thoughts on how I might accomplish this? Thank you for your help.
This is the wrong way of doing it; PHP can handle array syntax in a variable name. This makes it much easier to handle. It is also unnecessary to call the server to clone the form. You should name your fields like this:
<form>
<div id="originalCredit">
<input name="title[]" type="text" value="">
<input name="productionCompany[]" type="text" value="">
<input name="year[]" type="text" value="">
<input name="role[]" type="text" value="">
</div>
add another credit
</form>
And then your Javascript can be like this:
$(function() {
$('#addCredit').click(function() {
var newCredit = $('#originalCredit').clone(); // create new set
newCredit.find('input').val(''); // empty input fields
$(this).before(newCredit); // append at the end
return false;
});
});
When the form is finally sent to the server, because the variables are in the format of name[] PHP will recognize they are an array and then you can do this:
<? foreach($_POST['title'] as $k => $v) { ?>
Title: <?=$_POST['title'][$k]?><br>
Company: <?=$_POST['productionCompany'][$k]?><br>
Year: <?=$_POST['year'][$k]?><br>
Role: <?=$_POST['role'][$k]?><br>
<? } ?>
Obviously this is just displaying it as an example, but you can then save/update/whatever with it.

Categories