Question

php loop, multiple sql updates

Asked by: bschwarting

Ok, I'm open to suggestions, angel :), on my project.  I've hit another roadblock and might be approaching this whole thing the wrong way.  I was trying to create a small footprint of code and loop it all, but can't seem to get everything to work.

I want to print out 365 checkboxes (see attached image), then update a table in the database with the answer for 1(yes) or 0(no).  I'm not sure if doing 365 updates all at once is the best idea or not, for each of my users.

My end game is this:
#1) print out 365 checkboxes
#2) check the individual users table to see which checkbox is already a yes, and check it for them (maybe with a value=$checked ?)
#3) allow my users to select/deselect one, or all at the same time and click submit, and update accordingly

Here is the code I have so far, which will print the table, create all the answer variables, then it will update the 1st box that is checked and nothing more for some reason.

any ideas would be appreciated!

<?php
 
//GET VARIABLES FROM SUBMISSION ON SAME PAGE
$answer1 = $_POST['answer1']; 
$answer2 = $_POST['answer2']; 
$answer3 = $_POST['answer3']; 
$answer4 = $_POST['answer4']; 
$answer5 = $_POST['answer5'];
$answer6 = $_POST['answer6']; 
$answer7 = $_POST['answer7']; 
$answer8 = $_POST['answer8']; 
$answer9 = $_POST['answer9']; 
$answer10 = $_POST['answer10'];
 
 
//DAILY READINGS
$daily1reading = ', example, read page 1';
$daily2reading = ', example, read page 2';
$daily3reading = ', example, read page 3';
$daily4reading = ', example, read page 4';
$daily5reading = ', example, read page 5';
$daily6reading = ', example, read page 6';
$daily7reading = ', example, read page 7';
$daily8reading = ', example, read page 8';
$daily9reading = ', example, read page 9';
$daily10reading = ', example, read page 10';
 
$date365t = mktime(0, 0, 0, 1, 0, date(Y));
$date365 = date("Y-m-d", $date365t);
 
?>
 
<form method="post" action="365-days">
 
<?php
 
echo '<table width=650><tr>';
for($loop365=1;$loop365<=365;$loop365++) {
  if(($loop365-1)%15==0) echo '</tr><tr>'; ?>
  <td align="center"><span title="<?php 
  echo "Daily reading for ".date('F jS',mktime(0,0,0,1,$loop365)); $dailyreading = "daily{$loop365}reading"; echo $$dailyreading; echo " (Day $loop365)";
$date365t += 86400;
$date365 = date("Y-m-d", $date365t);
 
echo "#"; echo ${$answerloop365}; echo "#"; 
?>"><?php echo $loop365; ?></span></td>
<td align="center">
<input type='checkbox' value="0" title="<?php 
  echo "Daily reading for ".date('F jS',mktime(0,0,0,1,$loop365)); $dailyreading = "daily{$loop365}reading"; echo $$dailyreading; echo " (Day $loop365)"; ?>" value='1' name="answer<?php echo ($loop365+1); ?>" />
</td><?php
 
$answerloop365 = ${'answer'.$loop365};
 
if ( $answerloop365 == '1' ) {
$date1 = date('Y-m-d');
$sql1 = "UPDATE $createtablename SET date='$date1', answer='$answerloop365' WHERE id = ( '$loop365' );";
mysql_query($sql1) or die ("Error in query: $sql1. ".mysql_error());
echo "<b>INSERTED</b>";
} else {
echo "NOT READY TO INSERT";
}
 
}
echo '</tr></table>';
 
?>
 
<table width="650" border="0">
<tr>
<td>
<br>
<input type="submit" value="Update All 365 Days Now!"><input type="Reset">
</form>
</td>
</tr>
</table>

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-07-05 at 19:02:09ID24545437
Tags

php

,

loop

,

sql update

Topics

PHP Scripting Language

,

PHP and Databases

,

MySQL Server

