Insert multiple selected checkbox value in database using php and angularjs - javascript

I have an html form with checkbox, textbox and radio buttons. When the save button is clicked the form data is to be inserted into to database. I am using an angularjs controller to get the form data and PHP to insert into mysql.
Question: How do I insert selected checkbox value in controller and PHP? Explain to me with code examples.
Below is my code:
html code :
<form class=rform align="center">
<b>Product Name:<input type="text" name="name" ng-model="newProduct.name" required=""/><br>
Product Category: <select name="catg" ng-model="newProduct.catg" ng-options="x for x in catg" ></select><br>
TAGS : <br>
<ul>
<li ng-repeat="tag in tags">
<input type="checkbox" name="tags" ng-model="newProduct.tags" value="tag" ng-true-value="tag"> {{tag}}
</li>
</ul>
<Status :<br><br>
<input type="radio" ng-model="newProduct.stat" value="Active">Active
<input type="radio" ng-model="newProduct.stat" value="Deactive">Deactive<br><br>
<input type="hidden" ng-model="newProduct.id" /></b>
<div class="btn"> <button type="submit" ng-disabled="rform.$invalid" ng-click="saveRecord(newProduct)">Save</button></div>
</form>
app.js
app.controller('ProductCtrl',function($scope,$http){
$scope.tags = ["Appliances","Electronics","Men&Women","Others"] ;
$scope.catg = ["mobile","Air Conditioner","Kitchen appliances","Footwear","SportsWear","clothes",
"watches","Lptops","Televisions","Camera","Furniture","Kitchen Dining","Music","Stationery"];
$scope.saveRecord = function (newProduct) {
$http.post("php/pinsert.php",{
'name' : $scope.newProduct.name,
'catg' : $scope.newProduct.catg,
'tags' : $scope.newProduct.tags,
'stat' : $scope.newProduct.stat
})
// data:$scope.products,
.success(function(data){
alert(data);
})
angular.forEach($scope.tags, function(tag){
if (tag.selected) $scope.albumNameArray.push(tag.name);
tag.selected= false ;
});
tag.selected= false ;
}
$http.get("php/pselect.php").then(function (response) {
$scope.myproducts = response.data.records;
});
});
PHP :
<?php
$connect = mysqli_connect("localhost", "root", "","user");
$data = json_decode(file_get_contents("php://input"));
$p_name = mysqli_real_escape_string($connect, $data->name);
$p_catg = mysqli_real_escape_string($connect, $data->catg);
$tags = mysqli_real_escape_string($connect, $data->tags);
$status = mysqli_real_escape_string($connect, $data->stat);
$query = "INSERT INTO products(pname,pcatg,tag,status) VALUES ('$p_name','$p_catg','$tags','$status')";
$result = mysqli_query($connect, $query) ;
if($result == TRUE)
{
echo "Data Inserted...";
}
else
{
echo 'Error';
}
?>

I would restructure your tags array likewise. The selected property will be set to true if the checkbox is selected. The name is simply for display.
$scope.tags = [
{"selected":false, "name":"Appliances"},
{"selected": false, "name":"Electronics"},
{"selected":false, "name":"Men&Women"},
{"selected":false, "name":"Others"}
];
The markup for the checkboxes should also be restructured. Notice the ng-model is using the .selected property of $scope.newProduct.tags. This will set allow you to see which tags properties are selected when saving to the DB.
<li ng-repeat="tag.name for tag in tags">
<input type="checkbox" name="tags" ng-model="tag.selected" value="tag" ng-true-value="tag"> {{tag.name}}
</li>
When assigning newProduct to scope it is not necessary to pass it as a parameter in $scope.saveRecord(). You can also pass the entire object in the post body. The ajax call is written without the shorthand $http.post either way is fine but I find this easier to read.
$scope.saveRecord = function(){
$http({
url: "php/pinsert.php",
method: "POST",
data: $scope.newProduct
}).success(function(data){
// process returned data
});
}
On the backend the data will be structured the same your the $scope.newProduct object was structured. You will need to:
Loop through this data
Find the selected tags
Save the checked (selected.true) tag values into the table
I don't know the exact structure of your products table but the 3 steps above are a guide for saving complex data into the DB.
$connect = mysqli_connect("localhost", "root", "","user");
$data = json_decode(file_get_contents("php://input"));
foreach($data['tags'] as $tag){
// Save only selected tags to products table
if($tag->selected){
$query = "
INSERT INTO products(tag)
VALUES('$p_name','$p_catg','$tags','$status')
";
$result = mysqli_query($connect, $query);
}
}
Hopefully this gets your started, cheers!

