PHP/MySQL - Disable radio option with count

Hey all i need a bit of help

I have a form that i need to disable certian radio selections (or hide them) when a mysql field count has reached x amount…

i have a field in sql called class_1 i need to count how many have selected option1, option2, and option3
then if count($class_1 == 10) hide or disable option1 raido … below is partial form code that i have…

what would the best way be to do this?
[php]

[/php]

the table structure

	 name 	varchar(50)
	 department 	varchar(100)
	 email 	varchar(75)
	 member 	varchar(8)
	 member_id 	varchar(30)
	 chapter 	varchar(255)
	 shirt 	varchar(18)
	 class_1 	varchar(10)
	 class_2 	varchar(10)
	 attending 	varchar(255)
	 hide 	varchar(2)
	 paid 	varchar(32)
First Class Choice:

None     Option A&C     Option A&D     Option B&C     Option B&D
Choose none if you will not be attending class

Here’s a demo, just change to your table name and db handler name

[php]<?php

$STH = $DBH->prepare(“SELECT
IF(COUNT(class_1) >= 10, ‘disabled’, null) as disabled
FROM data
WHERE class_1 = ?”);

$ids = array(‘Option A-C’, ‘Option A-D’, ‘Option B-C’, ‘Option B-D’);
$fields = array();

foreach ($ids as $id) {
$STH->execute(array($id));
$result = $STH->fetch();
$fields[$id] = $result[‘disabled’];
}
?>

First Class Choice:

None     <?php foreach ($fields as $id => $disabled) { ?> /><?= $id ?>    <?php } ?> Choose none if you will not be attending class

[/php]

Thanks for the fast reply, however i am unable to get that to work, getting :
Fatal error: Call to a member function prepare() on a non-object

at first i thought it may be a global issue so i added global $DBH as the first line but that didnt work??

Paste the code where you connect to the database. Remember to replace sensitive info like user/password

ok thanks for your help, and i do apologize for this but i am rather new to PDO, i tried your DB.php as the connection method from http://www.phphelp.com/forum/the-occasional-tutorial/using-php-with-databases-(pdo-tutorial)/ and got some wierd errors…

Fatal error: Call to undefined method DB::prepare()

i have triple checked the connection details and they are correct.
Here is my code:
[php]

<?php require_once ('./Connections/DB.php'); $DBH = new DB(); $STH = $DBH->prepare("SELECT IF(COUNT(class_1) >= 10, 'disabled', null) as disabled FROM data WHERE class_1 = ?"); $ids = array('Option A-C', 'Option A-D', 'Option B-C', 'Option B-D'); $fields = array(); foreach ($ids as $id) { $STH->execute(array($id)); $result = $STH->fetch(); $fields[$id] = $result['disabled']; } ?>

Second Annual Brothers of the Boot H.O.T. Conference


Please Fill out the form below to register for this event.

First and Last Name:
Department:
Email:
Current F.O.O.L.S. Member?:
Yes No
Member ID:

(Olny needed if yes to above)
Chapter:
Shirt Size:
Please Select Small Medium Large X-Large XX-Large XXX-Large

=========================================================
Note - Please make sure that you select a second option as you will be moved in the event the class is full
=========================================================

Training Classses - AM Block

Option A
Option B
Size Up
(Space is limited)
Mental Toughness
(Space is limited)
Presented by:
Presented by:
BOTB
Natural F.O.O.L.s
At Shreveport F.D. Training Grounds
At Shreveport F.D. Training Grounds
Classroom Training

H.O.T.
(Full PPE and SCBA Required)

Training Classses - PM Block

Option C
Option D
Leadership & Change
(Space is limited)
Vent, Enter, & Search
(Space is limited)
Presented by:
Presented by:
Chiefs Johnson & Walker
BOTB & Natural F.O.O.L.s
At Shreveport F.D. Training Grounds
At Shreveport F.D. Training Grounds
Classroom Training

H.O.T.
(Full PPE and SCBA Required)


First Class Choice:

None     <?php foreach ($fields as $id => $disabled) { ?> /> <?= $id ?>     <?php } ?> Choose none if you will not be attending class

