Solved

Not able to delete SQL row from HTML Checkbox...

Posted on 2011-09-15
2
263 Views
Last Modified: 2012-05-12
Not sure what the problem is here... I want the code to redirect user to page, but to also delete the mysql row if checkbox is checked.  

Edit: Line 222 is the dynamic checkboxes. line 236 is the delete button.

<?php require_once('../Connections/clcserver1.php'); ?>
<?php
// Start_session, check if user is logged in or not, and connect to the database all in one included file
include_once("scripts/checkuserlog.php");
?>
<?php
////////////////////////////////////////////////      Member log in double check       ///////////////////////////////////////////////////
if (!@$_SESSION['idx']) { 
    $msgToUser = '<br /><br /><font color="#FF0000">Only site members can do that</font><p><a href="register.php">Join Here</a></p>';
    include_once 'msgToUser.php'; 
    exit(); 
} else if ($logOptions_id != $_SESSION['id']) {
	$msgToUser = '<br /><br /><font color="#FF0000">Only site members can do that</font><p><a href="register.php">Join Here</a></p>';
    include_once 'msgToUser.php'; 
    exit(); 
}
?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

mysql_select_db($database_clcserver1, $clcserver1);
$query_Recordset1 = "SELECT * FROM job_leads";
$Recordset1 = mysql_query($query_Recordset1, $clcserver1) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);

mysql_select_db($database_clcserver1, $clcserver1);
@$industry = $_GET['industry'];
// Escape User Input to help prevent SQL Injection
$industry = mysql_real_escape_string($industry);
$query_Recordset1 = "SELECT * FROM job_leads WHERE industry= '$industry'";
$Recordset1 = mysql_query($query_Recordset1, $clcserver1) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);

// Start_session, check if user is logged in or not, and connect to the database all in one included file

// Include the class files for auto making links out of full URLs and for Time Ago date formatting
include_once("wi_class_files/autoMakeLinks.php");
include_once ("wi_class_files/agoTimeFormat.php");
// Create the two objects before we can use them below in this script
$activeLinkObject = new autoActiveLink;
$myObject = new convertToAgo; 
?>
<?php
// Include this script for random member display on home page
include_once "scripts/homePage_randomMembers.php"; 
?>
<?php
$sql_blabs = mysql_query("SELECT * FROM blabbing ORDER BY blab_date DESC LIMIT 10");

$blabberDisplayList = ""; // Initialize the variable here

while($row = mysql_fetch_array($sql_blabs)){
	
	$blabid = $row["id"];
	$uid = $row["mem_id"];
	$the_blab = $row["the_blab"];
	//$the_blab = substr($the_blab, 0, 48);
	$the_blab = wordwrap($the_blab, 30, "\n", true);
	//$the_blab = wordwrap($the_blab, 14, "<br />\n");
	$notokinarray = array("fag", "gay", "shit", "fuck", "stupid", "idiot", "asshole", "cunt", "douche");
    $okinarray   = array("sorcerer", "grey", "shug", "farg", "smart", "awesome guy", "butthole", "cake", "dude");
	$the_blab = str_replace($notokinarray, $okinarray, $the_blab);
	$the_blab = ($activeLinkObject -> makeActiveLink($the_blab));
	$blab_date = $row["blab_date"];
	$convertedTime = ($myObject -> convert_datetime($blab_date));
    $whenBlab = ($myObject -> makeAgo($convertedTime));
	$blab_type = $row["blab_type"];
	$blab_device = $row["device"];
	
	// Inner sql query
	$sql_mem_data = mysql_query("SELECT id, username, firstname, lastname FROM myMembers WHERE id='$uid' LIMIT 1");
	while($row = mysql_fetch_array($sql_mem_data)){
			$uid = $row["id"];
			$username = $row["username"];
			$firstname = $row["firstname"];
			$lastname = $row["lastname"];
			if ($firstname != "") {$username = "$firstname $lastname"; } // (I added usernames late in  my system, this line is not needed for you)
			///////  Mechanism to Display Pic. See if they have uploaded a pic or not  //////////////////////////
			$ucheck_pic = "members/$uid/image01.jpg";
			$udefault_pic = "members/0/image01.jpg";
			if (file_exists($ucheck_pic)) {
			$blabber_pic = '<div style="overflow:hidden; width:40px; height:40px;"><img src="' . $ucheck_pic . '" width="40px" border="0" /></div>'; // forces picture to be 100px wide and no more
			} else {
			$blabber_pic = "<img src=\"$udefault_pic\" width=\"40px\" height=\"40px\" border=\"0\" />"; // forces default picture to be 100px wide and no more
			}
	
			$blabberDisplayList .= '
      			<table width="100%" align="center" cellpadding="4" style="background-color:#CCCCCC; border:#999 1px solid;">
        <tr>
          <td width="7%" bgcolor="#FFFFFF" valign="top"><a href="profile.php?id=' . $uid . '">' . $blabber_pic . '</a>
          </td>
          <td width="93%" bgcolor="#F9F9F9" style="line-height:1.5em;" valign="top">
		 <span class="liteGreyColor textsize9"> ' . $whenBlab . ' <a href="profile.php?id=' . $uid . '"><strong>' . $username . '</strong></a> <br />
          via <em>' . $blab_device . '</em></span><br />
         <span class="textsize10"> ' . $the_blab . '</span>
            </td>
        </tr>
      </table>';
			}
	
}
?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta name="Description" content="CLC, Inc. Employment Network" />
<meta name="Keywords" content="employment, find a job, job, dfw employment, fort worth jobs, dallas jobs, training, veteran forum, 
forums employment, find employment, job discussion, job resources, vet, veteran, veteran resources" />
<title>CLC, Inc. Employment Network</title>
<link href="style/main.css" rel="stylesheet" type="text/css" />
<link rel="icon" href="favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
<script src="js/jquery-1.4.2.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript"> 
function toggleSlideBox(x) {
		if ($('#'+x).is(":hidden")) {
			//$(".sourceBox").slideUp(200);
			$('#'+x).slideDown(300);
		} else {
			$('#'+x).slideUp(300);
		}
}
</script>
</head>
<body>
<?php include_once "header_template.php"; ?>

