Quick 5 min tutorial :)

Post all your tuts or request for tuts here.
Post Reply
User avatar
Torniquet
Posts: 869
Joined: Sun Aug 02, 2009 6:18 am

Quick 5 min tutorial :)

Post by Torniquet »

Ok just a quick tutorial on how to manipulate dynamic information using checkboxes to select the elements.

Lets make take a scenario in which you might find this useful.

You want to 'throw away' items from your inventory. doing this one by one can be tedious if you have alot of things in your inventory.

lets take 5 items.

Sword
Chainmail
Mace
Steel Helmet
Shield

obviously this list of items will be dynamically generated based on the contents of your database. Throwing away 4 out of 5 items is not a major problem. But what if you wanted to throw away 60 out of 70 items. clicking the delete buttons 60 times is boring, slow and a real offput.

so we add a checkbox next to each one and give them the same name array by placing '[]' at the end of the name attribute.

Code: Select all

while($row = $sql->fetch_assoc()){
 echo $row['item_name'] . " <input type='checkbox' name='item[]' value='$row[item_id]' /><br />";
}
echo "<input type='submit' value='Throw Away' name='throwItem' />";
 
Now we have generated our list of item with a checkbox next to each one, we need to write the small amount of code to make an action against each box that is selected.

We have given each checkbox a value of the item id which should be unique and which we can reference the appropriate row in the database.

So, we now want the little piece of code to run which will remove the items from the database. We will do this by using the foreach command.

So check that the button has been pressed to throw the items away.

Code: Select all

if(isset($_POST['throwItem'])){

}
 
If the button has been pressed, we can run the foreach loop and make an action against each of the items selected.

Code: Select all

if(isset($_POST['throwItem'])){

  foreach($_POST['item'] as $v){
    
    $sql->query("DELETE FROM inventory WHERE item_id='$v'");

  }

  echo 'Items have been deleted!';

}
 
Thats simple enough no?

The foreach is taking the value ($v) of each element in the item array, which is accessed by the $_POST['item']. Then inside the foreach loop we access the value by using the $v variable.

Now you have the simple code, you can expand it to do more, for example selling or buying items. Handing over multiple items in trades or for quests. etc


Hope thats simple enough to understand :)

off to bed now.

Night x
New Site Coming Soon! Stay tuned :D
Mehtab
Posts: 27
Joined: Fri Apr 08, 2011 8:06 pm

Re: Quick 5 min tutorial :)

Post by Mehtab »

nice tutorial. Keep it coming
Post Reply

Return to “Tutorials”