I am using the following PHP code to delete my data from a mysql database. It's working for me, but it's redirecting me another page named delete_ac.php. I want to keep it in the same page (index.php), and if possible I want to use jquery so that data is deleted without redirecting the page.
index.php
<?php
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
?>
<tr>
<td bgcolor="#FFFFFF" style="border:1px solid black" >
<?php echo $row[0].' '; ?>
</td>
<td bgcolor="#FFFFFF" style="border:1px solid black">
<?php echo $row[1]; ?>
</td>
<td bgcolor="#FFFFFF">
delete
</td>
</tr>
<?php
}
?>
<?php include 'footer.php'; ?>
delete.ac.php
<?php
mysql_connect("localhost", "root", "") or
die("Could not connect: " . mysql_error());
mysql_select_db("dbname");
$tbl_name="tablename"; // Table name
// get value of id that sent from address bar
$id=$_GET['id'];
// Delete data in mysql from row that has this id
$sql="DELETE FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);
// if successfully deleted
if($result){
echo "Deleted Successfully";
echo "<BR>";
echo "<a href='index.php'>Back to main page</a>";
}
else {
echo 'Error';
}
?>
<?php
// close connection
mysql_close();
?>
A simple answer for you would be:
Include a delete class in your anchor.
<td bgcolor="#FFFFFF"><a class="delete" href="delete_ac.php?id=<?php echo $row[0]; ?>">delete</a></td>
Bind its click to jquery
$('a.delete').on('click', function(e){
var href = $(this).attr('href');
$.ajax({
'url' : href,
'type' : 'GET',
'success' : function(data) {
alert('Data: '+data);
},
'error' : function(request,error)
{
alert("Error");
}
});
});
As others have mentioned, look into SQL prepared statements.
To answer your question, you'd use the following for the ajax call
$.ajax({
method: "POST",
url: "delete.ac.php",
data: { id: PUT_YOUR_ID_VALUE}
});
and change $id=$_GET['id']; to $id=$_POST['id']; in delete.ac.php
Here's a new index.php that uses PDO and removes the need for a second, separate page. It's not perfect, and there's some stuff that can still be cleaned, but this is how I'd change it (while trying to keep it as close as possible to your posted code)
<?php
//Run the following code if and only if a POST
//request is made to this page.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
mysql_connect("localhost", "root", "") or
die("Could not connect: " . mysql_error());
mysql_select_db("dbname");
//This is really important. This is a predefined statement
//the code you had is at risk for SQL injection. Please read up on this
$sql = "DELETE FROM :TABLENAME WHERE id = :ID";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':ID', $_POST['id']);
$stmt->bindParam(':TABLENAME', "tablename"); //put tablename here
$stmt->execute();
}
// This ends the 'POST' code
//
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
?>
<tr>
<td bgcolor="#FFFFFF" style="border:1px solid black" >
<?php echo $row[0].' '; ?>
</td>
<td bgcolor="#FFFFFF" style="border:1px solid black">
<?php echo $row[1]; ?>
</td>
<td bgcolor="#FFFFFF">
delete
</td>
</tr>
<?php
}
?>
<script>
//We're creating a javascript function that will be called
//when the user clicks 'delete'. It takes the ID and passes it
//in the AJAX call
function delete(id){
$.ajax({
method: "POST",
url: "index.php",
data: { id: id}
});
}
</script>
<?php include 'footer.php'; ?>
Related
i have a table where i print out all of the users for the program. now i would like to have a toggle Bootstrap button for Activate and Incative. I would like to store 1 and 0 into my database. how do i save the value for the specific User ID the value and then update it when the button pressed. Also how to then when it has been pressed to then update the page? is it possible to not refresh the page?
<div class="table-responsive-sm">
<table class="table table-bordered table-condensed table-striped text-center table-dark">
<tr>
<th> First Name</th>
<th>Last Name</th>
<th>E-mail</th>
<th>Username</th>
<th>Accreditation</th>
<th>Instructor ID</th>
<th>Time Registered</th>
<th>Account State</th>
<th>Activate</th>
<th>SET Inactive</th>
</tr>
<?php
$sql = ("SELECT * FROM instructors GROUP BY ID ORDER BY ID DESC ");
$result=mysqli_query($mysqli,$sql);
while ($row=mysqli_fetch_array($result)){
$accred = $row['role'];
if($accred == '0'){
$test = 'Admin';
} else if ($accred == '1') {
$test = 'Bookkeper';
} else if ($accred == '2') {
$test = 'Coordinator';
} else if ($accred == '3') {
$test = 'Instructor';
}
$LoginState = $row['LoginState'];
if($LoginState == '0'){
$LogState = '<td style="color: White; background-color: orangered"><b>Inactive</b></td>';
} else if ($LoginState == '1') {
$LogState = '<td style="color: black; background-color: lightgreen"><b>Active</b></td>';
}
$ID = $row['ID' ];
echo "
<form method=\"POST\">
<tr>
<td>".$row['Fname']."</td>
<td>".$row['Lname']."</td>
<td>".$row['Email']."</td>
<td>".$row['username']."</td>
<td>".$test ."</td>
<td>".$row['ID' ] ."</td>
<td>".$row['RegisteredTime']."</td>
$LogState
<td><button name=\"LoginState\" type=\"button\" class=\"btn btn-success\" role=\"button\" value\"1\">Activate</button</td>
<td><button name=\"LoginState\" type=\"button\" class=\"btn btn-warning\" role=\"button\" value\"0\">SET Inactive</button</td>
</tr></form>";
}
if (isset($_POST['LoginState'])){
$sql1 = "INSERT into instructors (LoginState) VALUES ($logstats) WHERE ID = $ID";
if ($mysqli->query($sql1) === TRUE) {
echo "New record created successfully";
echo "<br/>";
} else {
echo "Error: " . $sql1 . "<br>" . $mysqli->error;
}}
Here is the html code to show toggle button
<td data-title="Status">
<label class="switch">
<input type="checkbox" id="toggle<?php echo $id; ?>" name="status_<?php echo $id; ?>" <?php if($status == 'on'){echo "checked"; }?> >
<div class="toggle round"></div>
</label>
</td>
$id is dynamic id which you get from db.you need proper CSS these classes to make it toggle button.
AJAX call to update records in db onChange of checkbox value
<script type="text/javascript">
$(document).ready(function(){
$('#toggle<?php echo $id; ?>').click(function(){
var id = <?php echo $id; ?>;
if($(this).prop("checked") == true){
var stat = 'on';
}
else if($(this).prop("checked") == false){
var stat = 'off';
}
$.ajax({
type: "POST",
url : "example.php",
data : { id : id,stat :stat },
success: function(data) {
//update value in page acc to new updated value from db
}
});
});
});
</script>
$id is same as above. You need to do update then select query in example.php to update content in page, without refreshing the page
Mark, as others said, if you want to refresh part of your page without reloading the whole page, you need to use AJAX.
One of the most popular and simple way to use AJAX is including the jQuery.js library. If you already use javascript, you will find a bit easy to include jQuery in your page. (you can find and copy the jquery.js file anywhere on internet, just type "download jquery file" in google)
in example, you can put this code in your html (in fact, you can put it almost in any place of your page)
<script type="text/javascript" src="jquery.min.js"></script>
Then you can use the softech's example...
<script type="text/javascript">
$(document).ready(function(){
...
$.ajax({
type: "POST",
url : "PageThatOnlyReturnsData.php",
data : { id:id, stat:stat },
success: function(data) {
//update value in page acc to new updated value from db
}
});
...
});
</script>
It's strongly recommended thay you create another php page to place de mySQL code and returns data (I named in example "PageThatOnlyReturnsData.php"), so this php page will print out the result data from your query.
So, the front php (the first page with HTML) calls the second php (the data php) through the $.ajax() function, and you can process the received data within the "success" function.
success: function(data) {
//here "data" is what you receive from the second php
//do what you want here with javascript using the new variable "data" as in the softech's example
}
Please help me. Thanks in advance. Actually I am trying to insert selected checkbox rows into database using jquery but i don't know how to insert into DB.My jquery code is selecting the row but how to check whether the row is passing through ajax request. My table has a dynamic row from the database table with checkboxes. so when i checked the checkboxes and click the submit button then the table row should insert into the database table.
My code as below:
test.php
<?php
$con = mysql_connect("localhost","root","");
if(!$con)
{
die("Could not connect:".mysql_error());
}
mysql_select_db("cakephp",$con);
$sql = mysql_query("select * from carts where userid=13");
?>
<html>
<head>
<title></title>
<script src="jquery.js"></script>
<script src="jquery.validate.min.js"></script>
<script src="jquery-ui.min.js"></script>
<style type="text/css">
.row_selected {background-color: #BFCBD7;}
</style>
<script>
$(document).ready(function(){
$('.chk').on('change', function() {
//alert('Hai');
var thisCheckbox = $(this);
var thisRow = thisCheckbox.closest('tr');
if ( thisCheckbox.is(':checked') ) {
thisRow.addClass('row_selected');
} else {
thisRow.removeClass('row_selected');
};
});
$('#orderSave').on('click', function(row,tr) {
//e.preventDefault();
//var toPost = $('.row_selected input').serialize();
/* Now post and insert into database */
//$.post('/invl_exams/ordercompletion', toPost, function(data) {
//alert('Success!');
//});
// Here i am creating the array to hold each selected row
var TableData = new Array();
var priVal = $(tr).find('td:eq(6)').text();
var priceVal = priVal.replace('$','');
TableData[row] = {
//column names: corresponding row data
"userid" : $('#userid').val(),
"username" : $('#hiddenUser').val(),
"date" : $(tr).find('td:eq(3)').text(),
"exam" : $(tr).find('td:eq(4)').text(),
"venue" : $(tr).find('td:eq(5)').text(),
"price" : priceVal,
"total_orders" : $(tr).find('td:eq(7)').text(),
"amount" : $(tr).find('td:eq(8)').text(),
"orders_completion" : $(tr).find('td:eq(9)').text()
}
TableData = JSON.stringify(TableData);
//console.log(TableData);
$.ajax({
type : "POST",
url : "testsubmit.php",
cache : "false",
data : {data:TableData},
success : function(result){
console.log(result);
}
});
});
});
</script>
</head>
<body>
<table border="1">
<tr>
<th>S.No</th>
<th>Exam Name</th>
<th>Venue</th>
<th>Date</th>
<th>Price</th>
<th>No of Orders</th>
<th>Amount</th>
<th>Checks</th>
</tr>
<?php
$i=1;
while($row = mysql_fetch_array($sql))
{
?>
<tr>
<td><?php echo $i++;?></td>
<td style="display:none" id="userid">13</td>
<td style="display:none" id="hiddenUser">Gautham</td>
<td><?php echo $row['exam_name'];?></td>
<td><?php echo $row['venue'];?></td>
<td><?php echo $row['date'];?></td>
<td><?php echo $row['price'];?></td>
<td><?php echo $row['noOf_orders'];?></td>
<td><?php echo $row['amount'];?></td>
<td><input type="checkbox" name="chk" class="chk" value="1"></td>
</tr>
<?php
}
?>
<tr>
<td colspan="7"> </td>
<td><button type="button" class="btn btn-success btn-xs" id="orderSave">Submit</button></td>
</tr>
</table>
</body>
</html>
testsubmit.php ( In this file i was checking the post request using print_r($_POST) )
<?php
$con = mysql_connect("localhost","root","");
if(!$con)
{
die("Could not connect:".mysql_error());
}
mysql_select_db("cakephp",$con);
//if(isset($_POST['toPost']))
//{
print_r($_POST);
//}
?>
your data inside last td is an input so you must
change from
"orders_completion" : $(tr).find('td:eq(9)').text()
to
"orders_completion" : $(tr).find('.chk')[0].checked
I am have a page where i have the table row id defined by 'lesson_id' and i have a delete function for jquery that deletes that row without having to change page.
It is almost all working but when it posts the information to delete_row.php it is not deleting the record.
but delete_row.php is working because i've manually done delete_row.php?id=4 and it deleted that record succesfully.
Any pointers and explanations would be great as i'm still learning.
lessons.php
<table id="lessons" class="table-hover">
<thead>
<tr>
<th>Lesson ID</th>
<th>Lesson Name</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
while($row=mysqli_fetch_array($result)){
echo '<tr id="'. $row['lesson_id'].'">';
echo '<td>'. $row['lesson_id'] .'</td>';
echo '<td>'. $row['name'] .'</td>';
echo '<td><a class="delete">Delete</a></td>';
echo '</tr>';
}
?>
</tbody>
<div id="error"></div>
<script>
$(document).ready(function()
{
$('table#lessons td a.delete').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
//$('#error').html(data);
$.ajax(
{
type: "POST",
url: "delete_row.php",
data: data,
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
}
});
}
});
});
</script>
delete_row.php
<?php
include ('../../../config.php');
$con = mysqli_connect ($dbhost,$dbuser,$dbpass,$dbname);
if (!$con){
die('could not connect: '. mysqli_error($con));
}
$error = "";
$success = "";
if($_GET['id'])
{
$id = $_GET['id'];
mysqli_query($con,"DELETE FROM module_lessons WHERE lesson_id='$id'");
}
?>
as its obvious ... this has no sql injection protection on it.
Change $_GET['id']; to $_POST['id'];
Here, you're doing a POST request:
type: "POST",
url: "delete_row.php",
... but in your PHP script you're checking for GET.
Also, as marc b noted, you're currently vulnerable to SQL injection. Look into using mysqli_real_escape_string, or bind_param.
I have radio button in a PHP while-loop.
I am storing the first row value in the value of radio button.
I need to pass the value of radio button in HTML a href.
How to pass that value with both PHP and HTML in same page??
My code:
index.php
<html>
<body>
<img src="images/print_label.png" name="Image3" width="152" height="110" border="0" align="top" style="margin-top:10px">
<?php
include "db.php";
require_once "purna_insert_orders_to_ship.php";
if(isset($_POST['submit']))
{
if($_POST['value'] == 'readytoship') {
// query to get all Fitzgerald records
$query = "SELECT * FROM orders WHERE status='readytoship'";
}
elseif($_POST['value'] == 'readytodispatch') {
// query to get all Herring records
$query = "SELECT * FROM orders WHERE status='readytodispatch'";
} else {
// query to get all records
$query = "SELECT * FROM orders";
}
$sql = mysql_query($query);
$num_rows = mysql_num_rows($sql);
if($num_rows >= 1)
{
echo "<div id='showmenu' class='scroll'>";
echo "<table id='table_struct' cellspacing='0' cellpadding='1' border='1' width='400' height='30'>
<tr class='tr_class' bgcolor='white'>
<td align='center' style='font-weight:bold'> Select </td>
<td align='center' style='font-weight:bold'> Po Id </td>
<td align='center' style='font-weight:bold'> Customer Name </td>
<td align='center' style='font-weight:bold'> quantity </td>
<td align='center' style='font-weight:bold'> price </td>
<td align='center' style='font-weight:bold'> status </td>
</tr>";
while($row = mysql_fetch_array($sql))
{
echo "<tr height='20' data-order_id='".$row['po_id']."'>
<td align='center'><input type='radio' class='case' name='radio' value='".$row['po_id']."'></td>
<td align='center'>".$row['po_id']."</td>
<td align='center'>".$row['customer_name']."</td>
<td align='center'>".$row['quantity']."</td>
<td align='center'>".$row['price']."</td>
<td align='center'>".$row['status']."</td>
";
echo "</tr>";
}
echo "</table>";
echo "</div>";
}
}
?>
</body>
</html>
Can anyone please help me out??
To use the value in an anchor tag, you would need to invoke the GET method as follows:
Click here
But, since it is in a radio button, you might want to consider using an HTML form with submit button rather than an anchor tag.
If you want to call that value in html ahref then you should need some jquery too
First you should echo some value in your radio button
<input type="radio" name="buttonval" id="smallBtn" value="yourvalue"/>
Then in the change even of the radio button, You shall fire the event
<script type="text/javascript">
$(document).ready(function()
{
$("input[name=buttonval]").on('change', function(){
var $postID = $('input:radio[name=buttonval]:checked').val();
$postID = "="+$postID;
});
$.ajax ({
type: "GET",
url: "localhost/ajax/buttonvaluereceiver.php",
data: {"postID" : $postID }
});
});
</script>
and in the success event of the ajax call you will get the result of what buttonvaluereceiver.php file does
Update :
As you need to do instantly in radio button change I am updating my answer for you
Here is the html and script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name='frm' id='frm'>
<input type='radio' id='test' value='rad' name='rad'>
</form>
Your link :
<div id='link'></div>
<script>
$("input").change(function(){
var data = $("#frm").serialize();
Call();
});
function Call()
{
$.ajax({
type: "POST",
url : "result.php",
data : $("#frm").serialize(),
success : function(data)
{
console.log(data);
$("#link").html(data);
}
},"json");
}
</script>
Here is the php that creates your link
<?php
echo "<a href='url.php?id".$_POST['rad']."'>Click here</a>";
?>
You can change the url and values according to your need.
I am trying to write a script that will log how many likes(Facebook) a page has in Mysql using the Facebook api, ajax and mysql. But at the moment it isn't working. All variables are defined, it is connected to Mysql, and jQuery is embedded and i'm not getting and SQL or PHP errors. Can anyone see where i'm going wrong?
Source code:
index.php:
<?php
$sql=mysql_query("select * from likes ORDER BY id DESC LIMIT 9");
while($row=mysql_fetch_array($sql))
{
?>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script >
FB.init({
status: true,
cookie: true,
xfbml: true
});
FB.Event.subscribe('edge.create', function(response) {
alert(response);
if (response == "http://fbquote.me/like.php?id=<?php print $row['id']; ?>") {
$.ajax({
type: "POST",
url: "popular/ajax_pop.php",
data: "id=<?php print $row['id']; ?>"
cache: false,
});
}
});
</script>
<br /> <table style="width: 90%; height: 4px;" class="style11115" align="center">
<tr>
<td style="width: 68px; height: 23px;" class="style11111 " valign="top"><div id="fb-root"></div><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http://fbquote.me/like.php?id=<?php print $row['id']; ?>" send="false" layout="button_count" show_faces="true" font=""></fb:like></td>
<td style="height: 23px" class="style11113" valign="top"><?php print $row['like']; ?></td>
</tr>
</table>
<?php } ?>
alax_pop.php:
<?php
include_once("../scripts/config.php");
$like = mysql_real_escape_string($GET_['id']);
$current_pop = mysql_query("SELECT pop FROM likes WHERE id=$like") or die ("Query failed: " . mysql_error());
$pop = $current_pop + 1;
$update = mysql_query("UPDATE like SET pop = ".$pop." WHERE id = ".$like."") or die ("Query failed: " . mysql_error());
;
?>
Well, there are lots of issues in the code above:
Your logic is totally wrong where you are including EVERYTHING inside the loop!
You are including the same div "id" multiple of times (9 times according to your Mysql query)
Including the FB JS library multiple of times (same thing for the JS initializing snippet)
You are missing the APP ID parameter
You are building 9 tables (I'm not sure if this is intended too!)
You are once again including the FB code a couple of times in the table!
Check #zzarbi answer for your ajax backend page!
Now a solution to your code issues?
Do more effort on learning the basics of PHP, HTML and Javascript.
Move your Facebook and table code outside the loop.
Something like this will get you started:
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script >
FB.init({
status: true,
cookie: true,
xfbml: true
});
FB.Event.subscribe('edge.create', function(response) {
$.ajax({
type: "POST",
url: "popular/ajax_pop.php",
data: "url=" + response
cache: false
});
});
</script>
<?php
$result=mysql_query("select * from likes ORDER BY id DESC LIMIT 9");
if($result) {
?>
<table style="width: 90%; height: 4px;" class="style11115" align="center">
<?php while($row=mysql_fetch_array($result)) { ?>
<tr>
<td style="width: 68px; height: 23px;" class="style11111 " valign="top">
<fb:like href="http://fbquote.me/like.php?id=<?php print $row['id']; ?>" send="false" layout="button_count" show_faces="true" font=""></fb:like>
</td>
<td style="height: 23px" class="style11113" valign="top">
<?php print $row['like']; ?>
</td>
</tr>
<?php } ?>
</table>
<?php } ?>
In your ajax url, read the url and extract the ID from it.
You have two errors:
First you are using the method POST to send data with AJAX, but in your PHP code you are using GET to read it, plus the fact that you are using
$GET_['id']
instead of
$_GET['id']
So replace "$GET_['id']" by "$_POST['id']".
Secondly you are updating the table "like" instead of "likes"
Edit:
Replace in alax_pop.php:
$like = mysql_real_escape_string($GET_['id']);
by
$like = mysql_real_escape_string($_POST['id']);