how to select rows from a database and display them with checkboxes? - php

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>

Related

pass a jquery variable to php code

this is my php code
require 'functions/connection.php';
$conn = Connect();
$result = mysqli_query($conn,"SELECT * FROM employee ORDER BY id asc");
echo "
<tr>
<th>Id</th>
<th>First name</th>
<th>Last name</th>
<th>Salary</th>
<th>Start Date</th>
<th>Department</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
echo "<td>" . $row['salary'] . "</td>";
echo "<td>" . $row['startdate'] . "</td>";
echo "<td>" . $row['department'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($conn);
?>
and this is my jquery code
<script>
$('.sort').click(function(){
var value = $(this).attr('data-val');
var field_name = $(this).attr('data-field');
$.post( "getEmployee.php", {value:value, field_name:field_name}, function( data ) {
$('.responstable').html(data);
});
if(value=="asc"){
$x="asc";
}
else{
$x="desc";
}
});
</script>
i would like to pass the variable x from the jquery code to the php so i can order my database asc or desc like this:
result = mysqli_query($conn,"SELECT * FROM employee ORDER BY id $x");
In your jquery code
$.post( "getEmployee.php", { sort: "asc" } );
In your php code using
$_POST['sort']

How to retrieve row from a html table on mouse click in PHP?

I am displaying some records in an HTML table using PHP. I am trying to make it so that when I click on a row, I can store the itemID (that has been clicked on) in a variable. For some reason, when I click on the row I want, the alert in JavaScript just doesn't work nor does it happen. Am I missing something trivial?
<?php
$con=mysqli_connect("localhost","root","mypassword","myDB");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "<font color = 'darkgreen'> Connected to database. </font> <br>";
$result = mysqli_query($con,"SELECT * FROM Inventory");
echo "<table border='1'>
<tr>
<th>Item ID</th>
<th>Item Name</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['itemID'] . "</td>";
echo "<td>" . $row['itemName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<script type="text/javascript">
$("tr.table").click(function() {
var tableData = $(this).children("td").map(function() {
return $(this).text();
}).get();
alert("Your data is: " + $.trim(tableData[0]) + " , " + $.trim(tableData[1]));
});
</script>
<?php
$con=mysqli_connect("localhost","root","mypassword","myDB");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "<h3 style='color: darkgreen;'> Connected to database. </h3> <br />";
$result = mysqli_query($con,"SELECT * FROM Inventory");
echo "<table border='1'>
<tr>
<th>Item ID</th>
<th>Item Name</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td class='item-id'>" . $row['itemID'] . "</td>";
echo "<td class='item-name'>" . $row['itemName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script type="text/javascript">
$("tr").click(function() {
var id = $(this).find('.item-id').text();
var name = $(this).find('.item-name').text();
alert("Your data is: " + $.trim(id) + " , " + $.trim(name));
});
</script>
echo "<tr onclick='showAlert($row['itemID'],$row['itemName']);'>";
please write in your table and create java script function to show alert
<script>
function showAlert(TxtItemid,txtItemName){
alert("Your data is: " + TxtItemid + " , " + txtItemName));
}
</script>
this is one of the way to alert.Please have try on this. This will work for you. It is working in my case.

PHP How to Delete Multiple Records using Checkbox

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";
}
?>

click row to fill textboxes in php - array vs ajax

I have a table coded in php which pulls in data from mysql database and displays it in a html table . Now when i click on a row I need certain textboxes to be filled.
What is the best approach for this: is it using an array or ajax,html and php,
<?php
$default = "<img src='http://localhost/on.png' width='24' height='24'/>";
$default1 = "<img src='http://localhost/of.png' width='24' height='24'/>";
$con = mysql_connect("*****","******","******");
if (!$con){
die("Can not connect: " . mysql_error());
}
mysql_select_db ("*****",$con);
$sql= "select act.*
from audit_activity as act
inner join (
select user_id, max(timestamp) as max_ts
from activity
group by user_id) as a on act.user_id=a.user_id and act.timestamp=a.max_ts";
$mydata = mysql_query($sql,$con);
echo "<table id='tfhover',table border=0>
<tr>
<th>Users</th>
<th>Status<th>
</tr>";
while($record = mysql_fetch_array($mydata)){
echo "<tr>";
echo "<td>" . $record['user_id'] . "</td>";
if (strtolower(trim($record['activity']))!=strtolower('LOGIN')){
echo "<td>" . $default1 . "</td>";
}else{
echo "<td>" . $default . "</td>";
}
echo "</tr>";
}
echo "</table>";
;
mysql_close($con);
?>
<html>
<script type="text/javascript">
window.onload=function(){
var tfrow = document.getElementById('tfhover').rows.length;
var tbRow=[];
for (var i=1;i<tfrow;i++) {
tbRow[i]=document.getElementById('tfhover').rows[i];
tbRow[i].onmouseover = function(){
this.style.backgroundColor = '#ffffff';
};
tbRow[i].onmouseout = function() {
this.style.backgroundColor = '#d4e3e5';
};
}
};
</script>
<head>
</head>
<body>
Total exams taken : <br>
<input type="text" name="fname"/>
</body>
</html>

Deleting a row from a database table using checkbox

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.

Categories