Jump to content

about looping


ted_chou12

Recommended Posts

If I am looping something, for example, a number. and every time this variable goes through a loop, the number increases by one integer, where my php form has a form action that also uses a loop to handle the action, what should I put for the while loop that handles the action?
This is what I started with:
while ($id != ""){}
but $id should be a variable that represents that figure.
Ted
Thanks
Link to comment
Share on other sites

Well you would need a breaking clause to stop the loop otherwise it can loop continuously and crash your system.  So something like
[code]
<?php
while ($id != "" && $id < 25) // If you want it to loop 25 times
{
    $id++
}
?>
[/code]

But thats pretty useless on it's own, not sure what your trying to do.  Hope that helps
Link to comment
Share on other sites

um... i think is better to put some code up, because $id is still an undefined variable:
this is the loop that generates the request for the action:
[code]
$id = 0;
while ($r = mysql_fetch_array($res)){
echo "<input type=checkbox name=$id value=\"$string\">";//ignore string
$id ++;}
[/code]
and this is what takes the action:
[code]
while ($id != ""){$id = $_POST['id']; //and action will be below
$id++;}
[/code]
but $id is not defined... so i am having a problem...
btw, I removed the form tags as well as the $_POST submit to make it simple.
Thanks
Ted
Link to comment
Share on other sites

Ted, you're not making any sense to me I'm afraid...  What do you mean by [i]'and this is what takes the action'[/i]?

The first loop looks as though it should work ok.  Perhaps you should be telling us what you're trying to achieve, rather than what you think the code should look like?

Regards
Huggie
Link to comment
Share on other sites

ok. :-\, i think im making it more complicated...:
[code]
<?php
if(isset($_POST['delete'])){
while ($id != ""){
$id = $_POST['id'];
require("../mysqlconnection.php");
$delete = mysql_query("DELETE FROM pm WHERE id='$id' AND username='$username'");
$id++;}}?>

<form name="pm" action="" method="post">
<?php
$id = 0;
while ($r = mysql_fetch_array($res)){
echo "<td align=center><input type=checkbox name=$id value=\"". $r['id'] ."\"></td>\n";
$id ++;}
?>
<input class="button" name="delete" type="submit" value="Delete Entry" />
</form>
[/code]
Link to comment
Share on other sites

OK, this is a mess, but we can help you straighten it out.

I'm still unclear, as you still haven't said what you're trying to achieve, can you give us an idea?  Maybe some examples of what's going to be submitted and what's being pulled by the database.  Spend a decent amount of time outlining and explaining the problem and we'll get you a solution sooner and with less posts :)

Regards
Huggie
Link to comment
Share on other sites

ok,cool 8)
I wish the form to be able to take multiple actions, so the php script will delete each row that is specified in the checkbox, value=". $r['id'] ." is the value of the checkbox, where id is the primary key to mysql table. Since the script loops until all the rows are displayed, therefore, there will be an unfix number of checkboxes, so I want the checkboxes to be able to multiple selected, and therefore deleting multiple rows from the table at once.
I think that explains my goal.
Ted
Link to comment
Share on other sites

OK,

If I understand it correctly, what you want to do is present multiple rows on a page, e.g. member list, each member has a check box next to their name and I can select the boxes and press the delete button at the bottom of the page to remove them from the database?

Regards
Huggie
Link to comment
Share on other sites

OK, in that case I'd use a different method completely... I'd construct a sql string first of all and remove them that way...

[code]<?php
if (isset($_POST['delete'])){
  if (!empty($_POST['id'])){
      // turn the id array into a comma separated string
      $id_list = implode(", ", $_POST['id']);

      // Query to run
      $sql = "DELETE FROM messages WHERE message_id IN ($id_list)";
      mysql_query($sql);
  }
}

// Select message list from database
$sql = "SELECT message_id, message_text FROM messages WHERE user_id = '{$_SESSION['user_id']}'";
$result = mysql_query($sql);

// Echo the messages and checkboxes
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
  echo "<input type=\"checkbox\" name=\"id[]\" value=\"{$row['message_id']}\"> {$row['message_text']}<br>\n";
}

// Echo the submit button
echo "<input type=\"submit\" name=\"delete\" value=\"Delete\">\n";
?>[/code]

You could use a foreach() loop or a while() loop, but this way is more efficient as it only queries the database with the delete code once.

Regards
Huggie
Link to comment
Share on other sites

thanks a lot, but some things inside looks brand new to me, like:
{$row['message_id']} {$row['message_text']}
and as well as the delete codes, I have a pagination code as well, I am getting a bit confused...
here is how to page code looks like originally:
[code]
                              <?php //Javascript for the delete, this helps to select all checkboxes?>
<SCRIPT LANGUAGE="JavaScript">
<!-- Modified By:  Steve Robison, Jr. (stevejr@ce.net) -->
<!-- Begin
var checkflag = "false";
function check(field) {
if (checkflag == "false") {
for (i = 0; i < field.length; i++) {
field[i].checked = true;}
checkflag = "true";
return "Uncheck All"; }
else {
for (i = 0; i < field.length; i++) {
field[i].checked = false; }
checkflag = "false";
return "Check All"; }
}
//  End -->
</script>
<?php //the delete code.
                                      if(isset($_POST['delete'])){
while ($id != ""){
$id = $_POST['id'];
require("../mysqlconnection.php");
$delete = mysql_query("DELETE FROM privatemessages WHERE id='$id' AND username='$username'");
if($delete === false)
{echo"<p><b>Sorry, the database is temporary down, please come back later!</b></p>";}
else
{header("location: confirm.php?confirm=pm_delete");}}}?>

<form name="deletepm" action="" method="post">
<?php //below is all the pagination code.
//order sort
$order = $_GET['order'];
if ($order == "senderasc") {$orderby = "ORDER BY username"; $menu1 = "v";}
elseif ($order == "senderdes") {$orderby = "ORDER BY username DESC"; $menu1 = "^";}
elseif ($order == "subjectasc") {$orderby = "ORDER BY entrytitle"; $menu2 = "v";}
elseif ($order == "subjectdes") {$orderby = "ORDER BY entrytitle DESC"; $menu2 = "^";}
elseif ($order == "dateasc") {$orderby = "ORDER BY entrydate"; $menu3 = "v";}
else {$order = "datedes";$orderby = "ORDER BY entrydate DESC"; $menu3 = "^";}

if ($order == "senderasc") {$ordersendermenu = "senderdes";}
else {$ordersendermenu = "senderasc";}

if ($order == "subjectasc") {$ordersubjectmenu = "subjectdes";}
else {$ordersubjectmenu = "subjectasc";}

if ($order == "dateasc") {$orderdatemenu = "datedes";}
else {$orderdatemenu = "dateasc";}

// connect to mysql below
require("../mysqlconnection.php");

// Set how many rows to display on each page
$limit = 20;
// Query the database to get the total number of rows
$query_count = "SELECT * FROM privatemessages WHERE username='$username' AND type='inbox'";
  $result_count = mysql_query($query_count) or die (mysql_error());
$totalrows = mysql_num_rows($result_count);
if(isset($_GET['page'])){    // Checks if the $page variable is empty (not set)
$page = $_GET['page'];      // If it is empty, we're on page 1
} else {
$page = 1;
}
// Set the start value
$startvalue = $page * $limit - ($limit);
// Query the database and set the start row and limit
$sql = "SELECT * FROM privatemessages WHERE username='$username' AND type='inbox' $orderby
LIMIT $startvalue, $limit";
  $res = mysql_query($sql) or die (mysql_error());
echo "<table border=0 align=center cellpadding=\"0\" cellspacing=\"1\" width=\"100%\">
<tr height=\"28em\">
<td width=\"28em\" align=center background=\"gradient.gif\"><img src=\"images/xx.gif\"></td>
<td width=\"28em\" align=center background=\"gradient.gif\">
<input type=checkbox value=\"Check All\" onClick=\"this.value=check(action)\"></td>
<td width=\"80em\" background=\"gradient.gif\">
<a href=\"".$_SERVER['PHP_SELF']."?page=".$page."&order=".$ordersendermenu."\"><b>".$menu1." Sender</b></a></td>
<td width=\"160em\" background=\"gradient.gif\">
<a href=\"".$_SERVER['PHP_SELF']."?page=".$page."&order=".$ordersubjectmenu."\"><b>".$menu2." Subject</b></a></td>
<td width=\"70em\" background=\"gradient.gif\">
<a href=\"".$_SERVER['PHP_SELF']."?page=".$page."&order=".$orderdatemenu."\"><b>".$menu3." Date</b></a></td>
</tr>";
// Do a quick check to see if there are any records to display
if(mysql_num_rows($res) == 0){
echo "<tr>
<td colspan=3 align=center>No messages found!!</td>
  </tr>";
}
// Start loop through records
$id = 0;
while ($r = mysql_fetch_array($res)){

$date = strtotime($r['entrydate']) + $row['timeoffset'];
$date = date('Y-m-d',$date);
$subject = substr($r['entrytitle'], 0, 30);
if (strlen($r['entrytitle']) > 30){$subject = "$subject..";}
$user = substr($r['user'], 0, 10);
if (strlen($r['user']) > 10){$user = "$user..";}
if ($r['flag'] == "unread") {$color = "#cccccc";}
else {$color = "#f2f2f2";}


// This is actually where the form goes...
echo "<tr height=\"25em\" bgcolor=".$color.">\n";
echo "<td align=center><img src=\"images/". $r['entryicon'] .".gif\"></td>\n";
echo "<td align=center><input type=checkbox name=$id value=\"". $r['id'] ."\"></td>\n";
echo "<td>". $user ."</td>\n";
echo "<td><a href=\"viewpm.php?id=". $r['id'] ."\">". $subject ."</a></td>\n";
echo "<td>". $date ."</td>\n";
echo "</tr>\n";
$id ++;}
// Close the table
echo "</table>";
// Start links for pages
echo "<p align=center>";