First Class Choice:

None     <?php foreach ($fields as $id => $disabled) { ?> /> <?= $id ?>     <?php } ?> Choose none if you will not be attending class

In addition to Training

I Am Attending:

Opening Cerimonies Closing Cerimonies Bash
(select all that apply)

I Agree to bring all needed equipment with me.

[/php]

Didnt know you were using the tutorial, then you have to do $dbh-> query($sql, $params); inside the loop

ok i am having a really dense moment … not sure what you mean. :-[, i tried this …

[php]<?php
ini_set(‘error_reporting’, E_ALL);
ini_set(‘display_errors’, ‘1’);

try {
require_once (’./Connections/DB.php’);
$db = new DB();

} catch (Exception $e) {
echo ‘

Error:

’;
echo $e->getCode() . ‘: ’ . $e->getMessage();
echo ‘

Stack trace:

’;
foreach ($e->getTrace() as $trace) {
echo $trace[‘file’] . ’ Line #’ . $trace[‘line’] . ‘
’;
}
}
#$db-> query($sql, $params);
$STH = $db->prepare(“SELECT
IF(COUNT(class_1) >= 10, ‘disabled’, null) as disabled
FROM hot14
WHERE class_1 = ?”);
$ids = array(‘Option A-C’, ‘Option A-D’, ‘Option B-C’, ‘Option B-D’);
$fields = array();

foreach ($ids as $id) {
$STH->execute(array($id));
$result = $STH->fetch();
$fields[$id] = $result[‘disabled’];
}
?>[/php]

and got this:

[code]Notice: Undefined variable: sql in hot_reg14_2.php on line 17

Notice: Undefined variable: params in hot_reg14_2.php on line 17

Fatal error: Uncaught exception ‘PDOException’ with message ‘SQLSTATE[42000]:
Syntax error or access violation: 1065 Query was empty’ in DB.php:45
Stack trace:
#0 DB.php(45): PDO->prepare(’’)
#1 hot_reg14_2.php(17): DB->query(NULL, NULL)
#2 hot_2.php(53): include(’/homepages/23/d…’)
#3 {main} thrown in DB.php on line 45[/code]

and Dreamweaver is throwing errors on lines 44-58 of the DB.php
[php]<?php

class DB {

 /**
  *
  * PDO connection
  * @var PDO
  */
private $pdoConn = null;

/**
 * Class constructor
 */
public function __construct() {
   $this->_initDb();
}

/**
 * Get PDO database connection
 *
 * @return
 */
public function getPDOConn() {
   return $this->pdoConn;
}

/**
 * Init db connection
 */
private function _initDb() {
   $this->pdoConn = new \PDO('mysql:dbname=db451530158;host=db451530158.db.1and1.com;charset=utf8', 'dbo451530158', 'FOOLS2012');
   $this->pdoConn->exec("set names utf8");
   $this->pdoConn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
   $this->pdoConn->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
}

/**
 * Executes parametarized query
 * @param string $query
 * @param array $params
 * @param string $fetch_method
 */

public function query($query, $params = [], $fetch_method = ‘OBJ’, $class = ‘’) {
$stmt = $this->pdoConn->prepare($query);

   $result = $stmt->execute($params);
   
   if ($result) {
      $querybit = explode(" ", trim($query));
      if ($querybit[0] == 'SELECT') {
         if (strtoupper($fetch_method) === 'CLASS') {
            $ret = $stmt->fetchAll(constant('PDO::FETCH_CLASS'), $class);
         } else {
            $ret = $stmt->fetchAll(constant('PDO::FETCH_' . strtoupper($fetch_method)));
         }
      } else {
         $ret = [TRUE];
      }
   }      
   
   return !empty($ret) ? $ret : null;
}

/**
 * Get last inserted id
 *
 * @return integer
 */
public function getLastInsertedId() {
   return $this->pdoConn->lastInsertId();
}

/**
 * Generate unnamed placeholders.
 * Accepts an array of values that are to be inserted into the database.
 * 
 * @param array $array
 * @return string
 */
public function generatePlaceholders ($array) {
   return rtrim(str_repeat('?,', count($array)), ',');
}

}[/php]

not tested, but I meant you had to do something like this
[php]<?php
require_once (’./Connections/DB.php’);
$db = new DB();

$ids = array('Option A-C', 'Option A-D', 'Option B-C', 'Option B-D');
$fields = array();

foreach ($ids as $id) {
$db->query(‘SELECT
IF(COUNT(class_1) >= 10, ‘disabled’, null) as disabled
FROM data
WHERE class_1 = ?’,
array($id));
$result = $STH->fetch();
$fields[$id] = $result[‘disabled’];
}
?>[/php]

ok now we are getting somewhere …

[code]42000: SQLSTATE[42000]: Syntax error or access violation: 1064 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 ‘’, array(Option A-C)’ at line 4
Stack trace:

/homepages/23/d451520845/htdocs/Connections/DB.php Line #45
/homepages/23/d451520845/htdocs/forms/hot_reg14_2.php Line #17
/homepages/23/d451520845/htdocs/hot_2.php Line #53[/code]

Following the stack;
line 53 of hot_2.php:

<?php include ("./forms/hot_reg14_2.php"); ?>

line 17 of hot_reg14_2.php:

?>

line 45 of DB.php

$stmt = $this->pdoConn->prepare($query);

i don’t see the error…

[php]<?php
ini_set(‘error_reporting’, E_ALL);
ini_set(‘display_errors’, ‘1’);

try {
require_once (’./Connections/DB.php’);
$db = new DB();

  $ids = array('Option A-C', 'Option A-D', 'Option B-C', 'Option B-D');
  $fields = array();
 
 foreach ($ids as $id) {
   $db->query("SELECT
               IF(COUNT(class_1) >= 10, 'disabled', null) as disabled
               FROM hot14
               WHERE class_1 = ?',
               array($id)");
  $result = $STH->fetch();
  $fields[$id] = $result['disabled'];
}
} catch (Exception $e) {
echo '<h3>Error:</h3>';
echo $e->getCode() . ': ' . $e->getMessage();
echo '<h3>Stack trace:</h3>';
foreach ($e->getTrace() as $trace) {
   echo $trace['file'] . ' Line #' . $trace['line'] . '<br />';
}

}
?>[/php]

the DB.php is throwing syntax errors on 44-58 of DB.php
[php]<?php

class DB {

 /**
  *
  * PDO connection
  * @var PDO
  */
private $pdoConn = null;

/**
 * Class constructor
 */
public function __construct() {
   $this->_initDb();
}

/**
 * Get PDO database connection
 *
 * @return
 */
public function getPDOConn() {
   return $this->pdoConn;
}

/**
 * Init db connection
 */
private function _initDb() {
   $this->pdoConn = new \PDO('mysql:dbname=db451530158;host=db451530158.db.1and1.com;charset=utf8', 'dbo451530158', 'FOOLS2012');
   $this->pdoConn->exec("set names utf8");
   $this->pdoConn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
   $this->pdoConn->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
}

/**
 * Executes parametarized query
 * @param string $query
 * @param array $params
 * @param string $fetch_method
 */
public function query($query, $params = [], $fetch_method = 'OBJ', $class = '') {
   $stmt = $this->pdoConn->prepare($query);
   
   $result = $stmt->execute($params);
   
   if ($result) {
      $querybit = explode(" ", trim($query));
      if ($querybit[0] == 'SELECT') {
         if (strtoupper($fetch_method) === 'CLASS') {
            $ret = $stmt->fetchAll(constant('PDO::FETCH_CLASS'), $class);
         } else {
            $ret = $stmt->fetchAll(constant('PDO::FETCH_' . strtoupper($fetch_method)));
         }
      } else {
         $ret = [TRUE];
      }
   }      
   
   return !empty($ret) ? $ret : null;
}

/**
 * Get last inserted id
 *
 * @return integer
 */
public function getLastInsertedId() {
   return $this->pdoConn->lastInsertId();
}

/**
 * Generate unnamed placeholders.
 * Accepts an array of values that are to be inserted into the database.
 * 
 * @param array $array
 * @return string
 */
public function generatePlaceholders ($array) {
   return rtrim(str_repeat('?,', count($array)), ',');
}

}[/php]

MIght’ve been my mistake, not sure

[php]$db->query(“SELECT
IF(COUNT(class_1) >= 10, ‘disabled’, null) as disabled
FROM hot14
WHERE class_1 = ?’,
array($id)”);[/php]
should be

[php]$db->query(“SELECT
IF(COUNT(class_1) >= 10, ‘disabled’, null) as disabled
FROM hot14
WHERE class_1 = ?”,
array($id));[/php]

hey thanks for all your help, i know this is probably becoming a pain in the a$$, that fixed the stack however now it doesn’t like this
Sorry i am so dumb i am trying to learn.

$result = $STH->fetch();
Notice: Undefined variable: STH in hot_reg14_2.php on line 18
Fatal error: Call to a member function fetch() on a non-object in hot_reg14_2.php on line 18

ah, you don’t have the $STH variable/handler anymore

the query function in my DB class returns the result of fetchAll, so you only need to do something like this

$result = $db->query(…

then you should have the result in the $result variable. You might have to do some adjustments though so that you select the first element of the array ($result[0]), try to use var_dumps or other debugging to figure out what data you have/want :slight_smile:

ok i am soo lost now its not funny …

so i changed
$db->query("SELECT

to
$result = $db->query("SELECT
and now i get …

[code]Notice: Undefined index: disabled in /homepages/23/d451520845/htdocs/forms/hot_reg14_2.php on line 18

Notice: Undefined index: disabled in /homepages/23/d451520845/htdocs/forms/hot_reg14_2.php on line 18

Notice: Undefined index: disabled in /homepages/23/d451520845/htdocs/forms/hot_reg14_2.php on line 18

Notice: Undefined index: disabled in /homepages/23/d451520845/htdocs/forms/hot_reg14_2.php on line 18[/code]

[php]<?php
ini_set(‘error_reporting’, E_ALL);
ini_set(‘display_errors’, ‘1’);

try {
   require_once ('./Connections/DB.php');
   $db = new DB();
     
    $ids = array('Option A-C', 'Option A-D', 'Option B-C', 'Option B-D');
   $fields = array();
  
  foreach ($ids as $id) {
    $result = $db->query("SELECT
                IF(COUNT(class_1) >= 10, 'disabled', null) as disabled
                FROM hot14
                WHERE class_1 = ?',
                array($id)");
   $fields[$id] = $result['disabled'];
 }
} catch (Exception $e) {
 echo '<h3>Error:</h3>';
 echo $e->getCode() . ': ' . $e->getMessage();
 echo '<h3>Stack trace:</h3>';
 foreach ($e->getTrace() as $trace) {
    echo $trace['file'] . ' Line #' . $trace['line'] . '<br />';
 }

}
?>[/php]

That’s why I said you should try debugging, in line 18 you try to use $result[‘disabled’], a good place to start would be to check what $result contains.

ok so i added

[php] ##Debugging
echo “
”;
echo “

”;
print_r ($db);
print_r ($result);
print_r ($fields);
print_r ($id);
echo “
”;[/php]

and the result is:

[code]DB Object
(
[pdoConn:DB:private] => PDO Object
(
)

)
Array
(
[0] => 1
)
Array
(
[Option A-C] =>
[Option A-D] =>
[Option B-C] =>
[Option B-D] =>
)
Option B-D[/code]

hey Jim thanks for all the help so far and i am sorry to say that i am still unable to see what i am doing wrong.

bump?

Your problem is here

[php]$fields[$id] = $result[‘disabled’];[/php]

You get an undefined index error, it’s because the query function in the db class returns an array of results. so even if you get only one result it will be in $results[0] <-- your data here. So $result[‘disabled’] should really be $result[0][‘disabled’]

ok i changed that in the code and now i get no errors but its also not disableing the options even though i set the limit to 1 and add a row in the db with that option …

debug…

Try to run the query manually in sql and see what response you get. Does it say true (1) ?

If so, dump out the result array, what data is in there?

Sponsor our Newsletter | Privacy Policy | Terms of Service