Related

parameter is missing in php jquery ajax

Sorry for disturbing again with my very basic question. First of all, sorry if my English is a little bit hard to understand. My current situation is I want to do a popup modal in my drag and drop boxes. In my popup modal, I can view and edit the details of the user based on what we click in the button in the box. The problem is, I cannot SELECT the data by id. But, when I SELECT all the data, the data appear in the modal boxes. But, it appears all the data. I just want the selected id. Back to my question for past few days, I've redo again to get more understanding on this popup modal part. I've done ajax and a little bit JavaScript, also, I tried to debug my code just what I've been told but I got an error saying "Parameter is missing" . What is causing by that ? I've done some reading about parameter but I still don't get the actual understanding about it. Can someone give an idea what is actually parameter is missing . And what I suppose to do by it?
Here what I've tried so far.
This is the button
<button data-id="<?php echo $row['userid'];?>" data-target="doubleClick-1" class='jobinfo' type='button' id='btnInfo' ondblclick="document.getElementById('doubleClick-1').style.display='block'">Info</button>
This is the modal popup
<div id="doubleClick-1" class="modal">
<label class="tabHeading">User Info</label>
<div class="contentTechJobInfo">
<div class="tech-details">
<div class="techClose" onclick="document.getElementById('doubleClick-1').style.display='none'" >&times</div>
</div>
</div>
</div>
</div>
<script type='text/javascript'>
$(document).ready(function() {
$('.jobinfo').click(function() {
var userid = $(this).data('userid');
// AJAX request
$.ajax({
url: 'ajaxhome.php',
type: 'post',
data: {userid: userid},
success: function(response) {
// Add response in Modal body
$('.tech-details').html(response);
// Display Modal
$('#doubleClick-1').modal('show');
}
});
});
});
</script>
This my ajaxhome.php
<?php
$connection = mysqli_connect("", "", "");
$db = mysqli_select_db($connection, '');
if (!isset($_GET['userid'])) {
die("Parameter is missing!");
}
$userid = intval($_GET['userid']);
$query = "SELECT * FROM user WHERE userid ='$userid'";
$query_run = mysqli_query($connection, $query);
if ($query_run) {
while ($row = mysqli_fetch_array($query_run)) {
?>
<div class="input-box">
<label for="">Name</label>
<input type="text" id="username" name="username" value="<?php echo $row['username']?>">
</div>
<div class="input-box">
<label for="">Number</label>
<input type="text" id="usernumber" name="usernumber" value="<?php echo $row['usernumber']?>">
</div>
<div class="input-box">
<label for="">Class</label>
<input type="text" id="userclass" name="userclass" value="<?php echo $row['userclass']?>">
</div>
<button type="submit" id="submit" name="update" class="btn btn-primary"> Update Data </button>
<?php
if (isset($_POST['update'])) {
$username = $_POST['username'];
$usernumber = $_POST['usernumber'];
$userclass = $_POST['userclass'];
$query = "UPDATE user SET username='$username', usernumber='$usernumber', userclass='$userclass' WHERE userid='$userid'";
$query_run = mysqli_query($connection, $query);
if ($query_run) {
echo '<script> alert("Data Updated"); </script>';
header("location:homepage.php");
} else {
echo '<script> alert("Data Not Updated"); </script>';
}
}
} ?>
<?php
}
?>
In short, I think the problem comes from these lines of code in your modal:
var userid = $(this).data('userid');
you should replace it with
var userid = $(this).data('id'); // you should pass 'id' to .data() function instead of 'userid'
With your current code userid variable in your modal will always be undefined. It means it wont exist in $_GET when you send ajax request to PHP. And it causes your ajaxhome.php moves to die("Parameter is missing!");.
To get data-xxx attribute with jQuery, you should use pass 'xxx' to .data() function.
var xxx = $(this).data('xxx');
In your button, you are storing userid in data-id attribute
<button data-id="<?php echo $row['userid'];?>"
so if you need to get that userid you should pass 'id' into .data() function
Update:
In your ajax, you are using type: 'post', so in your php code you should check $_POST instead of $_GET
I don't think the value of user has been obtained
var userid = $(this).data('userid');
you can try
var userid = $(this).data('id');

Ajax data - for each data

