Delete Current Row in Php - php

How can i delete the current row from Mysql using php ?
I want to search from my Mysql database, every individual row has a Delete button on right side.
When i click on Delete button, that current row should be deleted from database.
I've tried to create a function in php that contains the Query to delete from database. But its not working when i call it in my Search block.
I've created two functions, one in PHP (named as "hello") that contains the Delete Query and one in JavaScript (named as "DeleteRecord") that is calling php function "hello".
Now i called JS function in my Search block.
JS function is working fine, but when JS call a php function, it also works if i just use echo, but within php function if i un comment the Delete Query, it doesn't work !
Anyone to help me out
Thanks !
function viewRecord($Para)
{
echo "<table border=1>
<thead>
<th>Book_Number</th>
<th>Name</th>
<th>Auther</th>
<th>Quantity</th>
<th>Shelf</th>
</thead>";
while($row=mysql_fetch_array($Para))
{
echo "<tr>";
echo "<td>".$row['Book_Number']."</td>";
global $DeleteRecordNumber;
$DeleteRecordNumber = $row['Book_Number'];
echo "<td>".$row['Name']."</td>";
echo "<td>".$row['Auther']."</td>";
echo "<td>".$row['Quantity']."</td>";
echo "<td>".$row['Shelf']."</td>";
echo "<td>"."<input type=button value=Delete onclick=DeleteRecord()>"."</td>";
echo "</tr>";
}
echo "</table>";
}
function hello()
{
global $DeleteRecordNumber;
$asd = $DeleteRecordNumber;
echo $asd;
// $Del = "DELETE FROM books WHERE Book_Number='$asd'";
// mysql_query($Del);
}
mysql_close($Connection);
?>
<script type=text/javascript>
function DeleteRecord()
{
document.write (<?php hello(); ?>);
}
</script>

Wait a minute, i think you are mixing apples with oranges! You cannot execute a PHP function on the client side using a button unless you submit the form. The more i look at your post the more errors i Find.
However, assuming you ARE submitting the command (you are not showing what DeleteRecord() does, so i will assume you have a form submision there), You should have a unique field in your table, for example 'id" which would be of type NOT NULL, AUTO_INCREMENT, PRIMARY.
When dislpaying your rows, have each row to hold this unique id. Then when the button is pressed simply do:
$result = MySQL_Query("DELETE QUICK FROM books WHERE id='idtodelete'");
Update the query with your table name and a unique id, That should do it.
converting it to function should go like:
function delete_record($id)
{
return MySQL_Query("DELETE QUICK FROM books WHERE id=$id");
}
If you dont want to use a unique field, use anything that is unique, like an email or something that is not present in another record in the same table, like your field 'Book_Number', but it is more standard the field 'id'.
Column names are case-sensitive, so, if your query is not working as it should, check the character case of everything.

Are you trying to delete a record without refreshing the page?
If so you can remove the element via javascript/jquery and on the delete function you would make an ajax post call to the server with the book id and the operation to perform.
In jQuery it would look like (assuming you put an id in your book_number<td> as book_number):
<script>
var data = {
book_id: $("#book_number"),
operation:"delete"
}
var jqxhr = $.post( "example.php", data, function() {
alert( "Record deleted" );
//delete the row from the table
})
.done(function() {
alert( "Alternative to the above" );
})
.fail(function() {
alert( "error deleting record" );
})
.always(function() {
alert( "Operation completed" );
});
</script>
On the php side, in example.php you would need to adapt your code to include some processing if the $_SERVER['REQUEST_METHOD'] is equal to "POST" and if so, in your query string you would place:
"DELETE FROM books WHERE Book_Number='{$_POST['book_id']}'";
Keep in mind that although this might work, it is not safe from SQL injection, you would need to use some form of escaping to safeguard your queries from SQL Injection.
Another way to do it would be to have the delete button serve as a submit button for a form with the book_number being passed around and do the same above but this time around without the Javascript part. This would force a page reload.

Related

How to declare the value of id as a variable in phpMysql

