Google Answers Logo
View Question
 
Q: PHP and MySql...Updating Multiple Records ( Answered 5 out of 5 stars,   0 Comments )
Question  
Subject: PHP and MySql...Updating Multiple Records
Category: Computers > Programming
Asked by: flyguylol-ga
List Price: $20.00
Posted: 04 Feb 2006 17:22 PST
Expires: 06 Mar 2006 17:22 PST
Question ID: 441529
I am working on a web page in PHP and MySql.  I've been using
Dreamweaver MX 2004. The web page lists a user's properties using the
"repeat region" behavior. Beside every property, there is a checkbox
with the value of the user's property (name of the checkbox is
"propertyname".  I need the user to be able to check multiple
properties, and with the update button, have a column in the database
updated with the current time. Right now, only one property's
"dateforformatcounter" is updated, regardless of how many checkboxes
are checked.

Here is the code:

<?php require_once('Connections/connectdb.php'); ?>

<?php
// Load the tNG classes
require_once('includes/tng/tNG.inc.php');

function GetSQLValueString($theValue, $theType, $theDefinedValue = "",
$theNotDefinedValue = "")
{
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $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;
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
  $updateSQL = sprintf("UPDATE owner_prop SET dateformatforcounter=%s
WHERE Propertyname=%s",
                       GetSQLValueString($_POST['update'], "text"),
                       GetSQLValueString($_POST['propertyname'], "text"));

  mysql_select_db($database_connectdb, $connectdb);
  $Result1 = mysql_query($updateSQL, $connectdb) or die(mysql_error());
}

$colname_Recordset1 = "-1";
if (isset($_COOKIE['UserName'])) {
  $colname_Recordset1 = (get_magic_quotes_gpc()) ?
$_COOKIE['UserName'] : addslashes($_COOKIE['UserName']);
}
mysql_select_db($database_connectdb, $connectdb);
$query_Recordset1 = sprintf("SELECT * FROM owner_prop WHERE owner =
'%s' ORDER BY dateformatforcounter DESC", $colname_Recordset1);
$Recordset1 = mysql_query($query_Recordset1, $connectdb) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script language="JavaScript" type="text/JavaScript">
<!--
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr;
for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++)
x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++)
x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array;
for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc)
x.oSrc=x.src; x.src=a[i+2];}
}

function checkAll(field)
{
for (i = 0; i < field.length; i++)
	field[i].checked = true ;
}

//-->
</script>
<link href="/para1.css" rel="stylesheet" type="text/css">
<style type="text/css">
<!--
a:link {
	color: #FFFFFF;
}
.Pararegspace {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 12px;
	line-height: 14px;
	font-weight: bold;
}
-->
<style type="text/css">
<!--
form {
margin: 0;
padding: 0;
}
.style15 {font-size: small}
-->
</style>
</head>
<body bgcolor="#CCCCCC" vlink="#000000" alink="#000000"
onLoad="MM_preloadImages('/Images/Headings/on/MAIL_ON.gif','/Images/Headings/on/ADD%20NEW%20PROPERTY_ON.gif','/Images/Headings/on/DELETE%20PROPERTY_ON.gif','/Images/Headings/on/CHANGE%20PASSWORD_ON.gif','/Images/Headings/on/SIGN-OUT_ON.gif','/Images/Headings/on/MODIFY%20ACCOUNT%20INFO_ON.gif','/Images/Headings/on/CLAIMREWARD_ON.gif','/Images/Headings/on/CONTACTUS_ON.gif')">
<table width="725" border="0" align="center" cellpadding="0"
cellspacing="0"><form action="<?php echo $editFormAction; ?>"
name="form1" method="POST">
  <tr>
    <td colspan="10"><div align="center"><img
src="/Images/consoleowners65trimmed.gif" width="267"
height="62"></div></td>
  </tr>
  <tr>
    <td colspan="10"><img src="/Images/spacer1x6.gif" width="1" height="6"></td>
  </tr>
  <tr>
    <td colspan="10" bgcolor="#14336A"><img
src="/Images/spacer1x6.gif" width="1" height="6"></td>
  </tr>
  <tr>
    <td width="6" bgcolor="#14336A">&nbsp;</td>
    <td width="62" bgcolor="#BBCAE5"><div align="center"><a href="#"
onMouseOut="MM_swapImgRestore()"
onMouseOver="MM_swapImage('Image5','','/Images/Headings/on/MAIL_ON.gif',1)"><img
src="/Images/Headings/MAIL.gif" name="Image5" width="31" height="12"
border="0"></a></div></td>
    <td width="94" height="35" bgcolor="#BBCAE5"><div
align="center"><a href="owners_newprop.php"
onMouseOut="MM_swapImgRestore()"
onMouseOver="MM_swapImage('Image6','','/Images/Headings/on/ADD%20NEW%20PROPERTY_ON.gif',1)"><img
src="/Images/Headings/ADD%20NEW%20PROPERTY.gif" name="Image6"
width="64" height="28" border="0"></a></div></td>
    <td width="94" bgcolor="#BBCAE5"><div align="center"><a href="#"