Participating Experts
1
Points
500
Comments
15

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Angel Devoid installation
    I bought a game entitled "Angel Devoid" for MS-DOS. I am running a Win95 system. When I installed, many times it would freeze up during installation. I created a boot-disk (also worked if running in REAL-DOS mode) and it installed fine. However, I have not found a w...
  2. game speed
    can anybody give an explanation why older games run really quickly on new machines? how are current games developed such that it runs at a certain max speed. Someone told me it was the screen refresh rate but that doesn't sound right
  3. PHP Development for Multiplayer Game
    I'm planning to develop a multiplayer game that running on Linux server using PHP & MYSQL & Flash. Flash & PHP will be used for the front end, and I am thinking to use PHP as the back end or the game engine. Do you think I can use PHP as the backend / engine? It i...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: profyaPosted on 2009-07-06 at 02:56:50ID: 24783714

Error line 49: $$dailyreading

 

by: profyaPosted on 2009-07-06 at 04:05:48ID: 24783997

You need to add a hidden input to handle the case of form submit. I changed the way the check boxes appear, I used control arrays in stead of answer1, answer2 ... there is a simple javascript code to select check boxes selected by the user when the form is postback. I hope this helps.
Try the following code:

<?php
$selectedValues="";
if (isset($_POST['formPosted']) && $_POST['formPosted']==1)
{//Form has been submitted
	$answers=isset($_POST['answer'])?$_POST['answer']:'';
	if (count($answers)>0)
	{
		foreach ($answers as $answer)
		{
			$date1 = date('Y-m-d');
			$sql= "UPDATE $createtablename SET date='$date1', answer='1' WHERE id = ( '".$answer."' );";
			mysql_query($sql) or die ("Error in query: $sql1. ".mysql_error());
			echo "<b>INSERTED</b>";
			} else {
			echo "NOT READY TO INSERT";
			}
 
		}
		$selectedValues= implode (",", $answers);
	}
}
 
$date365t = mktime(0, 0, 0, 1, 0, date('Y'));
$date365 = date("Y-m-d", $date365t);
?>
<form name=form1 method="post" action="">
<input type="hidden" name="formPosted" value="1">
<table width=650><tr>
<?php
	for($loop365=1;$loop365<=365;$loop365++)
	{
		  if(($loop365-1)%15==0)
		  echo '</tr><tr>';
?>
	  <td align="center">
		  <span title="
		  <?php
			echo "Daily reading for ".date('F jS',mktime(0,0,0,1,$loop365)); $dailyreading = "daily{$loop365}reading"; echo $dailyreading; echo " (Day $loop365)";
			$date365t += 86400;
			$date365 = date("Y-m-d", $date365t);
 
			echo "#"; echo $loop365; echo "#";
		  ?>
		  ">
				<?php echo $loop365; ?>
		  </span>
	    </td>
		<td align="center">
			<input type='checkbox' title="
			<?php
			  echo "Daily reading for ".date('F jS',mktime(0,0,0,1,$loop365)); $dailyreading = "daily{$loop365}reading"; echo $dailyreading; echo " (Day $loop365)"; ?>" value='<?php echo ($loop365+1);?>' id='answerNo<?php echo ($loop365+1);?>' name="answer[]"
			 />
		</td>
<?php
 
	}
 
?>
 
<table width="650" border="0">
<tr>
<td>
<br>
<input type="submit" value="Update All 365 Days Now!"><input type="Reset">
</form>
<script type="text/javascript">
var selectedValues="<?php echo $selectedValues;?>";
var selValuesAr=selectedValues.split(',');
for (i=0; i<selValuesAr.length; i++)
{
	id="answerNo"+selValuesAr[i];
	alert(document.getElementById(id));
 
	if (document.getElementById(id))
	{
		alert('dsfjlsdfjsl');
		document.getElementById(id).checked=true;
	}
}
</script>
</td>
</tr>
</table>

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:

Select allOpen in new window

 

by: bschwartingPosted on 2009-07-06 at 04:45:41ID: 24784197

profya, thanks for this!  when I try to use it, I get the white screen of death.  I've looked through all your code and can't find the error.  maybe you can assist?

 