From the below code I need to display the values of data1. I have declared it by using id as "id="data1". Suggest me how to pass this "data1" as a variable in phpMysql.
<div class="col-lg-12">
<p id="data1"></p>
<?php
// Make a MySQL Connection
mysql_connect("localhost", "projects", "pwd", "projects") or die(mysql_error());
mysql_select_db("projects") or die(mysql_error());
$var='data1';
// Get all the data from the "Race" table and create table
$result2 = mysql_query("SELECT
A.service_center_name,
A.status,
C.branch_name
FROM
customers A
INNER JOIN
ascs B ON A.serv_cent_mob_no = B.contact_number
Inner Join
branches C on B.branch_id=C.id
where C.branch_name='". $var. "'
GROUP BY A.service_center_name ,A.status,C.branch_name;")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Service Center Name</th> <th>City</th> <th>Branches</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result2 )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['service_center_name'];
echo "</td><td>";
echo $row['branch_name'];
echo "</td><td>";
echo $row['status'];
echo "</td></tr>";
}
echo "</table>";
?>
</div>
How to pass the data1 using variable in the below code "$var='data1';".
Solution:
You can use the jQuery AJAX function to parse the data to the desired file of your choosing. More about jQuery AJAX here.
Your AJAX function could look like so:
function postData() {
var data = $('#data1').html();
$.ajax({
type : "POST",
url: "/some/path/some_page.php",
data: { dataVariableName : data },
success: function (html) {
//Success handling
}
})
}
You could then fire the function from a button. For instance:
<button onclick="postData();">Submit data!</button>
In your some_page.php, you will then need to access your POST variable, like so:
<?php
$var=$_POST['dataVariableName'];
//Continue with SQL logic etc.
?>
Explanation:
What we basically did here, is that we encapsulated the AJAX function into another function named, postData, which we can use to call onclick, or however we desire. We could also simply add an onclick event to the ajax function directly, but I thought this would make for an easy understanding.
We then go on to define a variable that contains the data we wish to parse.
Then in our AJAX function, we first define our data type. As you can see in this example, we're using the data type POST. There are other data types that you can define here, and each for a different purpose. Another well-known data type would be GET for instance. I suggest you look up the data types to find out what they mean, and what influence they have. For instance, GET types will show as parameters in the URL.
Next we define what page we are sending our data to, which will be some_page.php in our example.
We then go on to define our POST variable, which is going to contain the data we're supposed to parse. You can parse more than one variable at a time in your AJAX function, by doing so:
data: {
dataVariableName : data,
dataVariableName2 : otherData,
//more variables [...]
},
Note that I also defined a success function in our AJAX function. We can use this to do a lot of things upon success, if we so desire. I.e. redirect to another page, alert(); a success message etc. etc. A lot of things.
If you run into trouble with the SQL, let me know, and I can take a look at that as well.
Important note:
You should really consider switching to mysqli_* or PDO, instead of using the deprecated mysql_* notation. You won't be able to use the mysql_* notation in the newer version of PHP, i.e. PHP 7.0 and forward. You should also look into prepared statements and sanitizing your inputs in general, in case you continue with the mysql_* notation.
using Jquery you can get the data in p tag like below
var pdata = $('#data1').html();
you can post this data to php using jquery Ajax as below
request = $.ajax({
url: "/form.php",
type: "post",
data: pdata
});
In your php, you can make it as
$var = $_POST['data'];

How to use onclick on a button with an insert function for multiple buttons php