onMouseOut="MM_swapImgRestore()"
onMouseOver="MM_swapImage('Image7','','/Images/Headings/on/DELETE%20PROPERTY_ON.gif',1)"><img
src="/Images/Headings/DELETE%20PROPERTY.gif" name="Image7" width="63"
height="28" border="0"></a></div></td>
    <td width="121" bgcolor="#BBCAE5"><div align="center"><a
href="owner_modify_account_info.php" onMouseOut="MM_swapImgRestore()"
onMouseOver="MM_swapImage('Image12','','/Images/Headings/on/MODIFY%20ACCOUNT%20INFO_ON.gif',1)"><img
src="/Images/Headings/MODIFY%20ACCOUNT%20INFO.gif" name="Image12"
width="91" height="28" border="0"></a></div></td>
    <td width="100" bgcolor="#BBCAE5"><div align="center"><a
href="owner_modify_account_pw.php" onMouseOut="MM_swapImgRestore()"
onMouseOver="MM_swapImage('Image9','','/Images/Headings/on/CHANGE%20PASSWORD_ON.gif',1)"><img
src="/Images/Headings/CHANGE%20PASSWORD.gif" name="Image9" width="70"
height="28" border="0"></a></div></td>
    <td width="86" bgcolor="#BBCAE5"><div align="center"><a href="#"
onMouseOut="MM_swapImgRestore()"
onMouseOver="MM_swapImage('Image16','','/Images/Headings/on/CLAIMREWARD_ON.gif',1)"><img
src="/Images/Headings/CLAIM%20REWARD.gif" name="Image16" width="55"
height="28" border="0"></a></div></td>
    <td width="88" bgcolor="#BBCAE5"><div align="center"><a href="#"
onMouseOut="MM_swapImgRestore()"
onMouseOver="MM_swapImage('Image17','','/Images/Headings/on/CONTACTUS_ON.gif',1)"><img
src="/Images/Headings/CONTACT%20US.gif" name="Image17" width="58"
height="28" border="0"></a></div></td>
    <td width="92" bgcolor="#BBCAE5"><div align="center"><a href="#"
onMouseOut="MM_swapImgRestore()"
onMouseOver="MM_swapImage('Image11','','/Images/Headings/on/SIGN-OUT_ON.gif',1)"><img
src="/Images/Headings/SIGN_OUT.gif" name="Image11" width="60"
height="13" border="0"></a></div></td>
    <td width="6" bgcolor="#14336A">&nbsp;</td>
  </tr>
  <tr>
    <td colspan="10" bgcolor="#14336A"><img
src="/Images/spacer1x6.gif" width="1" height="6"></td>
  </tr>
  <tr bgcolor="#CCCCCC">
    <td colspan="10"><div align="center" class="para1"></div></td>
  </tr>
  <tr bgcolor="#CCCCCC">
    <td colspan="10">
        <table width="750" border="0" cellspacing="0" cellpadding="0">
          <tr>
            <td width="25">&nbsp;</td>
            <td width="107"><input type="submit" name="Submit"
value="Renew Checked"></td>
            <td width="10">&nbsp;</td>
            <td width="68"><span class="para1">
              <input name="Checkall" type="button" id="Checkall"
onClick='checkAll(this.form,list)' value='Check all'/>
            </span></td>
            <td width="19">&nbsp;</td>
            <td width="282"><div align="center"><span
class="para1"><font color="#000000"><?php echo $_COOKIE['UserName'];
?>,
            you have <?php echo $totalRows_Recordset1 ?>
properties</font></span></div></td>
            <td width="42">&nbsp;</td>
            <td width="195"><span class="para1"><strong class="Pararegspace">
              <input name="update" type="hidden" id="update"
