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.
Related
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!
I have a text box which populates from database value.
<form id="manageSalesForm" name="manageSalesForm" method="post" action="<?php echo BASE_URL?>includes/functions/sales_functions.php">
<input name="txtSubTotal" type="text" id="txtSubTotal" size="15" value="<?php
$sql=mysqli_query($connection,'select sum(amount) from sales_temp');
$row = mysqli_fetch_array($sql);
echo $row[0];
?>"/>
I need to reset this, once submit button is clicked. (Moreover, when I clicked the button second time, it clears the text box.
<input type="submit" name="btnProceed" id="btnProceed" value="PROCEED" onclick="document.getElementById('txtSubTotal').value = '';"/>
Proceed button query
<?php
//Start the Session
if(!isset($_SESSION))
{
session_start();
}
include ("/../../pages/sales.php");
include("/../../dbutil.php");
if(isset($_POST['listCustomer'])){ $customer = $_POST['listCustomer'];}
if(isset($_POST['staff'])){ $user = $_POST['staff']; }
if(isset($_POST['txtReceiptNo'])){ $receipt_no = $_POST['txtReceiptNo']; }
if(isset($_POST['txtSubTotal'])){ $subTotal = $_POST['txtSubTotal']; }
if(isset($_POST['btnProceed'])){
$result=mysqli_query($connection,
"INSERT INTO sales(cus_id,item_id,stock_id,receipt_no,qty,unit_price,amount,user_id,purchase_id)
SELECT C.cus_id, I.item_id, S.stock_id, $receipt_no, ST.qty, ST.unit_price, ST.amount, U.id, P.purchase_id
FROM customers C, items I, stock S, sales_temp ST, users U, purchase_items P
WHERE ST.staff='$user'
AND C.customer_name='$customer'
AND I.item_name=ST.item_name
AND S.stock_code=ST.stock_code
AND ST.purchase_id=P.purchase_id");
//Update available qty from purchase_items relevant only to the logged in user(sales_temp table may have records from multiple users)
$resultUpdate=mysqli_query($connection, "UPDATE purchase_items P INNER JOIN sales_temp ST ON (P.purchase_id = ST.purchase_id) SET P.avail_qty = (P.avail_qty - ST.qty) WHERE ST.staff='$user'");
//Delete records relevant only to current user. Here 'WHERE' clause use to prevent deleting other user's records.
$resultDelete=mysqli_query($connection, "DELETE FROM sales_temp WHERE staff='$user'");
if (!$result) {
printf("Errormessage: %s\n", mysqli_error($connection));
}
// use exec() because no results are returned
if ($result) {
/*echo '<script type="text/javascript">',
'salesAddSuccess();',
'</script>';*/
}
else
{
echo '<script type="text/javascript">',
'salesAddFail();',
'</script>';
}}
?>
Code of button onclick for displaying the Sub Total, showSubTotal()
<button type="button" name="btnSave" id="btnSave" onclick="submitdata(); check_qty(); showSubTotal();">ADD</button>
This code not works. Please help me.
I found the solution, added the do_onload(id) to calculate the total on loadComplete event which is triggered after each refresh (also after delete)
function do_onload(id)
{
//alert('Simulating, data on load event')
var s = $("#list").jqGrid('getCol', 'amount', false, 'sum');
jQuery("#txtSubTotal").val(s);
}
And changed the phpgrid code accordingly.
$opt["loadComplete"] = "function(ids) { do_onload(ids); }";
$grid->set_options($opt);
I have two php files that handle a commenting system I have created for my website. On the index.php I have my form and an echo statement that prints out the user input from my database. I have another file called insert.php that actually takes in the user input and inserts that into my database before it is printed out.
My index.php basically looks like this
<form id="comment_form" action="insertCSAir.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="field1_name"/>
<input type="submit" name="submit" value="submit"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<!--connects to database and queries to print out on site-->
<?php
$link = mysqli_connect('localhost', 'name', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
I want users to be able to write comments and have it updated without reloading the page (which is why I will be using AJAX). This is the code I have added to the head tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
// this is the id of the form
$("#comment_form").submit(function(e) {
var url = "insert.php"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: url,
data: $("#comment_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
However, nothing is happening. The alert() doesn't actually do anything and I'm not exactly sure how to make it so that when the user comments, it gets added to my comments in order (it should be appending down the page). I think that the code I added is the basic of what needs to happen, but not even the alert is working. Any suggestions would be appreciated.
This is basically insert.php
if(!empty($_GET["field1_name"])) {
//protects against SQL injection
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
header("Location:index.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
it also filters out bad words which is why there's an if statement check for that.
<?php
if(!empty($_GET["field1_name"])) {
//protects against SQL injection
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element)
{
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0)
{
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
if ($result)
{
http_response_code(200); //OK
//you may want to send it in json-format. its up to you
$json = [
'commment' => $newComment
];
print_r( json_encode($json) );
exit();
}
//header("Location:chess.php"); don't know why you would do that in an ajax-accessed file
//die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
?>
<script>
// this is the id of the form
$("#comment_form").submit(function(e) {
var url = "insert.php"; // the script where you handle the form input.
$.ajax({
type: "GET", //Id recommend "post"
url: url,
dataType: json,
data: $("#comment_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
$('#myElement').append( data.comment );
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
To get a response from "insert.php" you actually need to print/echo the content you want to handle in the "success()" from the ajax-request.
Also you want to set the response-code to 200 to make sure "success: function(data)" will be called. Otherwise you might end up in "error: function(data)".
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);
?>
I am trying to simply just pass (or POST) a variable indicated by the user in a textbox to another .php for processing.
This is my POST function in javascript.
function POST() {
var name = $('#name').val();
$.post('pages/searchResult.php',{name:name}, function (data) {
$('#name_feedback').html(data);
});
}
This is how the user indicates the variable through a textbox and submit.
<div id="name_feedback"></div>
<div style="text-align: center"><input type="text" placeholder="Enter first or last name" name="name" id="name" class="textbox"/></div>
<div style="text-align: center"><input type="Submit" value="Search" class="css_button" id="searchBtn" onclick="POST();"/></div>
I am not sure why but my .php wont receive the variable..
<?php
//include('connect.php');
$pointData = array();
$dateData = array();
$name = $_POST['name'];
$query = "SELECT * from `users` WHERE firstName = '$name' OR lastName = '$name' LIMIT 1";
$result = mysql_query($query); //<<<
$row = mysql_fetch_assoc($result);
$userid = $row['id'];
echo mysql_error();
?>
I am using this video as a reference:
http://www.youtube.com/watch?v=-EHbBHm5l4g
try this way
var name = $('#name').val();
$.post('pages/searchResult.php',{"name":name}, function (data) {
$('#name_feedback').html(data);
}) .fail(function(err) {
alert( "error" +err);
});
At your php script side, you can echo the data which you want to return back based on success of the query search.
remove the single around the table name users and around $name from the below
"SELECT * fromusersWHERE firstName = '$name' OR lastName = '$name' LIMIT 1";
Happy Coding :)