I have a page with several buttons whose values and names are retrieved from the database. I'm trying to run an insert query on any button clicked, my code so far:
<?php
$sqlGetIllness = "SELECT * FROM illnissesandconditions ";
$resultGetIllness = $conn->query($sqlGetIllness);
while ($rowGetIllness= mysqli_fetch_array($resultGetIllness)){
echo "<div class='col-md-3'style='margin-top:20px;'><button onclick='insert(".$rowGetIllness['illness'].");' class='button button1' style=' color:white;' value='".$rowGetIllness['illness']."'>".$rowGetIllness['illness']."</button></div>";
}
function insert($value) {
$value='';
$sqlGetId = "SELECT commonID from common group by commonID DESC LIMIT 1 ";
$resultGetId = $conn->query($sqlGetId);
$r=mysqli_fetch_array($resultGetId);
$id=$r['commonID'];
$sqlGetIllness = "INSERT INTO medicalrecords (CommonID,Medical_Condition) VALUES (".$id.",'".$value."')";
$resultGetIllness = $conn->query($sqlGetIllness);
}
The value passed to the function inside onclick is correct when I inspect it in the browser, however nothing happens. I have a database connection on already, what could be wrong? Is it possible to do it like that in php without refreshing the page? Or do I need to use a client side lang like AJAX? Please note that I've never worked in AJAX btw.
New EDIT:
<script>
$("button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
data: {
condition: $(this).val(), // < note use of 'this' here
},
success: function(result) {
alert('Condition Inserted!');
},
error: function(result) {
alert('error');
}
});
});
</script>
Solution:
I got it worked out, after writing the script, i retrieved the variable value on top of the page
if (isset($_POST['condition'])) {
$value=$_POST['condition']; }
inside $_SERVER['REQUEST_METHOD'] == 'POST' ) and now it inserts the value when ever any button is clicked, my next step is to give the clicked button a background color
Solution is in the post under Solution, was my first time trying ajax and it did work indeed, gave the button an id, and took its value ( any button clicked ) through this.val and sent via post, retrieved and used the value in a variable for the insert query.

jQuery AJAX request not firing when posting to a php script.