value="<?php echo date('F jS, Y G:i:sT'); ?>">
            </strong></span></td>
          </tr>
        </table>
  <tr bgcolor="#BBCAE5">
    <td height="108" colspan="10">
      <?php do { ?>
      <table width="750" border="4" align="center" cellpadding="0" cellspacing="0">
        <tr>
          <td width="20" rowspan="2" bordercolor="#BBCAE5"><div align="center">
              <input type="checkbox" name="propertyname"
id="propertyname" value="<?php echo $row_Recordset1['Propertyname'];
?>">
          </div></td>
          <td width="46" rowspan="2" align="center" valign="middle"
bgcolor="#000000"><div align="center"><a
href="/owners_newprop_previewit3.php?Uprop=<?php echo
$row_Recordset1['Propertyname']; ?>"><img src="<?php echo
tNG_showDynamicThumbnail("", "upload/{Recordset1.Propertyname}/",
"{Recordset1.photo1}", 140, 100, true); ?>" border="5"
align="absmiddle" /></a></div></td>
          <td width="0" height="65" align="left" valign="top"
bordercolor="#BBCAE5" bgcolor="#BBCAE5"
class="para1"><strong></strong><a
href="/owners_property_details.php?Uprop=<?php echo
$row_Recordset1['Propertyname']; ?>"><font
size="2"><strong></strong></font></a></td>
          <td width="315" align="left" valign="top"
bordercolor="#BBCAE5" bgcolor="#BBCAE5" class="para1"><a
href="/owners_property_details.php?Uprop=<?php echo
$row_Recordset1['Propertyname']; ?>" class="Biggerpara"></a><a
href="/owners_newprop_previewit3.php?Uprop=<?php echo
$row_Recordset1['Propertyname']; ?>" class="Biggerpara"><font
color="#14336A" face="Arial, Helvetica, sans-serif"><?php echo
$row_Recordset1['Propertyname']; ?></font></a><br>
      Renew within: <a name="yoyo" class="Countdown">
      <?php
$startDate = $row_Recordset1['dateformatforcounter'];
$thirtyDays = date("F jS, Y G:i:sT", strtotime($startDate) + 60*60*24); 
$threesixtyHours = date("F jS, Y G:i:sT", strtotime($startDate) + 60*60*360);
// enter start date below like this: "January 2, 2001"
$end = $threesixtyHours;
// enter string of what this start date is.
$text = "";
$textOnTheDay = "";
$textAfterwards = "This property has expired!";
//-
$now = strtotime ("now");
$then = $then = strtotime ("$end");
$difference = $then - $now;
$num = $difference/86400;
$days = intval($num);
$num2 = ($num - $days)*24;
$hours = intval($num2);
$num3 = ($num2 - $hours)*60;
$mins = intval($num3);
$num4 = ($num3 - $mins)*60;
$secs = intval($num4);
if ($days>0 || $hours>0 || $minutes>0 || $seconds>0) {
echo "$days days, ";
echo "$hours hours, ";
echo "$mins minutes";
echo $text;
} else if ($days<=5){ ?>
      </a><a name="yoyo" class="Countdown"><a class="Countdownred"> <?
echo "$days days, ";
echo "$hours hours, ";
echo "$mins minutes";
echo $text;
} else if (($days==0) && ($hours<=0 || $minutes<=0 || $seconds<=0)) {
echo $textOnTheDay;
} else { 
echo $textAfterwards;
} ?></a></a> <br>
      Created: <?php echo $row_Recordset1['datecreated']; ?><br>
      Last Modified: <strong class="para1"><?php echo
$row_Recordset1['timestamp']; ?></strong></td>
          <td width="24" rowspan="2" align="left" valign="middle"
bordercolor="#BBCAE5" class="para1">&nbsp;</td>
          <td width="323" rowspan="2" align="left" valign="middle"
bordercolor="#BBCAE5" class="para1"><strong class="Pararegspace">Type:
<?php echo $row_Recordset1['propertytype']; ?><br>
      Rent: $<?php echo $row_Recordset1['monthlyrent']; ?>.00<br>
      Security Deposit: $<?php echo $row_Recordset1['securitydeposit']; ?>.00<br>
      Lease: <?php echo $row_Recordset1['leaseduration']; ?><br>
      Square Feet: <?php echo $row_Recordset1['sqft']; ?> sq ft. <br>
      Bedrooms: <?php echo $row_Recordset1['bedrooms']; ?><br>
      Bathrooms: <?php echo $row_Recordset1['bathrooms']; ?>
          </strong></td>
        </tr>
        <tr>
          <td height="36" colspan="2" align="left" valign="bottom"
bordercolor="#BBCAE5"><div align="left"><a
href="/owners_newprop_previewit3.php?Uprop=<?php echo
$row_Recordset1['Propertyname']; ?>"><img src="<?php echo
tNG_showDynamicThumbnail("", "upload/{Recordset1.Propertyname}/",
"{Recordset1.photo2}", 70, 50, true); ?>" width="80" height="50"
border="1" align="bottom" /></a><a
href="/owners_newprop_previewit3.php?Uprop=<?php echo
$row_Recordset1['Propertyname']; ?>"><img src="<?php echo
tNG_showDynamicThumbnail("", "upload/{Recordset1.Propertyname}/",
"{Recordset1.photo3}", 70, 50, true); ?>" width="80" height="50"
border="1" align="bottom" /></a><a
href="/owners_newprop_previewit3.php?Uprop=<?php echo
$row_Recordset1['Propertyname']; ?>"><img src="<?php echo
tNG_showDynamicThumbnail("", "upload/{Recordset1.Propertyname}/",
"{Recordset1.photo4}", 70, 50, true); ?>" width="80" height="50"
border="1" align="bottom" /></a><a
href="/owners_newprop_previewit3.php?Uprop=<?php echo
$row_Recordset1['Propertyname']; ?>"><img src="<?php echo
tNG_showDynamicThumbnail("", "upload/{Recordset1.Propertyname}/",
"{Recordset1.photo5}", 70, 50, false); ?>" width="80" height="50"
border="1" align="bottom" /></a></div></td>
        </tr>
      </table>
      <?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
      <input type="hidden" name="MM_update" value="form1"
action="<?php echo $editFormAction; ?>">
      <input type="hidden" name="MM_update" value="form1">
    </form></td>
  </tr>
</table>
<table width="750" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
  </tr>
</table>
</body>
</html>
<?php
mysql_free_result($Recordset1);
?>


Thanks.
Answer  
Subject: Re: PHP and MySql...Updating Multiple Records
Answered By: palitoy-ga on 05 Feb 2006 04:20 PST
Rated:5 out of 5 stars
 
Hello flyguylol-ga,

Thank-you for your question.

It is difficult to reproduce your webpage locally as it relies on a
number of databases and includes that are not given here so that a
local copy of the page cannot be duplicated.  Please bear this in mind
as I try to answer your question for you.

At present the MySQL function to update your database needs to be
corrected as it currently only updates the dateformatforcounter.

The current line in your code is:
$updateSQL = sprintf("UPDATE owner_prop SET dateformatforcounter=%s
WHERE Propertyname=%s", GetSQLValueString($_POST['update'], "text"),  
                    GetSQLValueString($_POST['propertyname'],
"text"));

The important part of this is:
"UPDATE owner_prop SET dateformatforcounter=%s WHERE Propertyname=%s"

This is saying "update the table owner_prop and set the
dateformatforcounter column equal to %s when the propertyname is also
equal to %s".

As there is not enough information in your question to give you a
complete answer for your specific situation (as I do not know the
structure of your database for example), I will have to give you a
generic answer.

The MySQL reference manual gives this as the UPDATE syntax:

UPDATE [LOW_PRIORITY] [IGNORE] tbl_name
    SET col_name1=expr1 [, col_name2=expr2 ...]
    [WHERE where_condition]
    [ORDER BY ...]
    [LIMIT row_count]
http://dev.mysql.com/doc/refman/5.0/en/update.html

Therefore to update multiple items in your query you simply need to
separate each with a comma.

An example in your case would be:
"UPDATE owner_prop SET dateformatforcounter=%s, properyone=%s,
propertytwo=%s WHERE Propertyname=%s"

This would set propertyone, propertytwo and dateformatforcounter to %s
where Propertyname = %s in owner_prop.  (propertyone and propertytwo
are two columns I have made up as I do not know the structure of your
database.)

I hope this answers your question and you can simply see how you need
to alter your code to incorporate the additional items in your MySQL
UPDATE query.

I am sure you can understand the difficulty in answering queries such
as these without seeing working copies of the page complete with
errors but if you have any further questions on this subject please
ask for clarification and give as much further information as you can.

Further reading:
http://clusty.com/search?sourceid=Mozilla-search&query=dreamweaver+update+multiple+checkboxes

Request for Answer Clarification by flyguylol-ga on 05 Feb 2006 10:13 PST
Hello palitoy-ga,

Thanks for the prompt answer.

When I was writing the question, I thought about including only those
aspects of the code that dealt with the update, but decided to present
the entire code so that the researcher could perhaps get a better
handle on the question.

In response to your answer:

"UPDATE owner_prop SET dateformatforcounter=%s, properyone=%s,
propertytwo=%s WHERE Propertyname=%s"

Yes, I am trying to update the user's selected properties with the
current time (dateformatforcounter).  The user could have one property
selected, the user could have one hundred properties selected.  I
believe there has to be some type of array here to deal with the
variable number of properties, but need to know how to write the code
for the array (hence the question).

For every property that the user clicks on to be renewed, the
checkbox's (propertyname) value corresponds to the propertyname.  In
some situations, I have heard of setting this value to an array
number, but again, I don't know how to do it.  Right now,

<input type="checkbox" name="propertyname"
id="propertyname" value="<?php echo $row_Recordset1['Propertyname'];

...is the way I have it set up.


     Therefore to update multiple items in your query you simply need to
     separate each with a comma.

     An example in your case would be:
     "UPDATE owner_prop SET dateformatforcounter=%s, properyone=%s,
     propertytwo=%s WHERE Propertyname=%s"

     This would set propertyone, propertytwo and dateformatforcounter to %s
     where Propertyname = %s in owner_prop.  (propertyone and propertytwo
     are two columns I have made up as I do not know the structure of your
     database.)

There is only one "Propertyname" in the database.  How do I write the
UPDATE to include an undetermined amount of properties being updated? 
Do I need to change the checkbox value?  How do I create an array for
this?

I hope this provides clarification.

Clarification of Answer by palitoy-ga on 05 Feb 2006 11:40 PST
From your clarification request I believe you are correct in thinking
that an array will be helpful in producing the correct MySQL function
however I think more information will be first needed on what
columns/rows you have in your current database.  Can you provide this
for me?  Can you also provide me with an approximate level of
expertise that you have in php programming?  I don't want to pitch my
answers to the wrong level of expertise :-)

