Front end mysql view, delete entry with checkbox? - php

I'm building off of a question I had asked and resolved earlier: front end mysql, deleting a row
Basically, I've got a front end where users can view a DB. Instead of having a delete button next to each row, I'd like to have a checkboxes that can be selected for multiple rows. Then, the user only clicks a single delete button and all the selected rows are removed. I don't know much php and mysql at all, so I'm not sure how to approach the code that I already have.
Currently, the onclick calls a delete function. Can anyone help?
I've got a php file that outputs the html for the mysql data into a long strong, the part I need to change is:
$display_string .= "<td class='blank'><input type=\"button\" VALUE=\"Delete\" onclick='delFunction(" . $row['ID'] . ")' ></td>";
Next my delete function:
function delFunction(ID){
// confirm delete
if (!confirm(\"Are you sure you want to delete?\")) return false;
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject(\"Msxml2.XMLHTTP\");
} catch (e) {
try{
ajaxRequest = new ActiveXObject(\"Microsoft.XMLHTTP\");
} catch (e){
// Something went wrong
alert(\"Your browser broke!\");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var queryString = \"?ID=\" + ID
ajaxRequest.open(\"GET\", \"delete_row.php\" + queryString, true);
ajaxRequest.send(null);
}

To my understanding of your problem, I am posting some codes for both front and back ends
Front-End Sample Code
<body>
<form action="delete.php" method="post">
<input type="checkbox" name="del_chk[]">Item1
<input type="checkbox" name="del_chk[]">Item2
<input type="checkbox" name="del_chk[]">Item3
<input type="checkbox" name="del_chk[]">Item4
.
.
<input type="submit">
</form>
................
Your back-end code would now be...
<?php
if(isset($_POST['del_chk'])){
$chkbox=$_POST['del_chk'];
foreach($chkbox as $key=>$value) {
//Now you can get your value and use it in mysql delete statements
//for example
$del_query="DELETE FROM `yourtable` WHERE `pri_key`=$value;";
if(mysql_query($del_query)) {
echo "Successful Deletion of: ".$value;
}
else
{
echo "Unsuccessful Deletion of: ".$value;
}
} //end foreach
}
?>
I don't know much of ajax. but you can use ajax to call this page..

Related

JAVASCRIPT: OK button proceed to another .php form

I have a basic javascript code for my saving entry.
Scenario:
I have two forms, the first form,[view_netbldg.php], is for my data entry then when the user click the "ADD" button it will proceed to the next form [save_netbldg.php]. So in my save_netbldg.php form there is a if else condition where the code will know first if the variable of $bldgName or $netName are empty. Everything is okay, but my concern is this when the code detect either of the two variables are empty the code below I'm using will be executed.
Here's my code:
if($bldgName == "" || $netName == "")
{
echo "<script type='text/javascript'>\n";
echo "alert('Please complete the fields for Building Name or Network Name');\n";
echo "</script>";
header("location:view_netbdlg.php");
}
*The result of the program is, its not displaying the alert instead it will jump to the header
The correct way is, if the $bldgName == "" || $netName == "" == true** an alert will display and when the user click the ok button it will proceed to the next form which is "view_netbdlg.php". I don't need a confirmation message here because its only an error message something like that.
Advance thank you.
You are confusing php with javascript, You can solve this by
if($bldgName == "" || $netName == "")
{
echo "<script type='text/javascript'>\n";
echo "alert('Please complete the fields for Building Name or Network Name');\n";
echo "window.location='view_netbdlg.php';\n";
echo "</script>";
}
That happens because when the document loads, it stops when it finds a script tag.
In your case, you're trying to echo data in an undetermined part of the document, when it is already loaded.
Here's my solution:
PHP File (test.php):
<?php
if(!isset($_POST['bldgName']) || !isset($_POST['netName']) {
die("false"); //returns false if the values are NOT set
} else {
die("true"); //returns true if the values are set
}
?>
In your file (file.html):
<form method="post" action="test.php" id="formtest">
<input type="text" name="bldgName" />
<input type="text" name="netName" />
</form>
<script type="text/javascript">
if(getAjaxResponse(document.getElementById("formtest") == "true") {
alert("Please complete the fields for Building Name or Network Name");
window.navigate("view_netbdlg.php");
}
function getAjaxResponse(frm){
var elem = frm.elements;
var params = "";
url = form.action;
for(var i = 0; i < elem.length; i++){
if (elem[i].tagName == "SELECT"){
params += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) + "&";
} else {
params += elem[i].name + "=" + encodeURIComponent(elem[i].value) + "&";
}
}
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST",url,false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
return xmlhttp.responseText;
}
</script>
you have written the the code under script and never invoked that script
for that you have to use functions and call the function manually...
For more about function call refer
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Call
You could try:
if($bldgName == "" || $netName == ""){
header('Refresh: 10; URL=your url');#10 second delay
echo "Please complete the fields for Building Name or Network Name";
exit;#make sure rest of page doesn't render!
}

Load external page into div after clicking on item from php list

I know, I know. From the title up above, you are probably wondering what in in the world I am asking. Let me try and break this down a little easier because I am stuck and cannot figure this out. So here goes..............
I have a place on my site where a user can look at a list of news items that have been posted. All of the news items are listed in a MYSQL database and is retrieved and displayed on the page using PhP, like this:
$sql_list = "SELECT * FROM LatestMusic WHERE active = 'y' ORDER BY lm_id DESC";
$sql_list_result = mysql_query($sql_list,$connection) or die ('Could not select the List of Latest Music Entries');
$bgc = "FFC6C6";
while($list_data = mysql_fetch_array($sql_list_result)){
if ($bgc == "FFC6C6") {
$bgc = "FFFFFF";
} else {
$bgc = "FFC6C6";
}
print "<tr bgcolor=\"#" .$bgc. "\">";
print "<td align=\"center\" width=\"44\">";
print "<img src=\"/images/b_edit.png\" border=\"0\">";
print "</td>";
print "<td align=\"center\" width=\"63\">";
print "<img src=\"/images/b_drop.png\" border=\"0\">";
print "</td>";
print "<td align=\"left\" style=\"padding-left: 15px;\">";
echo $list_data[1];
print "</td>";
print "</tr>";
}
That part I get. From there, when the user click on anyone of the entries listed from the database, I need an external PHP page to load inside of a DIV on the same page without loading. I am using this coding in the header on the same page in order to achieve such a task:
<script>
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "YSMhome_LMeditform.php", true);
xmlhttp.send();
}
</script>
I can get the external page to load just fine into the DIV without the page reloading. The problem I'm having is this: The page that loads needs to be a form with form fields. When a user clicks on an entry in the list from the database, I need to pass a variable from the list (letting me know which entry they clicked on) into the external page that is loading in the DIV so that I can pre-populate the form fields with the data being sent. That is the part I cannot figure out.
If anyone can assist me with this, it would be greatly appreciated. I am new to AJAX (this is my first attempt with it), but I am willing to learn what I need to in order to get this to work.
When you call your ajax function, you need to pass it the relevant information. In your example, you should change:
onclick=\"loadXMLDoc()\"
to something like (assuming that $list_data[0] is an integer for simplicity):
onclick=\"loadXMLDoc({$list_data[0]})\"
Then in javascript, your function definition would look something like:
function loadXMLDoc(id)
and later on, you could change the url that is called to something like:
"YSMhome_LMeditform.php?id=" + id
Then you would have the ID available in "YSMhome_LMeditform.php as $_GET['id'].

PHP if (isset($_POST['uname'])) not doing anything?

I have two pages. 1st page has two text forms like so:
<form name="NameForm">
Name: <input type = "text" name = "uname">
Location: <input type = "text" name = "ulocation">
<button type="button" onClick="MakeRequest()"">Save</button>
</form>
It pushes the information into page number two using javascript like so (note this is on the same page as the code above):
<script>
function MakeRequest()
{
// get values
var uname = document.NameForm.uname.value;
var ulocation = document.NameForm.ulocation.value;
// validation stuff here that detects browser
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
var url = "location.php?uname=" + uname + "&ulocation=" + ulocation;
xmlhttp.open("POST", url, true);
xmlhttp.send();
}
</script>
So the problem is this, the php scripts on the page that does all server communication is not reading and storing the variables from this post request into my database.(my other get methods that view items in the database works fine)
if (isset($_POST['uname']))
{
$name = $_POST['uname'];
$location = $_POST['ulocation']
}
then the query goes somehting like
//$table and the other undefined variables are the names of my table & columns
$query = "INSERT INTO $table ($tablename, $tablelocation) VALUES ('$name', '$location')";
Basically I'm trying to get that query to work. If i remove the If statement, it stores $name to the database but not $location.
EDIT:
I forgot to add
<div id="result">
</div>
You are sending a GET.
to send a POST try:
[edited] perform the functions that order
function XHR(){
if(typeof XMLHttpRequest !=="undefined"){
try{ return new XMLHttpRequest(); } catch (e){}
}
if(typeof ActiveXObject !=="undefined"){
try{ return new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){}
try{ return new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){}
}
return false;
}
function MakeRequest()
{
// get values
var uname = document.NameForm.uname.value;
var ulocation = document.NameForm.ulocation.value;
// validation stuff here that detects browser
var url = "location.php";
xmlhttp = XHR();//Fixed
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");//Fixed
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4) {
if(xmlhttp.status==200){
document.getElementById("result").innerHTML = xmlhttp.responseText;
} else {
document.getElementById("result").innerHTML = "ERROR:"+xmlhttp.status;
}
}
};
xmlhttp.send("uname=" + uname + "&ulocation=" + ulocation);
}
<form name="NameForm">
Name: <input type = "text" name = "uname">
Location: <input type = "text" name = "ulocation">
<button type="button" onClick="MakeRequest()"">Save</button>
</form>
Your missing a form method. In your case you wish:
<form name='NameForm" method="POST">
If this does not resolve your issue, then download and use firebug for firefox or chrome console to debug javascript errors.
There will be no output of errors in JS to the text. You will need to use a debug console.
perform an insert via html form
I would modify your HTML to:
<form name="NameForm" method="POST">
Name: <input type = "text" name = "uname">
Location: <input type = "text" name = "ulocation">
<button type="button" onClick="MakeRequest()"">Save</button>
<input type='submit' name='SubmitForm' value='SUBMIT THIS FORM'>
</form>
Then my PHP code:
<?php
if(isset($_POST['SubmitForm'])){
$Name = $_POST['uname'];
$Location = $_POST['ulocation'];
// Perform validation for these inputs, check if empty, set correctly ETC
$query = "INSERT INTO $table ($tablename, $tablelocation) VALUES ('$name', '$location')";
}
then call your Javascript function inside your PHP script; or perform an ajax/jquery call to run the insert without the need of a submit button

Click counter on a div using php

I know nothing about javascript, but I'm using javascript in a couple places on my site to make it look a little nicer. One of these places is where when a user clicks a div, it can open a nice looking popup with more information. However, I also want to save the number of clicks a div has.
I know how I could do this with php, and I've managed to find some javascript code that could increment a variable, but I don't think those two can be combined unless the js saves the var as a cookie, which I think could have some security flaws if I'm then reading the js variable back into the database.
The javascript code I have is
/*Click counter*/
var clicks = 0;
function count()
{
document.getElementById( "cc" ).value = ++clicks;
}
and I'm not sure of where to start with the php since I don't know the javascript. But querying the database to increment the column that stores the number of clicks will be simple. I just don't know how to tell php that a click has been made using javascript. I don't think it can be done in php, unless the link goes to a php file which handles all of this first and then redirects, which won't work in this case since the popup wouldn't be loaded in the new page.
Any ideas or pseudo-code to help?
You should use AJAX to update the server database if you want to keep the counter up to date on the server side.
Based on this tutorial, here's a quick example:
mydiv.phtml:
<?php $_GET['id']=isset($_GET['id'])?$_GET['id']:1; include 'count.php'; ?>
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
var clickerid = <?php echo $_GET['id'] ?>; //counter id allows easy implementation of other counters if desired
var clicks = <?php echo $clicks ?>;
var clickLock = false;
var maxClickRate = 1000; //maximum click rate in ms, so the server won't choke
//Browser Support Code
function count(){
if (clickLock) {
alert('you\'re clicking too fast!');
return;
}
clickLock=true;
setTimeout('clickLock=false;',maxClickRate);
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById('cc').innerHTML = ++clicks;
}
}
// Now pass clicks value to the
// server script.
var queryString = "?id=" + clickerid + "&update=true";
ajaxRequest.open("GET", "count.php" +
queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<div onclick='count()'>
<form name='myForm'>
<input type='button' value='clickOnDiv'/>
</form>
</div>
Clicks so far: <span id='cc'><?php echo $clicks; ?></span>
</body>
</html>
count.php:
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
if (!isset($_GET['update'])){
$stmt = $dbh->prepare('SELECT count
FROM clicks
WHERE id = :clickerid');
$stmt->bindValue(':clickerid', $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$clicks = $result['count'];
} else {
$stmt = $dbh->prepare('UPDATE clicks
SET count = count + 1
WHERE id = :clickerid');
$stmt->bindValue(':clickerid', $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
}
$dbh = null;
} catch (PDOException $e) {
print "PDO Exception.";
die();
}
?>
set_database.php:
<?php
try {
$dbh = new PDO('mysql:host=localhost', 'user', 'password');
$dbh->query('CREATE DATABASE test;');
$dbh->query('CREATE TABLE test.clicks (id INT KEY, count INT);');
$dbh->query('INSERT INTO test.clicks VALUES (1,0);');
$dbh = null;
} catch (PDOException $e) {
print "PDO Exception.";
die();
}
?>

PHP In ajax responseText take all the html cose instead of ONLY the echo passed trought PHP

Using that javascript ajax function I pass the content of a form, that contain
the dato value, to the PHP login.php than trought the echo pass back the content
(the insert form) that I want to be switched to the cancel form, using
the content respondText (that may take only the echo of the PHP).
BUT INSTEAD the responseText contain ALL the html code, with the old html
plus the cancella_form passed by the echo, that's also out of the div
with id=visibile.
Any ideas why? D:
//ajaxSubmit(dato)
function ajaxSubmit( url , divId , hideId ) {
//in setXmlHttpObject() I just control the user's browser
// and assign the right XmlHttp Object
var ajaxRequest = setXmlHttpObject();
var dato = 'nome='+document.getElementsByName('dato')[0].value;
ajaxRequest.open("POST", url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(dato);
ajaxRequest.onreadystatechange = function() {
//Comunication complete
if (ajaxRequest.readyState == 4 && ajaxRequest.status==200) {
//Comuncation succesfull
if(ajaxRequest.statusText === "OK"){
var str= ajaxRequest.responseText;//<<<HERE///////
$(str).replaceAll("#visibile");
}
//Comuncation failed
else{
var str= "ERROR: Ajax: "+ajaxRequest.responseText;
document.write(str);
}
}
}
}//FINE ajaxRequest();
<?php
include("prova_login_adv.php");
$conn= mysql_connect('localhost','root','');
mysql_select_db('db_prova',$conn ) or die(mysql_error());
//
if(isset($_POST['nome'])){
$dato= $_POST['nome'];
mysql_query(" INSERT INTO test (valore) VALUES ('$dato') ") or die(mysql_error());
/// NOW I declare what I want to be replaced in the div id="visibile"
echo "
<form id='form_cancella' name='form_cancella' action='' methos='POST' onSubmit=' return false;' >
<text name='dato' value='".$dato."' >Benvenuto <b>".$dato."</b></text>
<input type='submit' name='cancella' value='cancella' onClick=\" ajaxSubmit('logout.php','visibile','form_cancella');\" />
</form>
";
}
?>

Categories