I have a database table which I am trying to retrieve data from using JQUERY AJAX. When my first page loads it does a php call to a table and populates a select form element. - This works
I then want to select one of the options submit the form and have the row returned via Ajax.
Previously I had the script working with just PHP files but am having trouble getting it to work. When submitting the form my URL is changing:
http://localhost/FINTAN/testertester.php?name=Specifics.
I am not getting anything back. In addition when looking at my console I get a jquery not defined
factory (jquery). I can find the line in question in my jquery ui.js. Not sure if this is the issue or my code has caused the issue. I have cleard the firefox cache and due to the fact I have not had a successful AJAX call via jquery method am guessing it my code.
To get the code below I have mixed and matched a book and an online tutorial and many other sources and this is not my first attempt. Ideally I would like to output table row. However just getting a request working and knowing its not a conflict or compatability issue would makeme feel better and not hindered before I start
<script src="jquery/jquery-ui-1.11.2/jquery-ui.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#name").val;
}
}
$.post("addithandle1.php",
{
name:vname};
function(response,status){
alert("recieved data-------*\n\nResponse : " + response
+"\n\nStatus : " + status);
}
}
</script>
</head>
<body>
<?php
include "config.php";
if (mysqli_connect_errno($con))
{
}
else
{
$result = mysqli_query($con, "SELECT * FROM script ");
echo " <Form method='post'> <label>Script :</label> <select id='name' name='name' >";
}
while($row = mysqli_fetch_array($result))
{
echo "<option value = '".$row['scriptname']."'>".$row['scriptname']."</option>";
}
echo "</select>";
echo "<button id='btn' class='btn-search'>Load Script </button></form>";
?>
</body></html>
This is my PHP file that I am trying to retrieve from
<?php
include 'config.php';
$batchtype2 = $_POST['name'];
$batchtype2 = mysqli_real_escape_string($con,$batchtype2);
$sql = "SELECT * FROM script WHERE scriptname = '".$batchtype2."' ";
$result = mysqli_query($con,$sql);
$count=mysqli_num_rows($result);
if($count==0 ){
echo "</br></br></br></br></br></br></br><p> No Matching results found</p>";
}
else{
while($row = mysqli_fetch_array($result)) {
echo '<tr><td>'.$row['scriptname'].'</td></tr>';
echo '<tr><td>'.$row['scripthours'].'</td></tr>';
echo '<tr><td>'.$row['scripttotal'].'</td></tr>';
}
}
mysqli_close($con);
?>
Thanks in advance for any help
By making the following corrections (you have some syntax issues as well as usage issues which should be revealed in your browser's console when you load this page) in your JavaScript/jQuery this will work like you expect -
Make sure to change this line -
var vname = $("#name").val;
to this -
var vname = $("#name").val(); // note the parentheses
in your function -
$(document).ready(function(){
$("#btn").click(function(e){
e.preventDefault(); // prevent the default action of the click
var vname = $("#name").val();
$.post("addithandle1.php", {name:vname}, function(response, status) { // POST instead of GET
// never use alert() for troubleshooting
// output for AJAX must be in the callback for the AJAX function
console.log("recieved data-------*\n\nResponse : " + response +"\n\nStatus : " + status);
$('#table').html(response); // put response in div
});
});
});
Now $_POST['name'] should get populated properly.
To get the table to appear in your requesting page first make sure that your PHP forms the table completely.
Add a div to your requesting page and modify the AJAX call above as shown.
<div id="table"></div>
Now, when you make a request the div on the requesting page will be updated with whatever comes back from the PHP script.
There are a couple of things about your script.
First make sure you write well structured code and that it is nothing in the wrongplace / broken.
You have in the $(document).ready(function(){ only the .click event of the button, but you left the ajax request outside, I imagine you did that so it will also make the ajax request in the first page load
The problem is that now it will only make it in the first page load, but not when you click the button, on clicking button you are only getting the value of name.
I recommend you to try something like this:
<script>
$(document).ready(function() {
// bind button click and load data
$("#btn").click(function(){
loadData();
return false; // prevent browser behaviour of the button that would submit the form
}
// load data for the first time
loadData();
};
function loadData() {
var vname = $("#name").val;
$.post("addithandle1.php", { name:vname }, function(response, status) {
alert("recieved data-------*\n\nResponse : " + response
+"\n\nStatus : " + status);
});
}
</script>
A few notes:
I would recommend always putting jquery code inside $(document).ready since that guarantees that jquery was loaded before running it
By default a form that has a submit button that you click, will get the form submitted by the browser, if you use ajax, you should prevent that behaviour, either on the button click event or on form with onsubmit="return false".

edit in place and change value to database also?

I am using editable plugin to edit-in-place. I am able to do it on the web page but I want to change this value to the database also.
Here is the php/html code :
while($row = mysql_fetch_assoc($result))
{
echo "<tr class='highlighter'><td class='editable-1'>".$row['subcategory_name']."</td>";
echo "</tr>";
}
and the jquery code is as follows :
$(document).ready(function()
{
$('.editable-1').editable({onEdit:begin});
function begin(){
this.append('Click somewhere else to submit');
}
}
);
I am trying to use ajax but not getting the value when I am updating in textbox.
Here is what I am trying to do
$.ajax({
url:'change_subcat.php',
data:'NOT AVAILABLE'
});
Please tell me how to made changes also in database.
You will need to submit the data via ajax to the server, where you need a script to process the data and save it to your database.
It looks like in this plugin, you can attach a listener to the onEdit event that will submit your data, maybe something like this:
$('.editable-1').editable({onEdit: submitData});
function submitData (content) {
$.post('/save_to_db.php', { data: content.current });
}
From the documentation for this plugin, it appears that the callback is called with an object for an argument (content, in this case) that has previous and current properties. You should be able to get the new value of the editable field with content.current.

Combine JQuery/PHP to log clicks into database?

The attached picture shows the results page of the search engine that I'm building. For each return result, the user may click on the result (i.e. "Food Science") and it will expand out accordion-style to reveal information about that particular result.
I want to log each time the user clicks on a result (for learning/intelligence purposes) and store it in a database table that I have created which stores the session ID, the query, the position of the result, and the order in which the user clicked the item.
Using JQuery, I already have a function that will pull the title of the result that was clicked, and I have it set where I want to log the click, but I don't know how to do it since JQuery is client side and PHP is server side.
How can I use the JQuery to trigger a PHP function so that I can query the database to insert the click logs into my table?
Below is the JQuery function.
$(document).ready(function() {
$('.accordionButton').click(function(e) {
if($(this).next().is(':hidden') == true) {
$(this).addClass('on');
$(this).next().slideDown('normal');
$(this).next().slideDown(test_accordion);
// SEND CLICK ACTION TO LOG INTO THE DATABASE
alert($(this).find('h3:last').text()); // displays the title of the result that was just clicked
}
else {
$(this).removeClass('on');
$(this).next().slideUp('normal');
$(this).next().slideUp(test_accordion);
}
});
}
You can do something like this (untested):
Define a javascript variable to track the order of the clicks, outside your click function:
var order = 0;
Add this into your click function, at the bottom:
order++;
var sessionID = $("input[name='sessionID']").val(); // assuming you have sessionID as the value of a hidden input
var query = $("#query").text(); // if 'query' is the id of your searchbox
var pos = $(this).index() + 1; // might have to modify this to get correct index
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order});
In your php script called "logClick.php" (in the same directory):
<?php
// GET AJAX POSTED DATA
$str_sessionID = empty($_POST["sessionID"]) ? '' ; $_POST["sessionID"];
$str_query = empty($_POST["query"]) ? '' ; $_POST["query"];
$int_pos = empty($_POST["pos"]) ? 1 ; (int)$_POST["pos"];
$int_order = empty($_POST["order"]) ? 1 ; (int)$_POST["order"];
// CONNECT TO DATABASE
if ($str_sessionID && $str_query) {
require_once "dbconnect.php"; // include the commands used to connect to your database. Should define a variable $con as the mysql connection
// INSERT INTO MYSQL DATABASE TABLE CALLED 'click_logs'
$sql_query = "INSERT INTO click_logs (sessionID, query, pos, order) VALUES ('$str_sessionID', '$str_query', $int_pos, $int_order)";
$res = mysql_query($sql_query, $con);
if (!$res) die('Could not connect: ' . mysql_error());
else echo "Click was logged.";
}
else echo "No data found to log!";
?>
You can add a callback function as a third parameter for the $.post() ajax method if you want to see if errors occured in the script:
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order},
function(result) {
$('#result').html(result); // display script output into a div with id='result'
// or just alert(result);
})
);
EDIT: If you need the value of the order variable to persist between page loads because you paginated your results, then you can pas the value of this variable between pages using either GET or POST. You can then save the value in a hidden input and easily read it with jQuery. (Or you could also use cookies).
Example (put this in every results page):
<?php
$order = empty($_POST["order"]) ? $_POST["order"] : "0";
$html="<form id='form_session' action='' name='form_session' method='POST'>
<input type='hidden' name='order' value='$order'>
</form>\n";
echo $html;
?>
In your jQuery, just change var order = 0; to
var order = $("input[name='order']").val();
Then, when a user clicks on a page link, prevent the default link action, set the order value and the form action, and then submit the form using javascript/jQuery:
$("a.next_page").click(function(event) {
event.preventDefault();
var url = $(this).attr("href");
$("input[name='order']").val(order);
$("#form_session").attr('action', url).submit();
});
All the 'next' and 'previous' pagination links must be given the same class (namely 'next_page' (in this example).
EDIT: If your pagination is as follows:
<div class='pagination'>
<ul><li><a href='page1.url'>1</a></li>
<li><a href='page2.url'>2</a></li>
</ul>
</div>
then just change this:
$("div.pagination a").click(function(event) {
etc.
This one is pretty easy, you need a PHP-Script to handle AJAX requests which are sent from your Search page.
In your search page you'll need to add an .ajax to create an AJAX request to your Script.
Everything you need to know about AJAX can be found here: http://api.jquery.com/jQuery.ajax/
In your PHP-Script you'll handle the Database action, use GET or POST data to give the script an ID over Ajax.
Use Ajax. Write a simple php-script that writes clickes to the database. I don't know how you log the clicks in the database exactly, but you can send the clicked item unique identifier to a php script with ajax, for example via POST variables.
A little example, on click:
$.post(
'count_click.php',
{ id: "someid" },
function(data) {
// data = everything the php-script prints out
});
Php:
if (isset($_POST['id'])) {
// add a click in the database with this id
}
Send a request to a PHP page using jQuery AJAX. See here for more info (it is really simple):
http://api.jquery.com/jQuery.ajax/
In this particular case, as you do not need to return anything, it may be better to just use the POST or GET methods in jQuery:
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.get/
Something like:
$.ajax({
  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston"
success: function(data){
alert('done');
});

Categories