We need to think about how the information would be best stored in the
database before building the update function.

For instance if there is only one propertyname in the in database and
this was updated each time a user submitted the form, previous data
could be lost.

Also, do you have a page online where you have a non-working copy of
the page?  This would make it significantly easier to visualise the
exact problem.

With regards to your <input> boxes, do these have different name's? 
When you submit a webpage and request the value of the input box you
need to know the name property of the input box.  Obviously if all
these have the same name the program does not know which one to use so
uses the last one it knows about.

We currently have this:

<input type="checkbox" name="propertyname" id="propertyname"
value="<?php echo $row_Recordset1['Propertyname'];?>">

This should perhaps be changed to this:
<input type="checkbox" name="propertyname<?php echo
$row_Recordset1['Propertyname'];?>" id="propertyname" value="<?php
echo $row_Recordset1['Propertyname'];?>">

This will name each checkbox with a name of propertyname-followed by
the value (which will hopefully be a unique name).

In the meantime, whilst you wait for my next response you may find the
following article helpful - it is written in ASP not PHP but the
principles are more or less identical.
http://www.codeproject.com/asp/checkboxesfordatabase.asp

Request for Answer Clarification by flyguylol-ga on 05 Feb 2006 12:35 PST
Hello palitoy-ga,

Thanks for the prompt responses.

     Can you provide this
     for me?  Can you also provide me with an approximate level of
     expertise that you have in php programming?  I don't want to pitch my
     answers to the wrong level of expertise :-)