<table width="920" style="background-color:#cccccc;" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>

    <td width="732" valign="top">

<div id="sb1" style="display:none; width:704px; border:#999 1px solid; padding:12px; background-image:url(style/area1BG.jpg); line-height:1.5em; ">CLC, Inc. Employment Network<br />
<table width="96%" border="0" align="center" cellpadding="0" cellspacing="0" style="margin-top:5px;">
  <tr>
      <td width="34%"><strong>&bull; Registration System</strong><span class="textsize10"> (php  mysql)</span><strong><br />
        &bull; Activation System</strong> <span class="textsize10">(php  mysql)</span><strong><br />
        &bull; Login w/ keep log System</strong> <span class="textsize10">(php  mysql)</span></td>
    <td width="33%"><strong>&bull; Friend System</strong> <span class="textsize10">(php  mysql)</span><strong><br />
&bull; Private Message System </strong><span class="textsize10">(php  mysql)</span><strong><br />
&bull; API and Gadget Systems </strong><span class="textsize10">(php  mysql)</span></td>
    <td width="33%"><strong>&bull; Profile EditingSystem</strong> <span class="textsize10">(php  mysql)</span><strong><br />
&bull; Member Listing System </strong> <span class="textsize10">(php  mysql)</span><strong><br />
&bull;Status System</strong> <span class="textsize10">(php  mysql)</span></td>
    </tr>