// Sets link for previous 25 and return to page 1
if($page != 1){
$pageprev = ($page - 1);
echo "<a href=\"".$_SERVER['PHP_SELF']."?page=1&order=$order\"><<</a>&nbsp;&nbsp;";
echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$pageprev&order=$order\">PREV&nbsp;</a> ";
}else{
echo "PREV&nbsp;";
}
// Find out the total number of pages depending on the limit set
$numofpages = $totalrows / $limit;
$totalpages = ceil($numofpages);
// Loop thru all the pages and echo out the links
for($i = 1; $i <= $numofpages; $i++){
if($i == $page){
echo "[".$i."] ";
}else{
echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$i&order=$order\">$i</a> ";
}
}

// Check for straglers after the limit blocks
if(($totalrows % $limit) != 0){
if($i == $page){
echo "[".$i."] ";
}else{
echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$i&order=$order\">$i</a> ";
}
}
// Print out the Next 25 and Goto Last page links
if(($totalrows - ($limit * $page)) > 0){
$pagenext = ($page + 1);
  echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$pagenext&order=$order\">NEXT&nbsp;</a>&nbsp;&nbsp;";
  echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$totalpages&order=$order\">>></a>&nbsp;&nbsp;";
}else{
echo("NEXT");
}
echo "</p>";
// Free results
mysql_free_result($res);
// Close mysql connection
mysql_close($mysql_conn);?>
<input class="button" name="delete" type="submit" value="Delete Entry" onClick="javascript: return checkDelete()" />
</form>
[/code]
Can you roughly point out where I should put these separatly?
Thanks
Ted
Link to comment
Share on other sites

[quote author=ted_chou12 link=topic=122076.msg503020#msg503020 date=1168604014]
thanks a lot, but some things inside looks brand new to me, like:
{$row['message_id']} {$row['message_text']}[/quote]

OK, it's just the way that I'm displaying the variables without exiting the echo... You're probably used to writing it like this...

[code=php:0]echo '<input type="checkbox" name="id[]" value="' .$row['message_id']. '">' .$row['message_text']. '<br>';[/code]

Regards
Huggie
Link to comment
Share on other sites

then please - instead of just getting others to write the code and others to patch them up, you do yourself many many many favours if you actually took the time to understand the code like the rest of us.

not being rude, ted - just that almost 99% of every question you have is regarding someone elses script.
Link to comment
Share on other sites

[quote author=redbullmarky link=topic=122076.msg503027#msg503027 date=1168604606]
then please - instead of just getting others to write the code and others to patch them up, you do yourself many many many favours if you actually took the time to understand the code like the rest of us.

not being rude, ted - just that almost 99% of every question you have is regarding someone elses script.
[/quote]

That's a little bit harsh... He's trying look:

[quote author=ted_chou12 link=topic=122076.msg503020#msg503020 date=1168604014]
thanks a lot, but some things inside looks brand new to me, like:
{$row['message_id']} {$row['message_text']}
[/quote]

I don't suffer fools gladly, but I try my best to steer them on the right path at least twice before reprimanding them :)

Regards
Huggie
Link to comment
Share on other sites

No problem, like I said, if you take your time explaining things in the first instance then you'll get things resolved quicker and in this case maybe even offered some alternative code that will work more efficiently.

Had I not have asked and just tried to understand what you were doing with your code, we'd have ended up with something similar to what you'd written that worked, but wasn't very effective.

Regards
Huggie.
Link to comment
Share on other sites

[quote author=ted_chou12 link=topic=122076.msg503020#msg503020 date=1168604014]
thanks a lot, but some things inside looks brand new to me, like:
{$row['message_id']} {$row['message_text']}

[/quote]

If those things are new to you then it's very unlikely that the code is your own - it's full of similar associative references. PHPFreaks is not here to provide a free service to modify other peoples code to suit your needs, it's to help you with your own code - read the forum guidelines.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.