I have a problem with my ajax code... I have a list of checkbox, the idea is insert the data of the marked checkboxes into the database.
If I select only one check box, the insert is correct. But if I select for example 3, all data appears on the same field, as unique value.
This is the example:
HTML
<input type="checkbox" class="get_value" value="test1">test1</br>
<input type="checkbox" class="get_value" value="test2">test2</br>
<input type="checkbox" class="get_value" value="test3">test3</br>
<input type="checkbox" class="get_value" value="test4">test4</br>
<input type="checkbox" class="get_value" value="test5">test5</br>
<button type='button' name='submit' id="submit">Submit</button>
This is the ajax code
<script>
$(document).ready(function(){
$('#submit').click(function(){
var insert = [];
$('.get_value').each(function(){
if($(this).is(":checked")){
insert.push($(this).val());
}
});
insert = insert.toString();
$.ajax({
url: "./functions/add_list.php",
method: "POST",
data:{insert:insert},
}
});
});
});
</script>
And this one the PHP that do the insert into the database:
if(isset($_POST["insert"])){
$query = 'INSERT INTO music (name,username) VALUES ("'.$_POST["insert"].'","'.$username.'")';
$result = mysqli_query($conn, $query);
}
For example if I check "test1" and "test2", I will see in my MySQL "name" field "test1,test2". But I need see them in diferent fields, not in the same.
I have tested the "foreach ($_POST["insert"] as $value) { insert... } but it did not help me.
Someone have an idea about my error?
I appreciate your help so much.
Regards,
you need to loop on the server side too :
$arr = explode(',', $_POST["insert"]);
foreach ($arr as $val) {
$query = 'INSERT INTO music (name,username) VALUES ("'.$val.'","'.$username.'")';
$result = mysqli_query($conn, $query);
}

How can I interact with a javascript variable using PHP?

I have a really simple web app which allows a user to enter a first and last name and hit submit to insert the name into a sql database.
Below the form, there is a HTML table displaying the contents of the database table.
If a user clicks on any row of the database, the ID of the HTML element (which is set to the same value of the database ID) is saved to a javascript variable using the following function.
<!--JS Functions-->
<script>
//Determine which record is selected.
var id;
function TableSelect(el) {
id = el.id;
alert(id);
}
</script>
Here is the form:
<!--HTML Form -->
<form method="post" action="index.php">
First Name: <input type="text" name="FirstName" value="">
<br><br>
Last Name: <input type="text" name="LastName" value="<?php echo $LastName;?>">
<br><br>
<input type="submit" name="submit" value="Submit">
<input type="submit" name="delete" value="Delete" onclick="Delete()">
</form>
Here is the PHP processing of the data and the output of the SQL table:
//prepare query to insert data from form into DB
if (isset($_POST['submit'])){
$query = "INSERT INTO tbl_HR_Master (First_Name, Last_Name) VALUES ('{$FirstName}', '{$LastName}') ";
$result = mysqli_query($connection, $query);
//Test if there was a query error
querycheck($result);
}//end if
//prepare query to populate table from DB
$query2 = "Select id, First_Name as 'First Name', Last_Name as 'Last Name' from tbl_HR_Master";
$result2 = mysqli_query($connection, $query2);
//Test if there was a query error
querycheck($result2);
//display table
echo "</br>";
echo "<table id=\"tbl_HR_Master\" border='1'><tr class=\"nohover\"\">";
// printing table headers
$fields_num = mysqli_num_fields($result2);
for($i=0; $i<$fields_num; $i++) {
$field = mysqli_fetch_field($result2);
echo "<td>{$field->name}</td>";
} //end for
echo "</tr>\n";
// print table rows
while($row = mysqli_fetch_row($result2))
{
echo "<tr>";
$id = $row[0];
foreach($row as $cell){
echo "<td onclick=TableSelect(this) id=". $id .">".$cell."</td>";
}//end foreach
echo "</tr>\n";
}//end while
I want to run a PHP function which deletes the selected record from the database however, obviously PHP runs on the server, therefore, I need some way to tell PHP which record is selected. Once again, if you look at my Javascript function, var id = the last selected record. How can I parse this JS variable to the server for processing?
In a nutshell, want to do this in PHP:
//delete selected record
if (isset($_POST['delete'])){
$query3 = "Delete from tbl_HR_Master where id = ". JS VARIABLE HERE." ";
} //end if
Form-based
You could do this with an hidden form field which you give a specific id:
<input type="hidden" id="your-id" value="" />
and then in your TableSelect function you assign the value:
document.getElementById('your-id').value = id;
Then you can access the variable like the other request (post / get) parameters, in your case:
$_POST['id']
Ajax-based
With jQuery you could perform an ajax request like this in your TableSelect function:
$.ajax({
url: 'file.php',
type: 'post',
data: {'id': el.id},
success: function(data, status) {
// ...
}
});
Request parameter access is the same:
$_POST['id']
You can have a hidden variable inside your form and use javascript to set the value of that hidden variable onclick.
<!--JS Functions-->
<script>
//Determine which record is selected.
var id;
function TableSelect(el) {
document.getElementById('selectedRow').value = el.id;
}
</script>
And add the following within your form tag
<input type="hidden" name="selectedRow" id="selectedRow">
Then you can update your query to be something like
$query3 = "Delete from tbl_HR_Master where id = $_POST['selectedRow']";
Of course don't forget to add sanitization and validation and all that jazz.