by: profyaPosted on 2009-07-06 at 04:57:23ID: 24784262

You are right, I have added the code that saves data to the database later, I didn't check it. There was a syntax error with it. I also liked the expression "the white screen of death", cool!
I am attaching you the revised code along with a screen capture of what I got when I ran it, I hope you find it useful. I have commented out database code and replaced it with an echo statement.

<?php
$selectedValues="";
$createtablename="mytable";
if (isset($_POST['formPosted']) && $_POST['formPosted']==1)
{//Form has been submitted
	$answers=isset($_POST['answer'])?$_POST['answer']:'';
	if (count($answers)>0)
	{
		foreach ($answers as $answer)
		{
			$date1 = date('Y-m-d');
			$sql= "UPDATE $createtablename SET date='$date1', answer='1' WHERE id = ( '".$answer."' );";
			echo "SQL: ", $sql, "<br>";
			/*mysql_query($sql) or die ("Error in query: $sql. ".mysql_error());
			if (mysql_affected_rows()>0)
				echo "<b>INSERTED</b>";
			else
				echo "NOT READY TO INSERT";
				*/
 
 
		}
		$selectedValues= implode (",", $answers);
	}
}
 
$date365t = mktime(0, 0, 0, 1, 0, date('Y'));
$date365 = date("Y-m-d", $date365t);
?>
<form name=form1 method="post" action="">
<input type="hidden" name="formPosted" value="1">
<table width=650><tr>
<?php
	for($loop365=1;$loop365<=365;$loop365++)
	{
		  if(($loop365-1)%15==0)
		  echo '</tr><tr>';
?>
	  <td align="center">
		  <span title="
		  <?php
			echo "Daily reading for ".date('F jS',mktime(0,0,0,1,$loop365)); $dailyreading = "daily{$loop365}reading"; echo $dailyreading; echo " (Day $loop365)";
			$date365t += 86400;
			$date365 = date("Y-m-d", $date365t);
 
			echo "#"; echo $loop365; echo "#";
		  ?>
		  ">
				<?php echo $loop365; ?>
		  </span>
	    </td>
		<td align="center">
			<input type='checkbox' title="
			<?php
			  echo "Daily reading for ".date('F jS',mktime(0,0,0,1,$loop365)); $dailyreading = "daily{$loop365}reading"; echo $dailyreading; echo " (Day $loop365)"; ?>" value='<?php echo ($loop365+1);?>' id='answerNo<?php echo ($loop365+1);?>' name="answer[]"
			 />
		</td>
<?php
 
	}
 
?>
 
<table width="650" border="0">
<tr>
<td>
<br>
<input type="submit" value="Update All 365 Days Now!"><input type="Reset">
</form>
<script type="text/javascript">
var selectedValues="<?php echo $selectedValues;?>";
var selValuesAr=selectedValues.split(',');
for (i=0; i<selValuesAr.length; i++)
{
	id="answerNo"+selValuesAr[i];
	if (document.getElementById(id))
	{
		document.getElementById(id).checked=true;
	}
}
</script>
</td>
</tr>
</table>

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:

Select allOpen in new window

 

by: bschwartingPosted on 2009-07-06 at 06:15:43ID: 24784810

that works great!

I'm missing two things now:

#1) Yours is doing the same thing, it's updating the next record instead of the record selected (see above where #1 updated id #2, should be id #1)
#2)  Once this is in the database, I need the script when it is first pulled up to see which of these are already a "1" and check them off

 

by: bschwartingPosted on 2009-07-06 at 06:21:43ID: 24784858

maybe something like this?

select id, answer from $createtablename where answer = 1

