I have been trying solve this for a while. I am new to php. Please help me to solve this.
I have form in which we can add more input fields whose values are added into an array 'array_names'. The php code i used adds values of added input filds into different 'id' in database. But I want add all input field values into single 'id' so than all values comes in single database table row. Please tell me how to do that.
Thanks in advance!
//form
<form action="" method="POST">
<div class="form-group">
<label for="PlanTitle"> <span class="FieldInfo"> Plan Title: </span></label>
<input class="form-control" type="text" name="PlanTitle" id="PlanTitle" placeholder="Type here" value="">
</div>
<div class="form-group">
<label for="SubTitle"> <span class="FieldInfo"> Plan Sub Title: </span></label>
<input class="form-control" type="text" name="SubTitle" id="SubTitle" placeholder="Type here" value="">
</div>
<div class="form-group">
<label for="SectionContent"> <span class="FieldInfo"> Features List </span></label>
<div class="input_fields_wrap">
<button class="add_field_button">Add More</button>
<input type="text" name="items[name][]">
</div>
</div>
<button type="submit" name="submit" class="inner">Submit</button>
</form>
//script
<script type="text/javascript">
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 1;
$(add_button).click(function(e)
{
e.preventDefault();
if(x < max_fields)
{
x++; //text box increment
$(wrapper).append('<input type="text" name="items[name][]">');
}
});
});
</script>
//php code
if(isset($_POST["Submit"])){
$Id = $_SESSION["id"];
$PlanTitle = $_POST["PlanTitle"];
$SubTitle = $_POST["SubTitle"];
$items = (isset($_POST['items']) && is_array($_POST['items'])) ? $_POST['items'] : array();
$array_names = $items['name'];
global $ConnectingDB;
foreach ($array_names as $name) {
$sql = "INSERT INTO plan(title,subtitle,items);
$sql .= "VALUES(:planTitle,:SubTitle,:Items);
$stmt = $ConnectingDB->prepare($sql);
$stmt->bindValue(':planTitle',$PlanTitle);
$stmt->bindValue(':subTitle',$SubTitle);
$stmt->bindValue(':name', $name);
$Execute=$stmt->execute();
}
Plan Table
Current Output
id
title
subtitle
items
1
title1
subtitle1
item1
2
title1
subtitle1
item2
3
title1
subtitle1
item3
Expected Output
id
title
subtitle
items
1
title1
subtitle1
item1,item2,itme2
As a general rule, if you ever find yourself trying to save an array in a db column, you are probably better off creating a new table for that array, where each element of the array gets its own record, and become friendly with INNER JOIN. A quick search will turn up numerous tutorials and examples on INNER JOIN, including many on this site.
If you absolutely must save the array into a column of a record, do what those leaving comments suggest.
Related
so i have a record that has a one-to-many relationship with another named outcome which each has atleast one person to make a team.
For the team, i am dynamically creating the fields to a maximum of 9 people in each. not to confuse which outcome each person in the team belongs to, i am passing the outcome id.
HTML
<button type="button" class="btn add_field_button">
<i class="fa fa-plus" aria-hidden="true"></i>Add More Fields
</button>
JAVASCRIPT
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var new_fields = 19;
var i = $("")
var x = 1; //initial text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
new_fields++;
$(wrapper).append('<div class="row"><input type="text" name="outcome[' +new_fields +'][' +x +'][id]" value="<?php echo $outcome->id; ?>" class="form-control" hidden><div class="form-group col-lg-4"><label class="form-control-label text-muted ">*Officer\'s Name:</label><input type="text" name="outcome[' +new_fields +'][' +x +'][officer]" class="form-control" required></div><div class="col-lg-4 form-group-sub"><label class="form-control-label text-muted">*Position:</label><input type="text" name="outcome[' +new_fields +'][' +x +'][position]" class="form-control" required></div><div class="col-lg-3 form-group-sub"><label class="form-control-label text-muted">*Institution Name:</label><select class="form-control" id="institution" name="outcome[' +new_fields +'][' +x +'][institution]" required><option value="">Select Institution</option><option value="option1">First Option</option><option value="option2">Second Option</option><option value="other">Other</option></select></div><i class="fa fa-times" aria-hidden="true"></i></div>');
//add input box
}
});
I have tried double curly brackets for the variables but it isn't working.
SAMPLE OUTPUT
{"2":{"id":"<?php echo $outcome->id; ?>","officer":"Munthu Oyamba","position":"Ofunika heve","institution":"option1"}},"21":{"3":{"id":"<?php echo $outcome->id; ?>","officer":"Munthu Wachiwiri","position":"Bwantasa","institution":"option2"}}}
If you have the javascript in your Blade template, this should work as it is injecting the string (value of my_var) in to the JS block:
$my_var = 'hi mom!';
<script>
console.log( {{ $my_var }} );
</script>
If your php variable has markup to be rendered you can use {!! $my_var !!}
https://laravel.com/docs/7.x/blade#blade-and-javascript-frameworks
Javascript code is executed in your browser. Your browser does not know how to execute php code.
The php code needs to be executed server side, which means before the page is even sent to your browser. Dynamically adding <?php ?> tags to your page does nothing.
I am writing a code for billing, here inside it rather to enter every entry by typing i wanted to do something like if record already exist then, enter one field other corresponding fields will automatically be filled with corresponding data. For eg: inside my form there is a section to display customer info and that is done by entering customer_id then a PHP file fetches name address phone number and other data corresponding to the entered customer_id and auto fill other customer fields of form.
HTML form
<form action="./manipulate/invoice.php" method="post" accept-charset="UTF-8">
<div style="width:15%;float:left">
Customer #
<br>
<input id="searchbox" style="width:98%;margin-left:1%;margin:right:1%" name="cust_id" type="text" placeholder="Customer ID">
</div>
<div class="w3-container">
<div style="width:100%;">
<h4>Contact Info About Customer</h4>
</div>
<div style="width:30%;float:left" >
<input id="cust_address" style="width:98%;margin-left:1%;margin:right:1%" type="text" placeholder="Customer_Address" >
</div>
<div style="width:15%;float:left">
<input style="width:98%;margin-left:1%;margin:right:1%" type="text" placeholder="City" id="cust_city">
</div>
<div style="width:15%;float:left">
<input style="width:98%;margin-left:1%;margin:right:1%" type="text" placeholder="State" id="cust_state">
</div>
<div style="width:15%;float:left">
<input style="width:98%;margin-left:1%;margin:right:1%" type="number" placeholder="Pincode" id="cust_pincode">
</div>
<div style="width:25%;float:left">
<input style="width:98%;margin-left:1%;margin:right:1%" type="number" placeholder="Phone Number" id="cust_phone">
</div>
</div>
</form>
Javascript function:
<script>
$(document).ready(function () {
function trial(s){
$('#searchbox').val(s);
$.ajax({
url:'./manipulate/get_addre.php',
type:'POST',
data:'cust_id='+s,
dataType:'json',
success:function(e){
//$('#cust_add').append(e['address']);
$('#cust_Address').val(e['address']);
$('#cust_city').val(e['city']);
$('#cust_state').val(e['state']);
$('#cust_pincode').val(e['pincode']);
$('#cust_phone').val(e['phone']);
$('#cust_Name').val(e['name']);
}
});
}
});
$('#searchbox').change(function() {
trail($(this).val());
});
</script>
get_addre.php is
<?php
$mysqli = new mysqli("localhost","root","","tssolutions");
if($mysqli->connect_errno){
echo "connection failed : $mysqli->connect_errno";
exit();
}
$cust_id = $_POST['cust_name'];
$query = "SELECT * FROM customer WHERE customerid = '".$cust_id."' ";
//echo 'hi';
if($result = $mysqli->query($query)){
/* fetch details*/
while($row = $result->fetch_assoc()){
$json = json_encode($row);
//return $json;
echo $json;
//echo "<b>Address : </b>".$row['address'].", ".$row['city'].", ".$row['state'].", ".$row['pincode'].", contact no. ".$row['phone'];
}
$result->free();
}
$mysqli->close();
?>
And in invoice.php these fields + some more fields are being inserted into another table in database.
The problem i am facing is whenever i enter into customer_id field in form rest all fields remains blank which were supposed to auto fill..
Anyone can correct it ? Thanks in advance.
The first thing i have to say is: Your code is vulnerable to SQL Injection. You should change this line:
$cust_id = $_POST['cust_name'];
to this line:
$cust_id = $mysqli->real_escape_string($_POST['cust_name']);
On the first glance i do not see any error, but oddly there is no event handler, that will acutally call your JavaScript trial function. It seems like you are missing this part of the code:
$('#searchbox').change(function() {
trial($(this).val());
});
Edit
After rebuilding your application i have found your error. You are sending data with the name 'cust_id' but you are requesting data with the name 'cust_name'. Once you change your names to the correct one, this will work.
You can use the web developer consoles (F12 in Chrome and Firefox) to have a look at the server response to your ajax calls in the newtwork tab.
I have a form. On this form I when I add line items I save the input value then prepend it to the form. This part works. Keep in mind the form is not being submitted I am just adding to the dom dynamically
In the part of the form I save there is a price input. I am using jquerypriceformat plugin to format the price into price format. For example 111 becomes $1.11. If I do not use the plugin it works. The plugin does work as intended. I think my problem is that after I type the value is being changed and I need to retain that value somehow.
Here is a fiddle
https://jsfiddle.net/ks2z5mdo/7/
I think the fiddle will better show what the problem is. Basically when you type a description type a quantity and price, the price gets formatted then hit the add button all the data is saved except the price.
How can I solve this?
So first is the form
<div class="form-row">
<strong>Line Items:</strong>
<br>
<div class="line-items">
<div class="line-item">
<div class="line-item-box description">
<label>Description:</label>
<textarea name="description" id="description"></textarea>
</div><!--
--><div class="line-item-box quantity">
<label>Quantity:</label>
<input type="text" name="quantity" id="quantity">
</div><!--
--><div class="line-item-box price">
<label>Price:</label>
<input type="text" name="price" id="price">
</div>
<button class="btn add-item">Add Item</button>
</div>
</div>
</div>
Then is the jquery
$(document).ready(function() {
$('#price').priceFormat();
$('.add-item').click(function() {
if ($('description, #quantity, #price').filter(function() { return $(this).val(); }).length > 0) {
var description = $('#description').val();
var quantity = $('#quantity').val();
var price = $('#price').val();
$('.line-items').prepend('<div class="line-item"><div class="line-item-box description">' + description + '</div><div class="line-item-box quantity">' + quantity + '</div><div class="line-item-box price">' + price*quantity + '</div><button class="btn remove-btn">Remove</button></div>');
return false;
} else {
alert('Line item empty');
}
});
$(document).on('click', '.remove-btn', function() {
$('.line-item').remove();
});
});
Your var price = $('#price').val(); adds a $ and a space in front of the actual value that you are trying to get. Therefore, one solution is to get the substring of this value to remove the $:
var price = $('#price').val().substring(2);
This will leave the value as a number rather than the string it was originally made to be. Here is a fiddle that works.
I have small project of PHP and JavaScript, which used to registering students on the MySql database and it does perfectly, but I need when user search/type certain name on it, example if he/she type name like "John" it has to show drop down of names which are relate with letter "J", I tried but it doesn't work. I will show you step by step What I did.
1: This is html form which user use to enter students Marks, on field name is where I want when user type name on text box, it has to show related names:
Note: I will show you few fields.
<form action="#" method="POST" id="name" name="name"
enctype="multipart/form-
data">
<div class="row">
<div class="col-sm-6">
<div class="panel panel-default">
<div class="panel-body">
<div class="form_sep">
<label for="reg_input_name" class="req">Admition Number</label>
<input type="text" id="idnum" name="idnum" class="form-control"
data-required="true" >
</div>
<div class="form_sep">
<label for="reg_textarea_message" class="req">Name</label>
<input type="text" name="name" id="name" cols="30" rows="4"
class="form-control"></div>
</div>
</div>
</div></div></form>
2:This is JavaScript codes and jQuery plugin which I place down on the same html form.
<script src="../jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.get('getStudents.php', function(data){
var students = JSON.parse(data);
$('#name').autocomplete({
source: students
});
});
});
</script>
3: This is PHP (getStudents.php) file.
<?php
include_once "db_connect.php";
$sql = "SELECT * FROM student_reg";
$res = mysql_query($sql);
if($res){
$students = array();
while($r = mysql_fetch_array($res)){
$students[] = $r['sname'];
}
echo json_encode($students);
}else{
echo mysql_error();
}
?>
Note: when I test/ echo on the php file its self it show all names, but when I place cursor on "name" text field and type it doesn't show drop down suggested names as I prefer.
Just an idea, but I would suggest you check out Datatables (https://www.datatables.net/). It might have some very useful applications for your app. The search functions do pretty near what you wish I think. Here's a very basic example with the searching functions available.(https://www.datatables.net/examples/basic_init/zero_configuration.html).
I want to autogenerate a number of labels on the bottom of my page based on what someone fills in in an inputfield.
So when someone fills in "2", I want 2 labels to pop up, preferable when he typed it without leaving the inputfield or anything.
This is what I have:
HTML
<div class="form-group">
<label class="control-label" for="if_aantalMensen">
Hoeveel extra mensen wil je inschrijven?
</label>
<div>
<input type="text" class="form-control" id="if_aantalMensen" name="if_aantalMensen"
data-bind="textInput: aantalMensen">
</div>
</div>
<div data-bind="foreach: aantalMensenArray" class="form-group">
<label><span data-bind="text: $index"></span></label>
</div>
Javascript
var vm = {
aantalMensen: ko.observable(0),
aantalMensenArray: ko.computed(function() {
var fields = [];
for (var i = 0; i < self.selectedNumberOfFields(); i++) {
fields.push(new Parameter());
}
return fields;
})}
It works if I just make "aantalMensenArray" into an observableArray that already has values in it. However, I can't get it to change the amount of labels shown.
Use valueUpdate:'afterkeydown'
"http://jsfiddle.net/dpa6zk9j/"