I want to display a record from a database in a table with checkboxes in every row. That checkboxes will determine if the user wants to delete that specific row if it will be checked. I was able to display the data from the DB but when i press the delete button nothing happen. Im not sure but i think the error is in my deleting part of the code but i could be wrong. Im not sure. Anyway, here is the code, i just remove some lines
<?php
$link = mysql_connect("localhost","root", "123");
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db= mysql_select_db("abc");
if(!$db) {
die("Unable to select database");
}
$search = $_POST['search'];
$searchbox = $_POST['searchbox'];
$query = ("SELECT $search FROM table where $search = '$searchbox'");
$result=mysql_query($query);
if($result)
{
if(mysql_num_rows($result)<=0)
{
echo "<script type='text/javascript'>alert('The entry does not exist'); location.href = 'admin_home.php';</script>";
}
}
switch ($search)
{
case 'studentnumber':
$result = mysql_query("SELECT * FROM table WHERE $search = '$searchbox'");
if($result){
echo "<table class='hovertable'>
<tr>
<caption>Student Records</caption>
<th colspan='1'> Student Number</th>
<th colspan='8'> $searchbox</th>
</tr>
<tr>
<th>Delete</th>
<th>Student Number</th>
<th>College</th>
<th>Course</th>
<th>Status</th>
<th>Last Name</th>
<th>First Name</th>
<th>Middle Name</th>
<th>Address</th>
<th>Gender</th>
<th>Civil Status</th>
<th>Religion</th>
<th>Email Address</th>
<th>Month</th>
<th>Day</th>
<th>Year</th>
<th>Father's Name</th>
<th>Father's Occupation</th>
<th>Mother's Name</th>
<th>Mother's Name</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr onmouseover=\"this.style.backgroundColor='#ffff66';\" onmouseout=\"this.style.backgroundColor='#d4e3e5';\">";
?>
<td><input name="need_delete[<? echo $rows['id']; ?>]" type="checkbox" id="checkbox[<? echo $rows['id']; ?>]" value="<? echo $rows['id']; ?>"></td>
<?php
echo "<td>" . $row['studentnumber'] . "</td>";
echo "<td>" . $row['college'] . "</td>";
echo "<td>" . $row['course'] . "</td>";
echo "<td>" . $row['status'] . "</td>";
echo "<td>" . $row['lname'] . "</td>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $row['mname'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['gender'] . "</td>";
echo "<td>" . $row['civilstatus'] . "</td>";
echo "<td>" . $row['religion'] . "</td>";
echo "<td>" . $row['emailaddress'] . "</td>";
echo "<td>" . $row['month'] . "</td>";
echo "<td>" . $row['day'] . "</td>";
echo "<td>" . $row['year'] . "</td>";
echo "<td>" . $row['father'] . "</td>";
echo "<td>" . $row['fatheroccupation'] . "</td>";
echo "<td>" . $row['mother'] . "</td>";
echo "<td>" . $row['motheroccupation'] . "</td>";
}
echo "</table>";
echo "</div>";
}
break;
default:
echo "<script type='text/javascript'>alert('An error occur'); location.href = 'admin_home.php';</script>";
}
?>
<input name="delete" type="submit" id="delete" value="Delete">
<?php
// Check if delete button active, start this
if ( ! empty($_POST['delete'])) {
foreach ($_POST['need_delete'] as $id => $value) {
$sql = 'DELETE FROM students` WHERE id='.(int)$id;
mysql_query($sql);
}
echo "<script type='text/javascript'>alert('Record Successfully Deleted');location.href = 'admin_home.php';</script>";
exit();
}
mysql_close();
?>
Thanks in advance !!
You can use values on your checkbox, and use them as an array, so you will know which one has been checked.
<input type="checkbox" name="need_delete[$id]">
Doing this way, your $_POST['need_delete'] will receive an array with your ids as index, so you will be able to test and delete those registers.
It looks like your are attempting to access the wrong index in your $_POST array. See the following, which is taken from near the end of your PHP code.
if ( ! empty($_POST['delete'])) {
Should be
if ( ! empty($_POST['need_delete'])) {
I did something similar to this for displaying as well as appending/deleting records. The method I used was to loop through all the post vars in the PHP script, and searching for all information based on the first part of the key (if it matches something, use the number after that as an object id). Then loop through the produced array of the data that will be appended, what is deleted, what is edited and what is ignored.
If the object already exists as is and the checkbox isnt set, ignore
If the object already exists and data is different and the checkbox isn't set, update
If the object already exists and the checkbox is set, delete
If the object doesn't exist and the checkbox isn't set, create new row
If the object doesn't exist and the checkbox is set, ignore
Hope that helps
Have some code
PHP Block:
$mysqlData = array(); // Items to Update
$mysqlNewData = array(); // Items to Create
$Data = $_POST;
unset($Data['stuff']);
foreach($Data as $k => $v)
{
$type = substr($k, 0, 2);
if ($type == "nw")
{
$type = substr($k, 2, 2);
$ID = substr($k, 4);
$mysqlSubData = $mysqlNewData[$ID];
if (gettype($mysqlSubData) != "array")
$mysqlSubData = array();
if ($type == "sd")
$mysqlSubData['startdate'] = $v;
if ($type == "ed")
$mysqlSubData['enddate'] = $v;
if ($type == "dl")
if ($v == "on")
$mysqlSubData['delete'] = true;
$mysqlNewData[$ID] = $mysqlSubData;
} else {
$ID = substr($k, 2);
$mysqlSubData = $mysqlData[$ID];
if (gettype($mysqlSubData) != "array")
$mysqlSubData = array();
if ($type == "sd")
$mysqlSubData['startdate'] = $v;
if ($type == "ed")
$mysqlSubData['enddate'] = $v;
if ($type == "dl")
if ($v == "on")
$mysqlSubData['delete'] = true;
$mysqlData[$ID] = $mysqlSubData;
}
}
Table Block:
<? $occurences = $mysql->getEntries("occurences", "`TargetID`='{$Target['ID']}'"); ?>
<table cellpadding="0" cellspacing="5" border="0" width="900" id="timetable">
<tr>
<td>Delete</td>
<td>Start Date</td>
<td>End Date</td>
</tr>
<? foreach($occurences as $occurence) { ?>
<? $ID = $occurence['ID']; ?>
<tr>
<td>
<input type="checkbox" name="dl<?=$ID?>" value="on" />
</td>
<td>
<input type="text" name="sd<?=$ID?>" id="sd<?=$ID?>" value="<?=$occurence['startdate']?>" style="width: 100px" />
<img src="/scripts/cal.gif" width="16" height="16" border="0" alt="Pick a date">
</td>
<td>
<input type="text" name="ed<?=$ID?>" id="ed<?=$ID?>" value="<?=$occurence['enddate']?>" style="width: 100px" />
<img src="/scripts/cal.gif" width="16" height="16" border="0" alt="Pick a date">
</td>
<td>
</td>
</tr>
<? } ?>
</table>
Add Another
<div style="text-align: center">
<input type="image" src="/images/button_save.png" value="Save" border="0" />
<img src="/images/button_cancel.png" alt="Cancel" border="0" />
</div>
</form>
<script type="text/javascript">
var TableRowExtras = 0;
function AddOccurence()
{
TableRowExtras++;
var da = new Date();
var t = document.getElementById('timetable');
var row = t.insertRow(t.rows.length);
var cell = row.insertCell(0);
var element = document.createElement('input');
element.name = 'nwdl' + TableRowExtras;
element.type = 'checkbox';
element.value = 'on';
cell.appendChild(element);
cell = row.insertCell(1);
element = document.createElement('input');
element.type = 'text';
element.name = 'nwsd' + TableRowExtras;
element.id = 'nwsd' + TableRowExtras;
element.value = da.getFullYear() + '-' + (da.getMonth() + 1) + '-' + da.getDate();
element.style.width = '100px';
cell.appendChild(element);
cell.innerHTML = cell.innerHTML + " ";
element = document.createElement('a');
element.href = "javascript:NewCssCal('nwsd" + TableRowExtras + "','yyyyMMdd','arrow')";
var element2 = document.createElement('img');
element2.src = '/scripts/cal.gif';
element2.width = '16';
element2.height = '16';
element2.border = '0';
element2.alt = 'Pick a date';
element.appendChild(element2);
cell.appendChild(element);
cell = row.insertCell(2);
element = document.createElement('input');
element.type = 'text';
element.name = 'nwed' + TableRowExtras;
element.id = 'nwed' + TableRowExtras;
element.style.width = '100px';
cell.appendChild(element);
cell.innerHTML = cell.innerHTML + " ";
element = document.createElement('a');
element.href = "javascript:NewCssCal('nwed" + TableRowExtras + "','yyyyMMdd','arrow')";
element2 = document.createElement('img');
element2.src = '/scripts/cal.gif';
element2.width = '16';
element2.height = '16';
element2.border = '0';
element2.alt = 'Pick a date';
element.appendChild(element2);
cell.appendChild(element);
}
</script>
Write a JavaScript function when a particular check box is checked or unchecked and store the ids in a comma separated list as a hidden variable then after the page is posted u can get id's of fields you want to delete and split the variable using "Explode" to remove comma.
Related
Please refer to the image. I want the value of the button pressed which is the id of the student in the database. How do I know which button is pressed by the user?
The problem is that name of all the inputs is same.
<form method="post" name="data">
<table style="overflow-x: auto; display: block; white-space: nowrap; max-height: 450px; max-width: 1100px;"
class="table table-striped">
<tr>
<th>ID</th>
<th>Student Name</th>
<th>Address</th>
<th>Contact No.</th>
<th>Email</th>
<th colspan="4">Accept / Reject</th>
</tr>
<?php
$query = "SELECT StudentID,StudentName,Address,ContactNo,Email FROM Student WHERE Accepted=0";
$mysqli = connect();
//Get result
$result = $mysqli->query($query) or die($mysqli->error . " " . __LINE__); //__LINE__ shows the line no. we are getting the error at
if ($result->num_rows > 0) {
//Loop through results
while ($row = mysqli_fetch_array($result)) {
//Display customer info
$output = "<tr>";
$output .= "<td>" . $row['StudentID'] . "</td>";
$output .= "<td>" . $row['StudentName'] . "</td>";
$output .= "<td >" . $row['Address'] . "</td>";
$output .= "<td >" . $row['ContactNo'] . "</td>";
$output .= "<td >" . $row['Email'] . "</td>";
$output .= "<td><input type='hidden' name='Yes" . $row['StudentID'] . "' value='" . $row['StudentID'] . "' ></td>";
$output .= "<td><input type='submit' value='yes' class='btn-success' style='border:none;'></td>";
$output .= "<td><input type='hidden' name='No' value='" . $row['StudentID'] . "' ></td>";
$output .= "<td><input type='submit' value='No' class='btn-link' style='border:none;' ></td>";;
$output .= "</tr>";
echo $output;
}
echo "</table>";
} else
echo "No pending request found";
?>
</table>
</form>
If you'll have multiple submit buttons (one per each loop of the foreach) all you'd need is to pass a unique value for the button to identify which one you pressed. One simple way to do it is to pass both the yes/no answer and the studentID. For instance:
<input type="submit" name="response" value="yes|<?php echo $row['studentID']; ?>" class="btn-success" style="border:none;">
Then, when processing the form you take the value received in $_POST['response'], explode it at the pipe and you get the yes/no answer and the student ID:
$verdict = explode("|", $_POST['response']);
$yay_or_nay = $verdict[0];
$whom = $verdict[1];
then you can do whatever it is that you need to do with $yay_or_nay and $whom
The problem is that name of all the inputs is same.
Give them unique values, and use a <button> element so that the display label is not the same as the value.
<button type='submit' value='No-UNIQUE-ID' class='btn-link' style='border:none;'>
No
</button>
I had a similar issue and had to use JS/jQuery
$(".myClass").bind("click", function() {
var id = event.target.id;
window.location.href = "myPage?id="+id;
});
I actually had a similar issue. The way I solved it was by having two radio buttons on each row with the "yes" or "no" part stored in the value. They are separated by a delimiter from the other value (your StudentID). A submit button below the table then lets the user submit the responses in bulk.
Your code would look something like this:
<form method="post" name="data">
<table style="overflow-x: auto; display: block; white-space: nowrap; max-height: 450px; max-width: 1100px;"
class="table table-striped">
<tr>
<th>ID</th>
<th>Student Name</th>
<th>Address</th>
<th>Contact No.</th>
<th>Email</th>
<th colspan="4">Accept / Reject</th>
</tr>
<?php
$query = "SELECT StudentID,StudentName,Address,ContactNo,Email FROM Student WHERE Accepted=0";
$mysqli = connect();
//Get result
$result = $mysqli->query($query) or die($mysqli->error . " " . __LINE__); //__LINE__ shows the line no. we are getting the error at
$count = $result->num_rows;
if ($result->num_rows > 0) {
//Loop through results
while ($row = mysqli_fetch_array($result)) {
//Display customer info
$output = "<tr>";
$output .= "<td>" . $row['StudentID'] . "</td>";
$output .= "<td>" . $row['StudentName'] . "</td>";
$output .= "<td >" . $row['Address'] . "</td>";
$output .= "<td >" . $row['ContactNo'] . "</td>";
$output .= "<td >" . $row['Email'] . "</td>";
$output .= "<td><input type='radio' name='radio" . $count . "' value='" . $row['StudentID'] . "|accept' ></td>";
$output .= "<td><input type='radio' name='radio" . $count . "' value='" . $row['StudentID'] . "|reject' ></td>";
$output .= "</tr>";
echo $output;
$count += 1;
}
echo "</table>";
echo "<input type='submit' name='submit' value='submit'>";
} else
echo "No pending request found";
?>
</table>
</form>
Then you get the values from whatever radio btn was selected and do the rest of your code:
if(isset($_POST['submit'])) {
for($x = 0; $x < $count; $x++) {
if(isset($_POST['radio' . $x])) {
$values = explode('|', $_POST['radio' . $x]);
$id = $values[0];
$status = $values[1];
//Do stuff with each result
}
}
}
When I put a term in search-box, my pagination is not working although it gives me a perfect result.
For an eg. If I type "Laptops" it gives me records having laptops,but my pagination is not going with the flow. I don't know where I have missed something.
Here is my code:
Search-Box:
<form action="" method="GET">
Search: <input type="text" name="term" value="<?php echo #$_REQUEST['term']; ?>" /><br />
<input type="submit" value="Submit" />
</form>
To Display data:
<table id="employee-grid" width="auto" cellpadding="1" cellspacing="1" border="1" class="table table-hover">
<?php
include_once '../storescripts/connect_to_mysql.php';
$num_rec_per_page = 5;
if (isset($_GET["page"])) {
$page = $_GET["page"];
} else {
$page = 1;
};
$start_from = ($page - 1) * $num_rec_per_page;
$sql = "SELECT * FROM products WHERE status='Active' LIMIT $start_from, $num_rec_per_page";
?>
<thead>
<tr class="success">
<th>Id</th>
<th>Product Image</th>
<th>Product Name</th>
<th>Price</th>
<th>Status</th>
<th>Quantity</th>
<th>Details</th>
<!--<th>Category</th>
<th>Subcategory</th>-->
<th>Date Added</th>
<th colspan="2">Functions</th>
</tr>
</thead>
<?php
if (!empty($_REQUEST['term']))
{
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM products WHERE product_name LIKE '%" . $term . "%' or status LIKE '%" . $term . "' or quantity LIKE '%" . $term . "' or details LIKE '%" . $term . "' or price LIKE '%" . $term . "' or details LIKE '%" . $term . "'";
}
$r_query = mysql_query($sql);
if ($r_query > 1)
{
while ($row = mysql_fetch_array($r_query))
{
echo "<tr bgcolor=''>";
echo "<td width='5%'>" . $row['id'] . "</td>";?>
<td width="10%"><img style='border:#666 1px solid;' width='70' src="<?php echo $row["productimage"]; ?>" alt="" /></td>
<?php echo "<td width='20%'>" . $row['product_name'] . "</td>";
echo "<td width='5%'>" . $row['price'] . "</td>";
echo "<td width='5%'>" . $row['status'] . "</td>";
echo "<td width='5%'>" . $row['quantity'] . "</td>";
echo "<td width='19%'>" . $row['details'] . "</td>";
// echo "<td>" . $row['category'] . "</td>";
// echo "<td>" . $row['subcategory'] . "</td>";
echo "<td width='10%'>" . $row['date_added'] . "</td>";
echo "<td><a href='product_listing_edit.php?id=" . $row['id'] . "'>Edit</a></td>";?>
<td><a href="#" class="delete" onclick="dialogbox(<?php echo $row['id']; ?>)" >Delete</a>
<?php
//echo "<td><a name='delete' href='product_listing_delete.php?id=" . $row['id'] . "' onclick='return show_confirm();' >Delete</a></td><tr>";
echo "</tr>";
}
}
else {
echo "Nothing should be displayed";
}
?>
</table>
Pagination Code:
<?php
//Pagination code starts here
$sql = "SELECT * FROM products";
$rs_result = mysql_query($sql); //run the query
$total_records = mysql_num_rows($rs_result); //count number of records
$total_pages = ceil($total_records / $num_rec_per_page);
echo "<a href='product_listing.php?page=1'>".'|<'."</a> "; // Goto 1st page
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='product_listing.php?page=".$i."'>".$i."</a> ";
};
echo "<a href='product_listing.php?page=$total_pages'>".'>|'."</a> "; // Goto last page
?>
You have to use r_query to find no of rows in pagination. Now you are finding the total number of rows in the table
<?php
//Pagination code starts here
$total_records = mysql_num_rows($r_query); //count number of records
$total_pages = ceil($total_records / $num_rec_per_page);
echo "<a href='product_listing.php?page=1'>".'|<'."</a> "; // Goto 1st page
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='product_listing.php?page=".$i."'>".$i."</a> ";
};
echo "<a href='product_listing.php?page=$total_pages'>".'>|'."</a> "; // Goto last page
?>
I'm retrieving a table from database as result of a search action, but when I try to display the result I see the table and the data, but the image returned in each row is not render, I think my problem is in the $('#search').html(data), I'm not sure please someone knows what is the problem?
this is the result
http://s9.postimg.org/mro5qn46n/search_result.jpg
****This is the search page, where result table is displayed****
<table align="center">
<tr>
<td>
<label for="criteria">Select Criteria</label>
</td>
<td>
<select name="select" id="criteria">
<option selected="true" style="display:none;"></option>
<option value="value1">name</option>
<option value="value2">apartment</option>
</select>
</td>
<td>
<input type="text" name="value" size="40" maxlength="60" id="value"\>
</td>
</tr>
<tr>
<td>
<input name="name-submit" type="button" id="submit" value="Search"\>
</td>
</tr>
<tr>
<td >
<div id="search"></div>
</td>
</tr>
</table>
<script type="text/javascript" src="../js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$('#submit').click(function(){
var criteria = $("#criteria option:selected").text();
var value = $("#value").val();
$.post("search_r.php",{criteria:criteria,value:value},function(data){
$('#search').html(data);
});
});
</script>
****This is the Page that calls $.post() in the main seach page ****
<?php
$criteria = $_POST['criteria'];
$value = $_POST['value'];
$con = mysqli_connect("localhost","root","");
mysqli_select_db($con,"gables");
$query = "SELECT * FROM residents WHERE $criteria = '$value'";
$result = mysqli_query($con,$query);
echo "<table border='1'>
<tr>
<th>Id</th>
<th>Name</th>
<th>Last Name</th>
<th>Apartment</th>
<th>Parking</th>
<th>Phone1</th>
<th>Phone2</th>
<th>image</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['0'] . "</td>";
echo "<td>" . $row['1'] . "</td>";
echo "<td>" . $row['2'] . "</td>";
echo "<td>" . $row['3'] . "</td>";
echo "<td>" . $row['4'] . "</td>";
echo "<td>" . $row['5'] . "</td>";
echo "<td>" . $row['6'] . "</td>";
echo "<td><img src=get_image.php?id=".$row['0']." width=160 height=120/></td>";
echo "</tr>";
}
echo "</table>";
?>
***Here the get_image.php****
<?php
$con = mysqli_connect("localhost","root","");
mysqli_select_db($con,"gables");
$id = $_GET['id'];
$query = "SELECT * FROM residents WHERE id='$id'";
$result = mysqli_query($con,$query);
if($result)
$picture = mysqli_fetch_array($result);
header('Content-Type: image/jpg');
echo $picture['11'];
?>
You can chage the get_image.php file as this. Then this work will work.
<?php
function get_image($id){
$con = mysqli_connect("localhost","root","");
mysqli_select_db($con,"gables");
$query = "SELECT * FROM residents WHERE id='$id'";
$result = mysqli_query($con,$query);
if($result)
$picture = mysqli_fetch_array($result);
return $picture['11'];
}
?>
Then use require_once(); function and in image src like this.echo "<td><img src='".get_image($row['0'])."' width=160 height=120/></td>";. In your code check how the src path will print and it will be print like as echo string, not as a execute the file.
echo
"<table border='1'>
<tr>
<th>Id</th>
<th>Name</th>
<th>Last Name</th>
<th>Apartment</th>
<th>Parking</th>
<th>Phone1</th>
<th>Phone2</th>
<th>image</th>
</tr>";
require_once('search_r.php');
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['0'] . "</td>";
echo "<td>" . $row['1'] . "</td>";
echo "<td>" . $row['2'] . "</td>";
echo "<td>" . $row['3'] . "</td>";
echo "<td>" . $row['4'] . "</td>";
echo "<td>" . $row['5'] . "</td>";
echo "<td>" . $row['6'] . "</td>";
echo "<td><img src='".get_image($row['0'])."' width=160 height=120/></td>";
echo "</tr>";
}
echo "</table>";
have a database with an id question and choiecs and an answer(multiple choice) i want to display the all of it which is in the database with a checkbox to the left of it. at the end i will have a submit button and all the questions checked i want to display under the table. My attempt. there has to be a more simple way. Thanks!
$result = mysqli_query($con,"SELECT id,question,choiceA,choiceB,choiceC,choiceD,answer FROM q_and_a ");
echo "<table border='1'>
<tr>
<th>Add</th>
<th>#</th>
<th>Question</th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>Answer</th>
</tr>";
echo '<form method="POST" action="makeTest.php">';
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo '<td><input type="checkbox" name="questions[]" value="yes"></td>';
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['question'] . "</td>";
echo "<td>" . $row['choiceA'] . "</td>";
echo "<td>" . $row['choiceB'] . "</td>";
echo "<td>" . $row['choiceC'] . "</td>";
echo "<td>" . $row['choiceD'] . "</td>";
echo "<td>" . $row['answer'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
I'd suggest throwing jQuery into the mix.
Keep HTML out of your PHP code and just use it to query the database.
Then use AJAX/JSON to update the DOM.
UPDATE - This has been tested (verified working), and a few bugs were fixed along the way.
ajax.php:
<?php
$action = $_POST["action"];
if ($action == "getQuestions") {
echo getQuestions();
}
function getQuestions() {
try {
$db = new PDO("mysql:host=localhost;charset=utf8", "root", "root");
$cmd = $db->prepare("
SELECT id, question , choiceA ,choiceB ,choiceC ,choiceD , answer
FROM pl2.questions;
");
$cmd->execute();
$rows = array();
while($r = $cmd->fetch(PDO::FETCH_ASSOC)) { $rows[] = $r; }
$json = json_encode($rows);
return($json);
} catch (PDOException $e) { echo $e->getMessage(); return; }
}
?>
questions.html
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script language="javascript">
var questionsJson = '';
$(document).ready(function() {
getQuestions();
});
function getQuestions() {
$.post('ajax.php', { action: 'getQuestions' }, function(data) {
questionsJson = data;
displayQuestions();
},'json');
}
function displayQuestions() {
var colAry = ['id', 'question', 'choiceA', 'choiceB', 'choiceC', 'choiceD', 'answer'];
for (var i = 0; i < questionsJson.length; i++) {
var q = questionsJson[i];
var row = '<tr><td><input type="checkbox" name="questions[]" value="yes"></td>';
for (var j = 0; j < colAry.length; j++) {
row += '<td>' + q[colAry[j]] + '</td>';
}
$('#mainTable').append(row + '</tr>');
}
}
</script>
</head>
<body>
<table id="mainTable" border="1">
<tr>
<th>Add</th>
<th>#</th>
<th>Question</th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>Answer</th>
</tr>
</table>
</body>
</html>
I have a little problem regarding with deleting multiple records in my table. I used checkbox in order to delete them but it doesn't work. I don't know what would be the exact CODE for it.
Here is my PHP code
<?php
echo "<form action='#'>
<fieldset>
<input type='text' name='search' value='' id='searchtalents' placeholder='Search Keywords..' size='40'/>
</fieldset>
</form>";
echo "<form name='tmsform' method='POST' action=''>";
$sql = "SELECT * FROM talentinfo WHERE 1 LIMIT 10";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ({$sql}) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found";
exit;
}
echo"<div id='talentinfo'><table id='mr_database' name='myform' style='border:1px solid #fff;' cellspacing=0 cellpading='2' class='pretty'>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th>Mr Tracking Number</th>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>Address</th>
<th>Contact Number</th>
<th>School</th>
<th>Course</th>
<th>Year Graduated</th>
<th>Position Considered</th>
<th>Referred Location</th>
<th>Unit</th>
</tr>
</thead>";
$counter = 40000;
while ($row = mysql_fetch_assoc($result)) {
$filled = (($counter % 2) == 1) ? "style='background-color:#BCD9E1;'" : "" ;
$id = $row['talents_id'];
echo "<tbody><tr {$filled} class='tmsdel'>";
echo "<td><a href ='#' rel='#edit_talents{$counter}'><center><img src='img/edit.gif' width='25' height='21' title='Edit'></center></a></td>";
echo "<td><a href ='#' id=".$row['talents_id'].'&idelete=talents'." class='delete'><center><img src='img/delete.png' width='25' height='21' title='Delete'></center></a></td>";
echo "<td><input type='checkbox' name='checkbox[]' id='check".$row['talents_id']."' value='".$row['talents_id'].'&idelete=talents'."'/></td>";
echo "<td><a href='#' rel='#tracing_number{$counter}' style='text-decoration:none; font-weight:bold; color:#444;'>" . $row ['mr_tracking_number'] . "</a></td>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['middlename'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['contact_number'] . "</td>";
echo "<td>" . $row['school'] . "</td>";
echo "<td>" . $row['course'] . "</td>";
echo "<td>" . $row['year_graduated'] . "</td>";
echo "<td>" . $row['position_considered'] . "</td>";
echo "<td>" . $row['referred_location'] . "</td>";
echo "<td>" . $row['unit'] . "</td>";
echo "</tr></tbody>";
?>
And here is my Javascript
$(function(){
$(document).ready(function(){
});
$("#delete-all").click(function(){
$("#mr_database").remove();
$.ajax({
url: "modules/delete-all.php",
type: "get",
async: false,
data: "check"
});
});
});
Please follow steps:
First you need to apply any class name to your all checkboxes.
Call function on button click for delete then
var allVals = '';
$("#delete-all").click(function(){
$('.checkboxclass :checked').each(function() {
allVals = allVals + $(this).val() + ',';
});
}
Then you need to pass allVals variables in ajax and post to .php file
Like: data: 'ids=' + allVals in $.ajax
In last you can get this variable in php file and do delete process on it.
Like: $ids = explode(',', $_REQUEST['ids'); and use ids in mysql query
Hope this helps you.
Rather simple answer since what i am seeing here is a script to view the table and delete the html in the browser but not the data on the server.
You need to write the modules/delete-all.php script mentioned here:
url: "modules/delete-all.php"
which should contain the " delete * FROM talentinfo " SQL Query.
This however will seamlessly delete all table contents. So you might want to do a prompt:
$("#delete-all").click(function(){
Check = confirm("Do you really want to delete ALL DATA ? (Hint: there is no undo)");
if (Check == true) {
$("#mr_database").remove();
$.ajax({
url: "modules/delete-all.php",
type: "get",
async: false,
data: "check"
});
}
});
The delete_all.php should delete all, so just do:
<?php
$sql = "delete * FROM talentinfo ";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ({$sql}) from DB: " . mysql_error();
exit;
} else {
print "ok";
}
?>