I have approximately 40 columns in the database for each record (yes
alot).  The good news is, in this case, the only one to be updated is
the "dateformatforcounter" (with <?php echo date('F jS, Y G:i:sT')?> )
where the primary key = "Propertyname".

I have been working on this site for about 1 1/2 months.  Before that,
I have never entered a piece of code.  I have approximately 40 pages
built, and have been working on this project full time about 15 hours
per day.  This is the only area (at this point) that I haven't been
able to figure out.  So I guess I would be considered a newbie.

Unfortunately, I'm running everything on my host computer at the
moment, using Apache, PHP, and MySql, so I can't show anything to you.
 But maybe this will help to clarify the issue:

Right now:
User selects multiple checkboxes.  Each checkbox has a value of =<?php
echo $row_Recordset1['Propertyname'].  User clicks the submit button. 
The first checkbox's value selects the propertyname and updates the
column "dateformatforcounter" within that propertyname with <?php echo
date('F jS, Y G:i:sT')?>.

What I Need (hopefully);)
User selects multiple checkboxes. Each checkbox has a value of =<?php
echo $row_Recordset1['Propertyname'].  User clicks the submit button.
Php runs through the checkboxes to see if they are selected.  For each
selected checkbox, PHP uses the value of the selected checkbox to
select the record and updates the "dateformatforcounter" column with
<?php echo date('F jS, Y G:i:sT')?>.

I've actually spent an entire week googling sites on this subject, and
was unable to find anything in PHP that I found helpful (I have seen
the url you mentioned, though...).

   <input type="checkbox" name="propertyname<?php echo
   $row_Recordset1['Propertyname'];?>" id="propertyname" value="<?php
   echo $row_Recordset1['Propertyname'];?>">

I guess it comes down to this:  How do you get the php update command
to check to see if the checkbox values exist and if so, run the update
using the checkbox values to select the record?

Clarification of Answer by palitoy-ga on 06 Feb 2006 02:32 PST
Hello again and thank-you for answering my queries.

I will try to explain how I would get the update command to check
whether a checkbox has been checked or not.  Again, if you have any
queries on any of this please just ask.

When a page is submitted by POST to a php page, the php page
automatically creates an array called $_POST.  This array contains all
of the elements that have been submitted to the page.  If one of those
elements is a checkbox, it only appears in the $_POST array if it has
been checked by the user and we can use this to our advantage.  We
simply need to look through the array (by the use of a loop) and see
if any of our checkboxes have been submitted and then "remember it"
(by storing it in a variable) if it has.

This is how I would achieve this:

===BEGIN CODE===
# set a variable to remember the checked boxes
$remember = "";
# loop through the array and check whether the checkbox name
# is one we are looking for
foreach($_POST as $key => $value){
  # check if the $key is one of the checkboxes, this is done by a 
  # regular expression and assumes the checkbox name begins 
  # with propertyname...
  if ( preg_match("/^propertyname/",$key) {
    # if it does match then remember it
    if ( $remember == "" ) { $remember = $key."=".$value.","; }
    else { $remember = $remember . $key."=".$value.","; };
  }; # end if statement
}; # end foreach statement

# at this point in the code $remember should be a list of submitted
# checkboxes and their values.  there will also be a trailing ,
# so we should remove this
if ( $remember != "") { $remember = substr("$remember", 0, -1); };

===END CODE===

All of this should be placed before the update statement in your
current code.  To check things are working correctly you could use
print $remember;exit; in your code to stop it at this point.  It
should print out what checkboxes have been ticked when the page is
submitted.

Please also remember that each checkbox has to have a unique name (as
we discussed in the previous clarification).

$remember would then be simply added to the update command like this:

$updateSQL = sprintf("UPDATE owner_prop SET dateformatforcounter=%s".$remember."
WHERE Propertyname=%s", GetSQLValueString($_POST['update'], "text"),  
                    GetSQLValueString($_POST['propertyname'],
"text"));

Please let me know how you get on with this.

Request for Answer Clarification by flyguylol-ga on 06 Feb 2006 11:17 PST
Hello palitoy-ga,

I'm impressed with your code, it was well thought out and well
described.  Unfortunately, I'm getting an error:

You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'propertynameapt39=apt39,propertynameniceprop4=niceprop4 WHERE 
Propertyname=NULL' at line 1

I'm not sure what is going on here...
Here is the code that applies...

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
$remember = "";
foreach($_POST as $key => $value){
  if(preg_match("/^propertyname/",$key)){
    if ( $remember == "" ) { $remember = $key."=".$value.","; }
    else { $remember = $remember . $key."=".$value.","; };
  }; 
}; 
if ( $remember != "") { $remember = substr("$remember", 0, -1); };

  $updateSQL = sprintf("UPDATE owner_prop SET
dateformatforcounter=%s".$remember." WHERE Propertyname=%s",
                       GetSQLValueString($_POST['update'], "text"),
                       GetSQLValueString($_POST['propertyname'], "text"));

...and further down:

<input type="checkbox" name="propertyname<?php echo
$row_Recordset1['Propertyname']; ?>" id="propertyname<?php echo
$row_Recordset1['Propertyname']; ?>" value="<?php echo
$row_Recordset1['Propertyname']; ?>">

(something with the name of the checkbox doesn't seem right here, but
it could be me.)

Thanks for your prompt answer!

Clarification of Answer by palitoy-ga on 06 Feb 2006 12:02 PST
Could you please try changing this line:

if ( $remember == "" ) { $remember = $key."=".$value.","; }

to:

if ( $remember == "" ) { $remember = $key."='".$value."', "; }

(Note the extra apostrophes.)

The error could be because these need to be presented like this to the
database.  Could you also add print $updateSQL; after the following
line:
$updateSQL = sprintf("UPDATE owner_prop SET
dateformatforcounter=%s".$remember." WHERE Propertyname=%s",
                       GetSQLValueString($_POST['update'], "text"),
                       GetSQLValueString($_POST['propertyname'], "text"));

This will help us see what is going on with the $updateSQL variable if
things are still not correct.  The properyname=NULL part is a bit
puzzling... I will need to think a little bit more about this.

Just another thought on this... do the columns in the database you are
trying to update have exactly the same names as the checkboxes?  Are
the database column names equal to the number that is passed (for
instance apt39 or niceprop4)?

Clarification of Answer by palitoy-ga on 06 Feb 2006 12:09 PST
I have just noticed something else, we need to add a comma to the
beginning of the $remember variable if it is not blank.

So change:

if ( $remember != "") { $remember = substr("$remember", 0, -1); };

to:

if ( $remember != "") { $remember = " ,".substr("$remember", 0, -1); };

Request for Answer Clarification by flyguylol-ga on 06 Feb 2006 13:28 PST
Hello palitoy-ga

I made the changes and inserted the print command...

I'm getting the following error when I try to update multiple checkboxes:

UPDATE owner_prop SET dateformatforcounter='February 6th, 2006
16:12:53EST' ,propertynameapt39='apt39',
propertynameniceprop4=niceprop4,propertynameCountry_Cottage=Country
Cottage,propertyname231sss=231sss WHERE Propertyname=NULLYou have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near
'Cottage,propertyname231sss=231sss WHERE Propertyname=NULL' at line 1

   do the columns in the database you are
   trying to update have exactly the same names as the checkboxes?  Are
   the database column names equal to the number that is passed (for
   instance apt39 or niceprop4)?

I am only trying to update one column, the "dateformatforcounter". 
I'm trying to use each selected checkbox (propertyname) as the primary
key to select the row in which the "dateformatforcounter" is updated.

For example:  First checkbox's name (at this point)=
propertynameapt39.  This checked checkbox should find the column in
the "owner_prop" table called "Propertyname" with the value of apt39. 
Then it should update the "dateformatforcounter" column within the
apt39 row with the current date/time.

Hope that makes more sense.

Request for Answer Clarification by flyguylol-ga on 06 Feb 2006 13:29 PST
Oh...here's the updated code...

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
$remember = "";
foreach($_POST as $key => $value){
  if(preg_match("/^propertyname/",$key)){
    if ( $remember == "" ) { $remember = $key."='".$value."', "; }
    else { $remember = $remember . $key."=".$value.","; };
  }; 
}; 
if ( $remember != "") { $remember = " ,".substr("$remember", 0, -1); };

  $updateSQL = sprintf("UPDATE owner_prop SET
dateformatforcounter=%s".$remember." WHERE Propertyname=%s",
                       GetSQLValueString($_POST['update'], "text"),
                       GetSQLValueString($_POST['propertyname'], "text"));
	print $updateSQL; 
  mysql_select_db($database_connectdb, $connectdb);
  $Result1 = mysql_query($updateSQL, $connectdb) or die(mysql_error());
}