</table>
</div>
<div style="width:728px; border:#999 1px solid; border-bottom:none;"><?php include_once "leaderBoardAd.php"; ?></div>
<table style="background-color:#EFEFEF; border:#999 thin solid; padding:10px; line-height:1.5em;" width="730" border="0" cellspacing="0" cellpadding="0">
<tr>
  <td width="86%" valign="top" style="font-size:10px;"><table border="1" cellpadding="0" cellspacing="0">
    <tr>
      <td><table style="background-color:#EFEFEF; border:#999 thin solid; padding:10px; line-height:1.5em;" width="730" border="1" cellspacing="0" cellpadding="8">
        <tr>
          <td width="14%" valign="top"><h2>Select Industry</h2>
            <p><a href="http://clcinc.org/social/joblist.php?industry=logistics"> Logistics</a> <br />
               <a href="http://clcinc.org/social/joblist.php?industry=admin"> Administrative</a> <br />
               <a href="http://clcinc.org/social/joblist.php?industry=manu"> Manufacturing</a><br />
               <a href="http://clcinc.org/social/joblist.php?industry=mgmt"> Management</a><br />
               <a href="http://clcinc.org/social/joblist.php?industry=protect"> Protective/Law</a><br />
               <a href="http://clcinc.org/social/joblist.php?industry=natresource"> Oil/Gas</a><br />
               <a href="http://clcinc.org/social/joblist.php?industry=social"> Social</a><br />
               <a href="http://clcinc.org/social/joblist.php?industry=aero"> Aerospace</a><br />
               <a href="http://clcinc.org/social/joblist.php?industry=service"> Service</a><br />
               <a href="http://clcinc.org/social/joblist.php?industry=retail"> Retail</a><br />
            </p>
            </td>
          <td width="86%" valign="top" style="font-size:10px;">
          <form name="form1" method="post" action="">
            <table border="1" cellpadding="0" cellspacing="0">
              <tr>
                <td>Industry</td>
                <td>Contact</td>
                <td>Location</td>
                <td>Position</td>
                <td>Pay</td>
                <td>Hours</td>
                <td>Qualifications</td>
                <td>Delete</td>
                </tr>
              <tr>
                <?php do { ?>
                 [b] <td height="20"><?php echo $row_Recordset1['industry']; ?></td>
                  <td><?php echo $row_Recordset1['contact']; ?></td>
                  <td><?php echo $row_Recordset1['location']; ?></td>
                  <td><?php echo $row_Recordset1['position']; ?></td>
                  <td><?php echo $row_Recordset1['pay']; ?></td>
                  <td><?php echo $row_Recordset1['hours']; ?></td>
                  <td><?php echo $row_Recordset1['qualifications']; ?></td>
                  <td><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<?php echo $row_Recordset1['id']; ?>"></td>
                  </tr>
                  <tr>
                  <?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
              </tr>
            </table>
            <p> <a href="http://clcinc.org/social/jobadd.php">Insert an opening</a><br />
[/b]
<?php
/*
$res_user_type = mysql_query("SELECT account_type FROM myMembers WHERE id='$uid' LIMIT 1");
$data=mysql_fetch_array($res_user_type);
if ($num_acc_type > 0){
  
		  print '<input name="delete" type="submit" id="delete" value="Delete" />';
		  echo $data[0];
		  echo $uid;
}
*/
//verify that the user is B or C account type
$userID2 = $_SESSION['id'];
$result = mysql_query("SELECT account_type FROM mymembers WHERE id = '" . $userID2 . "' AND (account_type = 'b' OR account_type = 'c')") or die(mysql_error());  

if(mysql_num_rows($result) > 0) {
  print '<input name="delete" type="submit" id="delete" value="Delete" />';
} else {
;
exit();
}
mysql_close();
?>
            </p></td>
        </tr>
      </table></td>
      </tr>
  </table></td>
</tr>
</table></td>
    <td width="188" valign="top"><?php include_once "right_AD_template.php"; ?><br />
<a href="#" target="_blank"><center></center></a></td>
  </tr>

</table>
<?php
// Check if delete button active, start this
if ( isset( $_POST['checkbox'] ) && is_array( $_POST['checkbox']) )
{
$ids = array_map( 'intval', $_POST['checkbox'] );
$ids = implode( ',', $ids );
$sql = 'DELETE FROM `job_leads` WHERE `id` IN ( ' . $ids . ' )';
$result = mysql_query( $sql );
}
else
{
$result = FALSE;
}

// if successful redirect to self
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=joblist.php?industry=$industry\">";
}
mysql_close();
?>
<?php include_once "footer_template.php"; ?>
</body>
</html>
<?php
mysql_free_result($Recordset1);

?>

Open in new window

0
Comment
Question by:clcinc
2 Comments
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 36547585
Approximate code below
$delete = isset($_POST['delete'])?$_POST['delete'] : false;
if ($delete !== false) {
  $checkbox = isset($_POST['checkbox'])?$_POST['checkbox'] : array();; // Not secure
  if (!empty($checkbox)) {
    foreach($checkbox as $c) {
      $query = "DELETE FROM table WHERE ID=$c";
      mysql_query($query);
    }
    header('location: newlocation.php'); // modify as needed
  }
}

Open in new window

0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 36548820
This sequence occurs at line 265
<?php
// Check if delete button active, start this
if ( isset( $_POST['checkbox'] ) && is_array( $_POST['checkbox']) )
{
$ids = array_map( 'intval', $_POST['checkbox'] );
$ids = implode( ',', $ids );
$sql = 'DELETE FROM `job_leads` WHERE `id` IN ( ' . $ids . ' )';
$result = mysql_query( $sql );
}
else
{
$result = FALSE;
}

Open in new window

You might want to use some data visualization techniques to see what you are actually creating with this code.  You might also want to know whether the query works, and if not, why not.  So I think I might want to add these things to the programming, at least temporarily, so I could see what the code is doing to the data.

Use var_dump($_POST) to print out the contents of $_POST.  If you echo "<pre>" before var_dump() it will make the variables much easier to read.
Use var_dump($sql) to print out the contents of the generated query immediately before running the query.
Test the return value from the mysql_query() function.  MySQL is not a black box.  It can and will fail for reasons that are outside of your control.  You need to be able to detect the errors and make your script respond appropriately.  An example of how to run a query and visualize any resulting errors is in this code snippet.

You might also enjoy this book.  It is a much better way to learn PHP and MySQL when compared to Dreamweaver.  Dreamweaver contains some of the worst PHP programming ever written.  Do not try to follow their examples; you can learn a lot more - and the right techniques - from the SitePoint book in a matter of minutes!
http://www.sitepoint.com/books/phpmysql4/

Best of luck, ~Ray
$sql = " - WHATEVER - ";
if (!$res = mysql_query($sql))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/>$sql <br/>";
    die($errmsg);
}
// IF THE SCRIPT GETS THIS FAR, THE QUERY WORKED

Open in new window

0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Introduction Since I wrote the original article about Handling Date and Time in PHP and MySQL (http://www.experts-exchange.com/articles/201/Handling-Date-and-Time-in-PHP-and-MySQL.html) several years ago, it seemed like now was a good time to updat…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now