jQuery serialize and insert in mysql

I have this code to insert some data that comes from a while, in a db. I'm trying to use jQuery serializearray and jQuery post together. But it seems I do some errors
$query= "SELECT * FROM barcode_prodotti";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo'
<input type="text" name="prodotto[]" class="prodotto" value="'.$row["prodotto"].'"></div>
<input type="text" name="prezzo[]" class="price" value="'.$row["prezzo"].'">
<input type="text" name="quantita[]" class="price" value="'.$row["quantita"].'">';
}
?>
<script src="js/mine.js"></script>
<button>Serialize form values</button>
</form>
<div id="results"></div>
This is my jQuery code I put in mine.js
$(document).ready(function(){
$('form').submit(function(msg) {
var mia =$(this).serialize();
$('#results').text(mia)
alert($(this).serialize()); // check to show that all form data is being submitted
$.post("testtest.php",$(this).serializeArray(),function(data){
alert(data);
});
return false; });
});
This is my php file (testtest.php)
mysql_connect("localhost","root","");
mysql_select_db("db");
$arr = $_POST;
$sql="INSERT INTO table VALUES(
'".$arr['prodotto']."',
'".$arr['quantita']."',
'".$arr['prezzo']."'
)";
$rssql = mysql_query($sql);
?>
So I the serialize is ok (i tried to assign in a div a value to see if it was ok), but I can't insert values in my db
Your INSERT query ends up looking like this after variable substitution.
INSERT INTO table VALUES( 'product', '123', '321')
If your table has exactly three columns this will work fine. Otherwise it will fail. You may wish to use this query instead.
INSERT INTO table (prodotto, prezzo, quantita ) VALUES( 'product', '123', '321')
which enumerates the columns where you want your data.
After doing an insert (and after any query) you should check for errors. This can be done with code like this.
$res = mysql_query($q);
if ($res === false) {
echo $mysql_error ();
}
Note well: The mysql_xxx() interface is being removed from PHP for a good reason: it is vulnerable to cybercriminals. Please adopt mysqli_xxx() or PDO as soon as possible.
The simplest way to do this:
<form id="myform" method="post">
<input type="text" name="prodotto" id="prodotto">
<input type="text" name="prezzo" id="prezzo">
<input type="text" name="quantita" id="quantita">
</form>
Jquery is pretty simple too:
var datastring = $("#myform").serialize();
$.ajax({
type: 'POST',
url: 'url/to/yourfile.php',
data: datastring
}).done(function(res){
var res = $.trim(res); //the ajax response. you can alert it or whatever...
});
You can parse the fields in the ajax file like that:
yourfile.php
<?php
$product = mysql_real_escape_string($_POST["prodotto"]);
$prezzo = mysql_real_escape_string($_POST["prezzo"]);
$quantity = mysql_real_escape_string($_POST["quantita"]);
//here you have the variables ready to add them as values to database
$ins = "INSERT INTO table (prodotto, prezzo, quantita ) VALUES( 'product', '123', '321')";
mysql_query($ins);
?>

Getting form data from both dependent drop down lists to php

I have a form on my page which includes 2 dependent drop down lists. When user selects value from 1st list, it populates the second list and user then selects value from 2nd list.
I want to submit form data to php page to insert into table in mysql, but when it submits, all data is passed EXCEPT value from 2nd list. Value from 1st list and other input fields are passed OK.
I've tried everything I know and I can't make this work. Any ideas how to implement this?
This is the form from index2.php (EDIT: simplified the form element):
<form name="part_add" method="post" action="../includes/insertpart.php" id="part_add">
<label for="parts">Choose part</label>
<select name="part_cat" id="part_cat">
<?php while($row = mysqli_fetch_array($query_parts)):?>
<option value="<?php echo $row['part_id'];?>">
<?php echo $row['part_name'];?>
</option>
<?php endwhile;?>
</select>
<br/>
<label>P/N</label>
<select name="pn_cat" id="pn_cat"></select>
<br/>
<input type="text" id="manufactured" name="manufactured" value="" placeholder="Manufactured" />
<input id="submit_data" type="submit" name="submit_data" value="Submit" />
</form>
And this is javascript:
$(document).ready(function() {
$("#part_cat").change(function() {
$(this).after('<div id="loader"><img src="img/loading.gif" alt="loading part number" /></div>');
$.get('../includes/loadpn.php?part_cat=' + $(this).val(), function(data) {
$("#pn_cat").html(data);
$('#loader').slideUp(200, function() {
$(this).remove();
});
});
});
});
And this is php to load 2nd list:
<?php
include('db_connect.php');
// connects to db
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$part_cat = $_GET['part_cat'];
$query = mysqli_query($con, "SELECT * FROM pn WHERE pn_categoryID = {$part_cat}");
while($row = mysqli_fetch_array($query)) {
echo "<option value='$row[part_id]'>$row[pn_name]</option>";
}
?>
I am getting $part_cat from 1st list to insertpart.php, but $pn_cat.
EDIT: this is insertpart.php (simplified and it just echos resuls)
<?php
//Start session
session_start();
//Include database connection details
require_once('../includes/db_details.php');
//DB connect
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
// find part name based on ID
$part_typeID = mysqli_real_escape_string($con, $_POST['part_cat']);
$part_name_result = mysqli_query($con, "SELECT part_name FROM parts WHERE part_id = $part_typeID");
$part_row = mysqli_fetch_array($part_name_result, MYSQL_NUM);
$part_type = $part_row[0];
echo"part_type='$part_type'";
//find pn value based on id
$pn_typeID = mysqli_real_escape_string($con, $_GET['pn_cat']);
$pn_name_result = mysqli_query($con, "SELECT pn_name FROM pn WHERE pn_id = $pn_typeID");
$pn_row = mysqli_fetch_array($pn_name_result, MYSQL_NUM);
$pn = $pn_row[0];
echo"pn='$pn'";
mysqli_close($con);
?>
It's still work in progress, so the code is ugly, and I know I'm mixing POST and GET that is being rectified. If I echo $pn_cat on this page there is no output, $part_type is OK.
Can you try swapping the $_GET in
$pn_typeID = mysqli_real_escape_string($con, $_GET['pn_cat']);
with $_POST?
$pn_typeID = mysqli_real_escape_string($con, $_POST['pn_cat']);
EDIT: based on asker's feedback and idea for a work-around
NOTE: This edit is based on what you suggested, even though I tested your original code and received satisfactory results (after I removed the PHP and MySQL from the code and replaced them with suitable alternatives).
The Work-Around
Here's the HTML for the hidden field:
<input type="hidden" id="test" name="test" value="" placeholder="test" />
Here's a simple Javascript function:
function setHiddenTextFieldValue(initiator, target){
$(initiator).change(function() {
$(target).val($(this).val());
});
}
You can call the above function within the function(data) { of your original code with something like:
setHiddenTextFieldValue('#pn_cat', '#test'); // note the hashes (#)
I also recommend you to hard-code the following HTML into your HTML and PHP files, right before the looping of the <option>s begin:
<option value="" disabled selected="selected">Select</option>
The above line could improve user experience, depending on how you want your code to work. Note however, that this is entirely optional.
Solved it! It was just a stupid typo, can't believe I've lost 2 days over this!
In loadpn.php instead of:
$row[part_id]
it should read:
$row[pn_id]
For some reason drop down worked, but offcourse value of pn_cat wasn't being set.
Also this works in setting 2 field values (which now I don't need but if somebody wants to know):
$(document).ready(function() {
$("#part_cat").change(function() {
$('#pn_hidden').val($(this).val());
});
$("#pn_cat").change(function() {
$('#pn_hidden2').val($(this).val());
});
});
Also changed js to post:
$(document).ready(function() {
$("#part_cat").change(function() {
$.post('../includes/loadpn.php', 'part_cat=' + $(this).val(), function(data) {
$("#pn_cat").html(data);
});
});
});
And thanks for the:
<option value="" disabled selected="selected">Select</option>
It really helps with user experience.

Categories

Resources