$colname_Recordset1 = "-1";
if (isset($_COOKIE['UserName'])) {
  $colname_Recordset1 = (get_magic_quotes_gpc()) ?
$_COOKIE['UserName'] : addslashes($_COOKIE['UserName']);
}
mysql_select_db($database_connectdb, $connectdb);
$query_Recordset1 = sprintf("SELECT * FROM owner_prop WHERE owner =
'%s' ORDER BY dateformatforcounter DESC", $colname_Recordset1);
$Recordset1 = mysql_query($query_Recordset1, $connectdb) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);

Request for Answer Clarification by flyguylol-ga on 06 Feb 2006 14:08 PST
Hello palitoy,

I've been working at this since I read your last post, and got this error...

UPDATE owner_prop SET dateformatforcounter='February 6th, 2006
17:04:42EST' ,propertyname231sss='231sss', propertynameapt39=apt39
WHERE Propertyname=NULLUnknown column 'propertyname231sss' in 'field
list'

Sounds to me like sql is searching for the column 'propertyname231sss'
when there is no column with that name.  The column id is
"Propertyname" and one of the values within that column is '231sss'. 
I'm not sure what to do about this, but think that may be the cause of
the error.

Thanks in Advance.

Clarification of Answer by palitoy-ga on 07 Feb 2006 02:10 PST
I think I am on the same wavelength as you know with regards to what
we need to do.  Each time a user submits the page, the date/time is
recorded for each of the properties that the user has ticked.  Is this
correct?

I am sorry it has taken so long for me to get my head around this!  In
your last clarification you were correct in your assumptions.

This will require a rewrite of the code I sent you before as the
previous UPDATE command would not achieve this.

What we need to achieve is to "update the dateformatforcounter column
in the database when the propertyname column is equal to value
submitted by the checkbox".  The "value submitted by the checkbox" is
only available when the checkbox has been checked therefore we can
still use our old plan of attack and we simply need to alter the MySQL
statement and the $remember variable.

===BEGIN CODE===
# set a variable to remember the checked boxes
$remember = "";
# loop through the array and check whether the checkbox name
# is one we are looking for
foreach($_POST as $key => $value){
  # check if the $key is one of the checkboxes, this is done by a 
  # regular expression and assumes the checkbox name begins 
  # with propertyname...
  if ( preg_match("/^propertyname/",$key) {
    # if it does match then remember it
    if ( $remember == "" ) { $remember = " OR Propertyname='".$value."',"; }
    else { $remember = $remember . " OR Propertyname='".$value."',"; };
  }; # end if statement
}; # end foreach statement

# at this point in the code $remember should be a list of submitted
# checkboxes and their values.  there will also be a trailing ,
# so we should remove this
if ( $remember != "") { $remember = substr("$remember", 0, -1); };

===END CODE===

Also change this line:

$updateSQL = sprintf("UPDATE owner_prop SET
dateformatforcounter=%s".$remember." WHERE Propertyname=%s",
                       GetSQLValueString($_POST['update'], "text"),
                       GetSQLValueString($_POST['propertyname'], "text"));

To:

$updateSQL = sprintf("UPDATE owner_prop SET
dateformatforcounter=%s WHERE Propertyname=%s".$remember,
                       GetSQLValueString($_POST['update'], "text"),
                       GetSQLValueString($_POST['propertyname'], "text"));

Let me know how you get on with this.

Request for Answer Clarification by flyguylol-ga on 07 Feb 2006 11:03 PST
Hello palitoy-ga,

I think we are on the same page now!!  I updated the code, and low and
behold, when I try to update four of the properties:

UPDATE owner_prop SET dateformatforcounter='February 7th, 2006
13:53:20EST' WHERE Propertyname=NULL OR Propertyname='Premium Living',
OR Propertyname='Townhouse01', OR Propertyname='niceprop4', OR
Propertyname='apt39'You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near ' OR Propertyname='Townhouse01', OR
Propertyname='niceprop4', OR Propertyname='ap' at line 1

I don't understand why the first Propertyname is NULL.

Don't know if this helps, but when I take the variable out of the
checkbox name and try it again (with four updates) we get no errors,
but:

UPDATE owner_prop SET dateformatforcounter='February 7th, 2006
13:59:47EST' WHERE Propertyname='apt39' OR Propertyname='apt39'

This leads me to believe that somehow your snippet is causing the
first of the Propertynames to be listed as "NULL".  I'm not sure
though with my limited expertise!

I think we are almost there though.

Request for Answer Clarification by flyguylol-ga on 07 Feb 2006 11:11 PST
One more thing.

If I choose only one property to be updated, the property successfully
updates, and the print $updatesql function gives me:

UPDATE owner_prop SET dateformatforcounter='February 7th, 2006
14:08:50EST' WHERE Propertyname=NULL OR Propertyname='Townhouse01'

Thought this might help.

Clarification of Answer by palitoy-ga on 07 Feb 2006 11:42 PST
The NULL part is coming from the %s in your original code.  I have
looked through your code but could not see what it was there for... I
assumed it was used in one of your tNG classes that are required by
the page.

What happens if you take the %s out so that the update command is this:

$updateSQL = sprintf("UPDATE owner_prop SET
dateformatforcounter=%s WHERE ".$remember,
                       GetSQLValueString($_POST['update'], "text"),
                       GetSQLValueString($_POST['propertyname'], "text"));

If this works the only thing you would need to check is what happens
if no checkboxes are checked.

Let me know how you get on again.

Clarification of Answer by palitoy-ga on 07 Feb 2006 11:44 PST
We also need to take out the commas from the original code to make it this:

if ( $remember == "" ) { $remember = " OR Propertyname='".$value."' "; }
else { $remember = $remember . " OR Propertyname='".$value."' "; };

Sorry I missed this before...

Request for Answer Clarification by flyguylol-ga on 07 Feb 2006 12:20 PST
Hello Palitoy-ga,

IT WORKS!!! Taking out the commas did the job! Thanks for hanging in
there. Now the only issue I have is that my "checkall" checkbox option
was assiciated with the name of the checkboxes being "propertyname". 
Because the checkboxes now have a different value (propertyname<?php
echo $row_Recordset1['Propertyname'];?>), the "checkall" option does
not work anymore.  Is there a quick fix for this?  If not, don't worry
about it.

<input name="Checkall" type="button" id="Checkall"
onClick='checkAll(this.form1,propertyname' value='Check all'/>

Great job making this work for me!  I'll wait until you post again,
then leave my ratings and tip.

Clarification of Answer by palitoy-ga on 08 Feb 2006 03:17 PST
Success!  That is what I like to hear :-)