if answer = 1
$checked = checked
} else {
$checked = ' '

then make the input a variable for selected

<input type='checkbox' $checked />

 

by: profyaPosted on 2009-07-06 at 06:43:12ID: 24785074

#1) You are right, your code was using echo ($loop365+1), now change it to:
<?php echo ($loop365);?>
Line 55 in the code I have submitted, two positions need to change.
#2) hmmm. Theoretically, you get the data from the database and extract it as string, separated with comma, no trailing commas, for example this is good 1,20,40,100 but this is bad 1,20, 40,100,
assign the value you have extracted from the database in $selectedValues variable, the javascript code will then check the corresponding check boxes. Put this code in the ELSE clause of:
if (isset($_POST['formPosted']) && $_POST['formPosted']==1)

To be executed when the page has been loaded for the first time,

 

by: bschwartingPosted on 2009-07-06 at 07:04:25ID: 24785263

profya, for some reason i keep getting a bunch of records that won't update.  what is it looking at before it updates?

 

by: profyaPosted on 2009-07-06 at 07:11:15ID: 24785338

Excuse me, I didn't get your point. When this happens? When you click on the submit button? Try echoing the sql statement and see the logic, is there anything missing? specifically the WHERE clause.

 

by: bschwartingPosted on 2009-07-06 at 12:36:16ID: 24788491

When the date field is blank in the database, it will take the submit fine and update.  If there is a date in the database already, it won't update.

 

by: bschwartingPosted on 2009-07-06 at 12:51:53ID: 24788633

can you help me with #2?  not sure I am following.

 

by: profyaPosted on 2009-07-07 at 00:31:39ID: 24792070

MySQL ignores updating a record if the new values are similar to those values already exist. For example if the date is '1/1/2009', answer=1 and id=100, MySQL ignores
UPDATE myTable SET date='1/1/2009', answer='1' WHERE id=100
because it is none sense to update it to values it is already have.
If mysql_affected_rows()=0 and mysql_error()="" then mysql has ignored the update statement.

Regarding #2:
Add ELSE clause to the following IF statement:
if (isset($_POST['formPosted']) && $_POST['formPosted']==1)

In line 26, this code will be executed when the form is not yet submitted, the first time the page loaded. The code does the following:
1) Accesses the table and get answers where answer=1
2) Store those answers in a string variable comma separated.
Something like:

else
{
	$sql="SELECT id FROM $createtablename WHERE answer='1'";
	$rs=mysql_query($sql);
	$tempVar="";
	$delimiter="";
	if ($rs && mysql_num_rows($rs)>0)
	{
		while ($rec=mysql_fetch_array($rs))
		{
			$tempVar.=$delimiter.$rec['id'];
			$delimiter=",";
		}
 
		echo "Selected values from db: ", $tempVar;//Echo to see if it has been extracted properly, remove it when every this is fine.
	$selectedValues=$tempVar;
	}
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:

Select allOpen in new window

 

by: bschwartingPosted on 2009-07-07 at 07:19:47ID: 24794447

ok, that makes sense on the update routine.  

#2 works great!  you are a genius!

my last issue, #3, is my only remaining issue!  right now, when the page is 1st brought up, and all the boxes are checked, if the user has made a mistake, and wants to deselect the box, it never updates the answer to 0.  what is the best strategy for that?

 

by: profyaPosted on 2009-07-07 at 07:55:47ID: 24794771

There are tow appraoches you can select one of them:
1) Update all rows to zero first then apply user selections:
before the loop, UPDATE $createtablename SET answer='0' and execute the query, then the loop will run the query that updates user current selections.

2)If your table does not contain an autoincrement, the id is not an auto increment, then you can simply change the type of the update query, you can change it to delete first and then insert:
Before the loop:
DELETE FROM $createtablename and execute the query, then the loop will run the query that updates user current selections.

because your table always contains about 365 records, these addition queries will not affect the performance.

There are several methods also you can use, the above are the most appropriate to your condition as I can see. For example you can collect all ids for answer=1 in a variable similar to the technique I used to preselect on the first load, then run an update query after the loop completes something like
UPDATE $createtablename SET answer='0' WHERE ID NOT IN ('$selectedIdsVariable')

 

by: bschwartingPosted on 2009-07-07 at 10:40:31ID: 31600001

Genius, pure genius!

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...