WEB Mysql / PHP Crew: Help me out with this idea

Discussion in 'OT Technology' started by Ricky, Apr 16, 2009.

  1. Ricky

    Ricky █▄ █▄█ █▄ ▀█▄

    Joined:
    Jun 17, 2005
    Messages:
    38,767
    Likes Received:
    6
    I just want someone to point me in the correct direction because im completely lost on how i'd do this.

    So lets say i have a form with checkboxes like so:

    [] joe
    [] sarah
    [] dugg
    [] michael

    and a mysql table arranged like this:

    id ... name ... age


    Now how can i have it, so lets say i only select Joe and Sarah, to have the age on each of those rows listed in an html field for only the selected checkboxes.

    Thanks. I really hope someone can kind of understand what im trying to do.
     
  2. crazybenf

    crazybenf Active Member

    Joined:
    Nov 14, 2001
    Messages:
    15,578
    Likes Received:
    3
  3. Ricky

    Ricky █▄ █▄█ █▄ ▀█▄

    Joined:
    Jun 17, 2005
    Messages:
    38,767
    Likes Received:
    6
    Basically i set all my stuff to use an array and did a foreach to list all the rows.

    But i want to only list the rows selected from the form's checkboxes
     
  4. Insert Tokens

    Insert Tokens Making Cancer My Bitch OT Supporter

    Joined:
    Jan 12, 2006
    Messages:
    8,329
    Likes Received:
    76
    Location:
    Tasmania
    Are you ticking the boxes then clicking submit to get the results?

    If so, it's just a matter of adding into the loop if($checked) or some-such.
     
  5. kingtoad

    kingtoad OT Supporter

    Joined:
    Sep 2, 2003
    Messages:
    55,923
    Likes Received:
    11
    Location:
    Los Angeles
    If you're posting the data, you could filter it through something like this:

    Code:
    <?php
    
    foreach ($_POST['radio_field_array'] as $value) {
      print '<input type="radio" value="$value" />';
    }
    
    Or something like this might work too:
    Code:
    foreach ($key as $value) {
      if (!isset($value)) {
        continue;
      }
      print $value;
    }
    
     
    Last edited: Apr 16, 2009
  6. Ricky

    Ricky █▄ █▄█ █▄ ▀█▄

    Joined:
    Jun 17, 2005
    Messages:
    38,767
    Likes Received:
    6
    hmm interesting

    alright thanks i'll try those out
     
  7. Ricky

    Ricky █▄ █▄█ █▄ ▀█▄

    Joined:
    Jun 17, 2005
    Messages:
    38,767
    Likes Received:
    6
    alright im a little confused with your example. im kind of new so ive been reading up but its a little confusing still.

    basically this is a slimmed down example of what i have:

    Code:
    <form name="input" action="test2.php" method="post">
    <input type="checkbox" name="name_<?php echo $row['id']; ?>" value="1" />
    <input type="submit" value="Submit" />
    </form>
    
    and my original code was something like this, which just grabbed all the email rows

    Code:
    <?php
     $hostname = "x.net";  
     $db_username = "x";  
     $db_password = "x";  
      
     $conn = mysql_connect($hostname, $db_username, $db_password) or die("Cannot connect to the database");  
     mysql_select_db("x") or die("Cannot select the database");  
    
    
    $sql = "SELECT id, email FROM poll";
    $result = mysql_query( $sql,$conn );
    while( $row=mysql_fetch_row($result) )
    {
      $cat_titles[] = $row[1];
     
    }
    mysql_free_result( $result );
    
    
    ?>
    
    <?php
    
    echo "<p>\n";
    foreach( $cat_titles as $v )
    {
      echo $v."<br />\n";
    }
    echo "</p>\n";
    ?>
    
    :o
     
  8. brds

    brds OT Supporter

    Joined:
    Jun 26, 2006
    Messages:
    17,651
    Likes Received:
    15
    Location:
    Atlanta
    I might make the

    Code:
    value="<?php echo $row['id'];?>"
    This way each value is different... and not just 1. It'll make it easier to work with.

    I'm still a little unclear as to what you're doing. Are you going to show their ages on test2.php once somebody selects the name, or are you going to ask the user for their ages after they select the name. If you're going to ask for the age after name selection, you can do something like this:


    Code:
    <form action="test2.php" method="post">
          <table>
                <tr>
                      <td>&nbsp;</td>
                      <td>Name:</td>
                      <td>Age:</td>
                </tr>
                <?php
                      for ($i = 1; $i < count(people); $i++)
                      {
                      echo "
                            <tr>
                                  <td><input type='checkbox' name='" . $people[$i][ID] . "' /></td>
                                  <td>" . $people[$i][name] . "</td>
                                  <td><input type='text' name='age' /></td>
                            </tr>
                      ";
                      }
                ?>
                <tr><td colspan="3"><input type="submit" value="Submit &gt;&gt;" /></td></tr>
          </table>
    </form>
    
    Then on the test2 page, just run through the count of people... see if they're checked. If they are checked.... extend the array to hold their age too. You can then input their age into the DB by running an update query in a loop.


    If that wasn't what you were looking for, try to explain a little more clearly and i can help you out with it.
     
  9. Ricky

    Ricky █▄ █▄█ █▄ ▀█▄

    Joined:
    Jun 17, 2005
    Messages:
    38,767
    Likes Received:
    6
    what im trying to do is lets say there are a bunch of names.

    I want to be able to select lets say 3 names out of a list of 100. Then i would want to display the ages of those three names only. Their age is already inside of the database.

    Nothing is going to be inserted into the database. Just selected and echod
     
  10. Slid.

    Slid. I'm a guy.

    Joined:
    Oct 25, 2001
    Messages:
    1,928
    Likes Received:
    0
    Location:
    NH
    Your request isn't entirely clear but I decided to make a working example (no sql, but same premise):

    check.php:
    Code:
    <?
      
      /*
      Commented but this gives you an idea of how php handles the checkbox array ..
      
      foreach($_REQUEST['checkboxNames'] as $key => $value) {
        print "$key : $value <br>";
      }
      */
    
      // Basically a hard-coded version of your sql query:
      $peopleArray[1]['name'] = 'Joe';
      $peopleArray[1]['age'] = '20';
      $peopleArray[2]['name'] = 'Sarah';
      $peopleArray[2]['age'] = '23';
      $peopleArray[3]['name'] = 'Dugg';
      $peopleArray[3]['age'] = '25';
      $peopleArray[4]['name'] = 'Michael';
      $peopleArray[4]['age'] = '19';
    
    ?>
    
    <form action="check.php">
    <?
      foreach($peopleArray as $key=>$value) {
        
        $isChecked = 0;
        if($_REQUEST['checkboxNames'][$key]=='on') $isChecked = 1;
        
    ?>
        <input name="checkboxNames[<?=$key?>]" type="checkbox" <? if($isChecked) echo 'checked'; ?>> <?=$value['name']?> <? if($isChecked) echo ': ' . $value['age']; ?><br>
    <?
    
      }
      
    ?>
    <input type="submit">
    </form>
    
    As opposed to using $_REQUEST you should use $_POST or $_GET depending on your form.

    Also, a checkbox is checked with "checked" not with value="1".

    <input type="checkbox" checked> is valid
    <input type="checkbox" value="1"> is not

    Running example:
    http://www.linksling.com/check.php?checkboxNames[2]=on
     
  11. Ricky

    Ricky █▄ █▄█ █▄ ▀█▄

    Joined:
    Jun 17, 2005
    Messages:
    38,767
    Likes Received:
    6
    i think that's what i was looking for slid.

    thanks a lot.

    Im going to play around with it. :bowdown:

    thanks for all the help people
     
  12. Ricky

    Ricky █▄ █▄█ █▄ ▀█▄

    Joined:
    Jun 17, 2005
    Messages:
    38,767
    Likes Received:
    6
    Man i must really suck at php :o

    My array isnt coming up like your hardcoded one. For some reason its also only just showing the first character. Hmm maybe it's better to just show you my example:

    www.offtopic.me/test3.php

    and here's the coding i've used along with your example:

    Code:
    <?
    --connection stuff up here--
     
    $result = mysql_query("SELECT id, name, age FROM poll");
    $row = mysql_fetch_array($result, MYSQL_ASSOC);
    
    ?>
    
    <form action="test3.php">
    <?
      foreach($row as $key=>$value) {
        
        $isChecked = 0;
        if($_REQUEST['checkboxNames'][$key]=='on') $isChecked = 1;
        
    ?>
    
        <input name="checkboxNames[<?=$key?>]" type="checkbox" <? if($isChecked) echo 'checked'; ?>> <?=$value['name']?> <? if($isChecked) echo ': ' . $value['age']; ?><br>
    <?
    
      }
      
    ?>
    <input type="submit">
    </form>
    
     
  13. Slid.

    Slid. I'm a guy.

    Joined:
    Oct 25, 2001
    Messages:
    1,928
    Likes Received:
    0
    Location:
    NH
    Okay, this is what you want:

    Code:
    <?
    --connection stuff up here--
     
    // $result = mysql_query("SELECT id, name, age FROM poll");
    // $row = mysql_fetch_array($result, MYSQL_ASSOC);
    
    ?>
    
    <form action="test3.php">
    <?
    
      $result = mysql_query("SELECT id, name, age FROM poll");
    
      while($row = mysql_fetch_assoc($result)) {
        
        $isChecked = 0;
        if($_REQUEST['checkboxNames'][$row['id']]=='on') $isChecked = 1;
        
    ?>
        <input name="checkboxNames[<?=$row['id']?>]" type="checkbox" <? if($isChecked) echo 'checked'; ?>> <?=$row['name']?> <? if($isChecked) echo ': ' . $row['age']; ?><br>
    <?
    
      }
      
    ?>
    <input type="submit">
    </form>
    
    while($row = mysql_fetch_assoc($result)) { will loop through each row return from your query. You access the values in the associative array like:

    $row['value name'] :
    $row['id']
    $row['name']
    $row['age']

    I basically replaced $key with $row['id'] and $value['name'] with $row['name'] (same with age, $value['age'] becomes $row['age'].)
     
    Last edited: Apr 16, 2009
  14. brds

    brds OT Supporter

    Joined:
    Jun 26, 2006
    Messages:
    17,651
    Likes Received:
    15
    Location:
    Atlanta
    Try using my query class (DBconnect.php) - You wont have to change anything inside of it... just copy/paste it into a text file, rename to php and upload to website:

    Code:
    <?php
        // begin class
        class DatabaseConnector
        {
            private $dbConnection; // set private attributes
    
            // constructor - sets db connection settings
            public function __construct($host, $dbName, $userName, $userPass)
            {
                $this->host = $host;
                $this->dbName = $dbName;
                $this->userName = $userName;
                $this->userPass = $userPass;
            }
    
            // method used to connect to the database
            public function connectToDB()
            {
                $this->dbConnection = mysql_connect($this->host, $this->userName, $this->userPass);
                if (!($this->dbConnection))
                    echo "Unable to connect to the database: " . mysql_error() . "<br />";        
            }
    
            // method used to check the connection to the database
            public function checkConnection()
            {
                if (is_resource($this->dbConnection))
                    return true;
                else
                    return false;
            }
    
            // runs the user defined query
            public function runQuery($runMe)
            {
                if ($this->checkConnection()) // if the connection is a resource
                {
                    $returned = mysql_query($runMe, $this->dbConnection); // store the results in 'returned'
                    
                    //Make sure query returned results
                    if ($returned === false) // if there was an error during sql execution
                    {
                        echo "SQL Query error: " . mysql_error();
                    }
                        
                    if ($returned === true) // if a update, insert, delete, etc... command was run
                        return true;
                        
                    if (is_resource($returned)) // if a query was run that gave back results - store in array and return array
                    {
                        $outArray = array(); // returned array with query results
                            
                        for ($i = 0; $i < mysql_num_rows($returned); $i++)
                        {
                            $outArray[] = mysql_fetch_assoc($returned);
                        }
                    }
                        
                    if (count($outArray) < 1)
                        return null;
                    else
                        return $outArray;
                }
                else
                    echo "Your Database Connection Was Unable To Be Authenticated.";
            }
            
            public function disconnectFromDB() // disconnect from the db for security
            {
                if ($this->checkConnection())
                    mysql_close($this->dbConnection);
            }
        }
    ?>
    
    Initiate it like this (Only thing you should do here is set up the localhost, db name, username, password, and table name):

    Code:
    <?php 
        require('./DBconnect.php');
        $connection = new DatabaseConnector("localhost", "database_name", "user_name", "password");
        $connection->connectToDB();
        $use = "USE table_name;";
        $connection->runQuery($use);
    ?>
    

    Then, to run a query and store the results in an array, you can do this:

    Code:
    $queryresults = "SELECT id, name, age FROM poll";
    $queryresults = $connection->runQuery($queryresults);
    
    Now you have all your results inside of $queryresults like this:
    Code:
    Arrayslot 1 => id => first_id_value
    Arrayslot 1 => name => first_name_value
    Arrayslot 1 => age =>first_age_value
    
    Arrayslot  2 => id => second_id_value
    Arrayslot  2 => name => second_name_value
    Arrayslot 2 => age =>second_age_value
    
    ect.....
    
    From there, you can do a for loop like this:
    Code:
    for ($i = 0; $i < count($queryresults); $i++)
    {
    echo "
          #" . $i . " - ID: " . $queryresults[$i][id] . " - Name: " . $queryresults[$i][name] . " - Age: " . $queryresults[$i][age] . "<br />
    ";
    }
    
     
  15. Ricky

    Ricky █▄ █▄█ █▄ ▀█▄

    Joined:
    Jun 17, 2005
    Messages:
    38,767
    Likes Received:
    6
    thanks for much for the help guys.

    both are working great :bowdown:
     
  16. Ricky

    Ricky █▄ █▄█ █▄ ▀█▄

    Joined:
    Jun 17, 2005
    Messages:
    38,767
    Likes Received:
    6
    Last question (i promise)

    So i got slid's example working at www.offtopic.me/test

    but as you can see, when you submit it, it places the email underneath the div. then does the loop and places the second one underneath that. How will i go about placing both of those together, sepeartly outside of the loop if that makes any sense.

    Like in the script i found that it only works if its inside of the while and before the ending here:

    Code:
    <?
    
      }
      
    ?>
    
    I just want to put all the emails together in one separate form field/div
     
  17. Slid.

    Slid. I'm a guy.

    Joined:
    Oct 25, 2001
    Messages:
    1,928
    Likes Received:
    0
    Location:
    NH
    Post your entire code snippet.
     
  18. Ricky

    Ricky █▄ █▄█ █▄ ▀█▄

    Joined:
    Jun 17, 2005
    Messages:
    38,767
    Likes Received:
    6
    Code:
    <html>
    <head>
    </head>
    <body>
    	<?php
    	include("config.php");
    	$result = mysql_query("SELECT id, name, email, city, state, country, url FROM poll");
    	?>
    
    		<form action="index2.php">
    		<?
    
    
    		  while($row = mysql_fetch_assoc($result)) {
    
    		    $isChecked = 0;
    		    if($_REQUEST['checkboxNames'][$row['id']]=='on') $isChecked = 1;
    
    		?>
    	
    	<div id="wrap">
    		<div id="leftcolumn"> <input name="checkboxNames[<?=$row['id']?>]" type="checkbox" <? if($isChecked) echo 'checked'; ?>>
    			<a href='<?php echo $row['url']; ?>'> <?php echo $row['name']; ?> </a>
    			 
    		 </div>
    		<div id="rightcolumn"><br> <?=$row['city']?>, <?=$row['state']?> <br>
    		 </div>
    	</div>
    [B]	<?if($isChecked) echo $row['email'];?>
    [/B]	<? }
    
    	?>
    
    	<input type="submit">
    	</form>
    </body>
    </html>
    
     
  19. Slid.

    Slid. I'm a guy.

    Joined:
    Oct 25, 2001
    Messages:
    1,928
    Likes Received:
    0
    Location:
    NH
    Okay, this will put all of the selected email's into a text area at the bottom of the page.

    Code:
    <html>
    <head>
    </head>
    <body>
    	<?php
    	include("config.php");
    	$result = mysql_query("SELECT id, name, email, city, state, country, url FROM poll");
    	?>
    
    	<form action="index2.php">
    	<?
    
    	  while($row = mysql_fetch_assoc($result)) {
    
    	    $isChecked = 0;
    	    if($_REQUEST['checkboxNames'][$row['id']]=='on') $isChecked = 1;
    	    
    	    // Create a comma separated list of emails selected
    	    [b]if($isChecked) $emailThing .= $row['email'] . ',';[/b]
    
    	?>
     
    	<div id="wrap">
    		<div id="leftcolumn"> <input name="checkboxNames[<?=$row['id']?>]" type="checkbox" <? if($isChecked) echo 'checked'; ?>>
    			<a href='<?php echo $row['url']; ?>'> <?php echo $row['name']; ?> </a>
    			 
    		 </div>
    		<div id="rightcolumn"><br> <?=$row['city']?>, <?=$row['state']?> <br>
    		 </div>
    	</div>
    	
    	<? 
    	
    	  }
    	  
    	  // Remove the last comma
    	  [b]$emailThing = substr($emailThing, 0, strlen($emailThing)-1);[/b]
    	  
    	?>
    	
      <?
        // only display if we have something to show ..
        if($emailThing!='') {
      ?>
      	<!-- display them after the loop -->
      	[b]<input type="text" name="emails" value="<?=$emailThing?>"><br>[/b]
      
      <?
        }
      ?>   
    
    	<input type="submit">
    	</form>
    </body>
    </html>
    
     
  20. Slid.

    Slid. I'm a guy.

    Joined:
    Oct 25, 2001
    Messages:
    1,928
    Likes Received:
    0
    Location:
    NH
    For reference if things aren't display in the order that you want / expect then just View Source for the html. Your setup was sandwiching the email addresses between the DIVs (because it's a loop).

    If you ever want to grab something from a loop and display it at the bottom (totals or whatever) you should save whatever that piece of data is to a variable and then output it later.
     
  21. Ricky

    Ricky █▄ █▄█ █▄ ▀█▄

    Joined:
    Jun 17, 2005
    Messages:
    38,767
    Likes Received:
    6
    thank you so much slid.

    i love you <3
     

Share This Page