With regards to your check-all problem, this turned out to require a
little more thinking than I first thought (as javascript isn't my
favoured programming language) but I think I have a solution for you.

In your code change this:

function checkAll(field)
{
for (i = 0; i < field.length; i++)
	field[i].checked = true ;
}

To:

function checkAll(obj)
{
// set the form to look at (your form is called form1)
var frm = document.form1
// get the form elements
var el = frm.elements
// loop through the elements...
for(i=0;i<el.length;i++) {
  // and check if it is a checkbox
  if(el[i].type == "checkbox" ) {
    // if it is a checkbox and you submitted yes to the function
    if(obj == "yes")
      // tick the box
      el[i].checked = true;
    else
      // otherwise untick the box
      el[i].checked = false;
    }
  }
}

As you can see from the above code I have added a little extra in -
you can add a button that allows the user to either "Check All" or
"Uncheck All" (if you don't require the uncheck button just simply
leave it off the page!).  The code for your buttons should then simply
be:

<input type="button" value="Check All" onClick="selectall('yes');return false;" />

<input type="button" value="UnCheck All" onClick="selectall('');return false;" />

Let me know how you get on with this and thanks for bearing with me
whilst we solved this together.

Request for Answer Clarification by flyguylol-ga on 08 Feb 2006 09:57 PST
Hello Palitoy-ga,

Thanks for working on this code.  Unfortunately, I get an error with
it at the moment.  I get an error "object expected" on line 191.  Not
sure what this is at all.

If we can have a resolution to this, that would be great!  Also, I
have been very impressed with your devotion to my question.  So for
that, thank-you!  I hope that there is a way I could call on you
specifically in the future.

Clarification of Answer by palitoy-ga on 08 Feb 2006 10:27 PST
Thank-you for the 5-star rating, kind words and generous tip.  They
are all greatly appreciated.  If you wish a question to be directed
for me specifically you can enter "For palitoy-ga" as the subject of
the question and the other researchers will leave it for me.

With regards to the new "object expected" error, is this because of
the new javascript code?  What happens if you remove the javascript
code and try it again?  Do you still get the error?

Clarification of Answer by palitoy-ga on 08 Feb 2006 10:32 PST
I have just noticed something... when I was transcribing this I was
using a different form and forgot to alter something in the code I
gave you.

These lines:

<input type="button" value="Check All" onClick="selectall('yes');return false;" />
<input type="button" value="UnCheck All" onClick="selectall('');return false;" />

Should read:
<input type="button" value="Check All" onClick="checkAll('yes');return false;" />
<input type="button" value="UnCheck All" onClick="checkAll('');return false;" />

Request for Answer Clarification by flyguylol-ga on 08 Feb 2006 10:56 PST
Hello Palitoy-ga.

Works perfectly now.  Thank-you very much!!

Clarification of Answer by palitoy-ga on 08 Feb 2006 11:14 PST
No problem!  Thanks for bearing with me as we worked through this.
flyguylol-ga rated this answer:5 out of 5 stars and gave an additional tip of: $20.00
Palitoy is a fantastic and knowledgable researcher with whole-hearted
devotion to answering your question.  If you get him (or her),
consider yourself lucky!

Comments  
There are no comments at this time.

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy