Page 1 of 2

multiple checkbox storing and retrieving

Posted: Tue Jan 14, 2014 7:57 am
by jaad
I have gone through dozens and dozens of example on how to store multiple checkbox values into mysql and then retrieve them on the same form for update if necessary but none of the example I've tried seem to work.


here is my

Code: Select all

<form action="" method="post" enctype="multipart/form-data">
 <input type="checkbox" name="co_app[]" id="co_app1" value="spouse"> Spouse
 <input type="checkbox" name="co_app[]" id="co_app2" value="roommate"> Roommate
 <input type="checkbox" name="co_app[]" id="co_app3" value="none"> None
</form>
here is my calling function:

Code: Select all

$users->update_user($first_name, $middle_name, $last_name, $gender, $dob, $sin, $home_phone, $cell_phone, $emerg_name,$emerg_email, $emerg_phone, $co_app, $co_name, $bio, $image_location, $user_id);
					header('Location: settings.php?success');
					exit();
				
				} else if (empty($errors) === false) {
					echo '<p>' . implode('</p><p>', $errors) . '</p>';	
				}	
            }
here is my update function

Code: Select all

public function update_user($first_name, $middle_name, $last_name, $gender, $dob, $sin,$home_phone, $cell_phone, $emerg_name,$emerg_email, $emerg_phone, $co_app, $co_name, $bio, $image_location, $id){
		
		

		$query = $this->db->prepare("UPDATE `users` SET
								`first_name`	= ?,
								`middle_name`	= ?,
								`last_name`		= ?,
								`gender`		= ?,
								`dob`			= ?,
								`sin`			= ?,
								`home_phone`	= ?,
								`cell_phone`	= ?,
								`emerg_name`	= ?,
								`emerg_email`	= ?,
								`emerg_phone`	= ?,
								`co_app`		= ?,
								`co_name`		= ?,
								`bio`			= ?,
								`image_location`= ?
								
								WHERE `id` 		= ? 
								");

		$query->bindValue(1, $first_name);
		$query->bindValue(2, $middle_name);
		$query->bindValue(3, $last_name);
		$query->bindValue(4, $gender);
		$query->bindValue(5, $dob);
		$query->bindValue(6, $sin);
		$query->bindValue(7, $home_phone);
		$query->bindValue(8, $cell_phone);
		$query->bindValue(9, $emerg_name);
		$query->bindValue(10, $emerg_email);
		$query->bindValue(11, $emerg_phone);
		$query->bindValue(12, $co_app);
		$query->bindValue(13, $co_name);
		$query->bindValue(14, $bio);
		$query->bindValue(15, $image_location);
		$query->bindValue(16, $id);
		
		try{
			$query->execute();
		}catch(PDOException $e){
			die($e->getMessage());
		}
		
	}

Re: multiple checkbox storing and retrieving

Posted: Tue Jan 14, 2014 8:04 am
by Celauran
$_POST['co_app'] is an array. Your update_user method is trying to store a string. Are you transforming the array in any way before passing it in to update_user?

Re: multiple checkbox storing and retrieving

Posted: Tue Jan 14, 2014 8:27 am
by jaad
]I think I do here:

Code: Select all

$allowed = array('id', 'username', 'first_name', 'middle_name','last_name', 'gender', 'dob', 'sin', 'home_phone', 'cell_phone','emerg_name','emerg_email','emerg_phone', 'co_app', 'co_name','bio', 'email'); // I have only added few, but you can add more. However do not add 'password' eventhough the parameters will only be given by you and not the user, in our system.
		if (!in_array($what, $allowed, true) || !in_array($field, $allowed, true)) {
		    throw new InvalidArgumentException;
		}else{
		
			$query = $this->db->prepare("SELECT $what FROM `users` WHERE $field = ?");

			$query->bindValue(1, $value);

			try{

				$query->execute();
				
			} catch(PDOException $e){

				die($e->getMessage());
			}
I've also tried this:

Code: Select all

if (isset($_POST['Update']){
if (isset($_POST['co_app']){
$co_appV= implode(",",$_POST['co_app']);
}

}
no luck either

Re: multiple checkbox storing and retrieving

Posted: Tue Jan 14, 2014 8:31 am
by Celauran
jaad wrote:]I think I do here:

Code: Select all

$allowed = array('id', 'username', 'first_name', 'middle_name','last_name', 'gender', 'dob', 'sin', 'home_phone', 'cell_phone','emerg_name','emerg_email','emerg_phone', 'co_app', 'co_name','bio', 'email'); // I have only added few, but you can add more. However do not add 'password' eventhough the parameters will only be given by you and not the user, in our system.
		if (!in_array($what, $allowed, true) || !in_array($field, $allowed, true)) {
		    throw new InvalidArgumentException;
		}else{
		
			$query = $this->db->prepare("SELECT $what FROM `users` WHERE $field = ?");

			$query->bindValue(1, $value);

			try{

				$query->execute();
				
			} catch(PDOException $e){

				die($e->getMessage());
			}
This is a SELECT. You're getting data back out of the database. Have you checked that it's being entered correctly to begin with?
I've also tried this:

Code: Select all

if (isset($_POST['Update']){
if (isset($_POST['co_app']){
$co_appV= implode(",",$_POST['co_app']);
}

}
no luck either
Are you then passing $co_appV to your update_user method?

Re: multiple checkbox storing and retrieving

Posted: Tue Jan 14, 2014 8:38 am
by jaad
I was going to pass it to the update_user method but then I realized I didn't understand how to bring it down into this section:

Code: Select all

$query = $this->db->prepare("UPDATE `users` SET
								`first_name`	= ?,
								`middle_name`	= ?,
								`last_name`		= ?,
								`gender`		= ?,
								`dob`			= ?,
								`sin`			= ?,
								`home_phone`	= ?,
								`cell_phone`	= ?,
								`emerg_name`	= ?,
								`emerg_email`	= ?,
								`emerg_phone`	= ?,
								`co_app`		= ?,
								`co_name`		= ?,
								`bio`			= ?,
								`image_location`= ?
								
								WHERE `id` 		= ? 
								");

		$query->bindValue(1, $first_name);
		$query->bindValue(2, $middle_name);
		$query->bindValue(3, $last_name);
		$query->bindValue(4, $gender);
		$query->bindValue(5, $dob);
		$query->bindValue(6, $sin);
		$query->bindValue(7, $home_phone);
		$query->bindValue(8, $cell_phone);
		$query->bindValue(9, $emerg_name);
		$query->bindValue(10, $emerg_email);
		$query->bindValue(11, $emerg_phone);
		$query->bindValue(12, $co_app);
		$query->bindValue(13, $co_name);
		$query->bindValue(14, $bio);
		$query->bindValue(15, $image_location);
		$query->bindValue(16, $id);
		
		try{
			$query->execute();
		}catch(PDOException $e){
			die($e->getMessage());
		}
		
	}

Re: multiple checkbox storing and retrieving

Posted: Tue Jan 14, 2014 8:41 am
by Celauran
You don't need to. It's defined as $co_app in the method signature, so that's what it will be referred to within the scope of that method.

Re: multiple checkbox storing and retrieving

Posted: Tue Jan 14, 2014 8:44 am
by jaad
then why isn't it working? it doesnt' write to database and of course it's not coming back either for those of which I selected lol.

Re: multiple checkbox storing and retrieving

Posted: Tue Jan 14, 2014 8:46 am
by Celauran
I don't currently have enough information to say why it's not working. Can you post all the code? The page handling the form as well as the user class?

Re: multiple checkbox storing and retrieving

Posted: Tue Jan 14, 2014 8:56 am
by jaad
sure thing.

Code: Select all

<?php 
include_once 'core/init.php';
$general->logged_out_protect();
?>
<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<link rel="stylesheet" type="text/css" href="css/style.css" >
	<title>Settings</title> 
    
 
<script>

function disableEnterKey(e){
	var key; 
	if	(window.event)
		key = window.event.keyCode;     //IE
	else
		key = e.which;     				//firefox
    if	(key == 13)
        return false;
	else
        return true;
}
	
</script>
<script type="text/javascript">
// this is a javascript sin number checker from http://www.codingforums.com/showthread.php?t=279032

// valid number examples 046-454-286   193-456-787   127-248-623

var sin = 0;

function validate(which,next) {
var val = which.value;
val = val.replace(/[^0-9]/g,"")
which.value = val;
next = "S" + next;
if (val.length == 3) {
document.getElementById(next).focus();
}
sin = document.getElementById("S1").value + document.getElementById("S2").value + document.getElementById("S3").value; 
}

function CheckNumber(sin) {  // sin is a string value
var c = 0;

if (sin.substring(0,3) == "000") {
alert("Invalid SIN: SIN's can't start with 000.");
document.getElementById("S1").value = "";  // clear the fields
document.getElementById("S2").value = "";
document.getElementById("S3").value = "";
//document.getElementById("S1").focus();  // if required
return false;
}

if (sin.length !=9) {
alert ("You must complete all three fields!");
return false;
}

// odd digits
for (var i = 1; i<=9; i+=2) {
c += Number(sin.charAt(i-1));
}

// even digits
for (var i = 2; i <=8; i+=2) {
var digit = Number(sin.charAt(i-1)) *2;
if (digit >9) {digit = digit -9}
c += digit;
}

sin = document.getElementById("S1").value + "-" + document.getElementById("S2").value + "-" +document.getElementById("S3").value; 

if ((c%10) == 0) {
alert ("The Social Insurance Number " + sin + " is valid");
}
else {
alert ("The Social Insurance Number " + sin + " is NOT valid");
return false;
}

}

</script>
</head>
<body>
	<div id="container">
		<?php include 'includes/menu.php'; ?>
		<?php 
	    if (isset($_GET['success']) && empty($_GET['success'])) {
	        echo '<h3>Your details have been updated!</h3>';	        
	    } else{

            if(empty($_POST) === false) {		
			
				if (isset($_POST['first_name']) && !empty ($_POST['first_name'])){
					if (ctype_alpha($_POST['first_name']) === false) {
					$errors[] = 'Please enter your First Name with only letters!';
					}	
				}
				if (isset($_POST['middle_name']) && !empty ($_POST['middle_name'])){
					if (ctype_alpha($_POST['middle_name']) === false) {
					$errors[] = 'Please enter your Middle Name with only letters!';
					}	
				}
				if (isset($_POST['last_name']) && !empty ($_POST['last_name'])){
					if (ctype_alpha($_POST['last_name']) === false) {
					$errors[] = 'Please enter your Last Name with only letters!';
					}	
				}
												
				$date = $users->parseDate($_POST['dob']);
				if ($date) {
    			$dob = $date->format('Y-m-d');
				}
				
				if (isset($_POST['gender']) && !empty($_POST['gender'])) {
					
					$allowed_gender = array('undisclosed', 'Male', 'Female');

					if (in_array($_POST['gender'], $allowed_gender) === false) {
						$errors[] = 'Please choose a Gender from the list';	
					}

				} 
				
				
				if (isset($_FILES['myfile']) && !empty($_FILES['myfile']['name'])) {
					
					$name 			= $_FILES['myfile']['name'];
					$tmp_name 		= $_FILES['myfile']['tmp_name'];
					$allowed_ext 	= array('jpg', 'jpeg', 'png', 'gif' );
					$a 				= explode('.', $name);
					$file_ext 		= strtolower(end($a)); unset($a);
					$file_size 		= $_FILES['myfile']['size'];		
					$path 			= "avatars";
					
					if (in_array($file_ext, $allowed_ext) === false) {
						$errors[] = 'Image file type not allowed';	
					}
					
					if ($file_size > 2097152) {
						$errors[] = 'File size must be under 2mb';
					}
					
				} else {
					$newpath = $user['image_location'];
				}

				if(empty($errors) === true) {
					
					if (isset($_FILES['myfile']) && !empty($_FILES['myfile']['name']) && $_POST['use_default'] != 'on') {
				
						$newpath = $general->file_newpath($path, $name);

						move_uploaded_file($tmp_name, $newpath);

					}else if(isset($_POST['use_default']) && $_POST['use_default'] === 'on'){
                        $newpath = 'avatars/default_avatar.png';
                    }
							
					$first_name 	= htmlentities(trim($_POST['first_name']));
					$last_name 		= htmlentities(trim($_POST['last_name']));
					$middle_name	= htmlentities(trim($_POST['middle_name']));	
					$gender 		= htmlentities(trim($_POST['gender']));
					//$dob	 		= htmlentities(trim($_POST['dob']));
					$sin			= htmlentities(trim($_POST['sin']));
					$home_phone		= htmlentities(trim($_POST['home_phone']));
					$cell_phone		= htmlentities(trim($_POST['cell_phone']));
					$emerg_name		= htmlentities(trim($_POST['emerg_name']));
					$emerg_email	= htmlentities(trim($_POST['emerg_email']));
					$emerg_phone	= htmlentities(trim($_POST['emerg_phone']));
					$co_app			= htmlentities(trim($_POST['co_app']));
					$co_name		= htmlentities(trim($_POST['co_name']));
					$bio 			= htmlentities(trim($_POST['bio']));
					$image_location	= htmlentities(trim($newpath));
					 
					 
				
					
			$users->update_user($first_name, $middle_name, $last_name, $gender, $dob, $sin, $home_phone, $cell_phone, $emerg_name,$emerg_email, $emerg_phone, $co_app, $co_name, $bio, $image_location, $user_id);
					header('Location: settings.php?success');
					exit();
				
				} else if (empty($errors) === false) {
					echo '<p>' . implode('</p><p>', $errors) . '</p>';	
				}	
            }
			
    		?>
         
    		<h2>Settings.</h2> <p><b>Note: Information you post here is made viewable to others.</b></p>
            <hr />

            <form action="" method="post" enctype="multipart/form-data">
                <div id="profile_picture">
                
               		<h3>Change Profile Picture</h3>
                    <ul>
                        
        				<?php
                        if(!empty ($user['image_location'])) {
                            $image = $user['image_location'];
                            echo "<img src='$image'>";
                        } 
                        ?>
                        
                        <li>
                        <input type="file" name="myfile" />
                        </li>
                        <?php if($image != 'avatars/default_avatar.png'){ ?>
	                        <li>
	                            <input type="checkbox" name="use_default" id="use_default" /> <label for="use_default">Use default picture</label>
	                        </li>
	                        <?php 
                        }
                        ?>
                    </ul>
                </div>
            
            	<div id="personal_info">
	            	<h3 >Change Profile Information </h3>
	                <ul>
	                    <li>
	                        <h4>First name:</h4>
	                        <input type="text" name="first_name" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['first_name']) ){echo htmlentities(strip_tags($_POST['first_name']));} else { echo $user['first_name']; }?>">
	                    </li> 
                         <li>
	                        <h4>Middle name:</h4>
	                        <input type="text" name="middle_name" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['middle_name']) ){echo htmlentities(strip_tags($_POST['middle_name']));} else { echo $user['middle_name']; }?>">
	                    </li>  
	                    <li>
	                        <h4>Last name: </h4>
	                        <input type="text" name="last_name" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['last_name']) ){echo htmlentities(strip_tags($_POST['last_name']));} else { echo $user['last_name']; }?>">
	                    </li>
	                    <li>
	                        <h4>Gender:</h4>
	                        <?php
	                       	 	$gender 	= $user['gender'];
	                        	$options 	= array("undisclosed", "Male", "Female");
	                            echo '<select name="gender">';
	                            foreach($options as $option){
	                               	if($gender == $option){
	                               		$sel = 'selected="selected"';
	                               	}else{
	                               		$sel='';
	                               	}
	                                echo '<option '. $sel .'>' . $option . '</option>';
	                            }
	                        ?>
	                        </select>
	                    </li>
                         <li>
	                        <h4>D.O.B (YYYY-MM-DD:</h4>
	                        <input type="date ('yyyy-mm-dd')" name="dob" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['dob']) ){echo htmlentities(strip_tags($_POST['dob']));} else { echo $user['dob']; }?>">
	                    </li>
                        <li>
	                    	
							<h4>SIN: </h4>
	                        <input type="text" name="sin" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['sin']) ){echo htmlentities(strip_tags($_POST['sin']));} else { echo $user['sin']; }?>">
                        </li>
                        <li>
	                        <h4>Home Phone:</h4>
	                        <input type="text" name="home_phone" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['home_phone']) ){echo htmlentities(strip_tags($_POST['home_phone']));} else { echo $user['home_phone']; }?>">
	                    </li> 
                        <li>
	                        <h4>Cell Phone:</h4>
	                        <input type="text" name="cell_phone" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['cell_phone']) ){echo htmlentities(strip_tags($_POST['cell_phone']));} else { echo $user['cell_phone']; }?>">
	                    </li>
                        <li>
	                        <h4>Emergency Name:</h4>
	                        <input type="text" name="emerg_name" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['emerg_name']) ){echo htmlentities(strip_tags($_POST['emerg_name']));} else { echo $user['emerg_name']; }?>">
	                    </li>
                        <li>
	                        <h4>Emergency email:</h4>
	                        <input type="text" name="emerg_email" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['emerg_email']) ){echo htmlentities(strip_tags($_POST['emerg_email']));} else { echo $user['emerg_email']; }?>">
	                    </li>
                        <li>
	                        <h4>Emergency Phone:</h4>
	                        <input type="text" name="emerg_phone" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['emerg_phone']) ){echo htmlentities(strip_tags($_POST['emerg_phone']));} else { echo $user['emerg_phone']; }?>">
	                    </li>
                        <li>
	                        <h4>Co-Application:</h4>
	                       
                          <input type="checkbox" name="co_app[]" id="co_app1" value="spouse"> Spouse
                          <input type="checkbox" name="co_app[]" id="co_app2" value="roommate"> Roommate
                          <input type="checkbox" name="co_app[]" id="co_app3" value="none"> None
                         
                        </li>
                        <li>
	                        <h4>Co-Applicant Name:</h4>
	                        <input type="text" name="co_name" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['co_name']) ){echo htmlentities(strip_tags($_POST['co_name']));} else { echo $user['co_name']; }?>">
	                    </li>
                        <li>
	                        <h4>Bio:</h4>
	                        <textarea name="bio"><?php if (isset($_POST['bio']) ){echo htmlentities(strip_tags($_POST['bio']));} else { echo $user['bio']; }?></textarea>
	                    </li>
	            	</ul>    
            	</div>
            	<div class="clear"></div>
            	<hr />
            		<span>Update Changes:</span>
                    <input type="submit" value="Update">
               
            </form>
    </div>

</body>
</html>
<?php
		}

Code: Select all

<?php 
class Users{
 	
	private $db;

	public function __construct($database) {
	    $this->db = $database;
	}	
	  
	public function update_user($first_name, $middle_name, $last_name, $gender, $dob, $sin,$home_phone, $cell_phone, $emerg_name,$emerg_email, $emerg_phone, $co_app, $co_name, $bio, $image_location, $id){
		
		

		$query = $this->db->prepare("UPDATE `users` SET
								`first_name`	= ?,
								`middle_name`	= ?,
								`last_name`		= ?,
								`gender`		= ?,
								`dob`			= ?,
								`sin`			= ?,
								`home_phone`	= ?,
								`cell_phone`	= ?,
								`emerg_name`	= ?,
								`emerg_email`	= ?,
								`emerg_phone`	= ?,
								`co_app`		= ?,
								`co_name`		= ?,
								`bio`			= ?,
								`image_location`= ?
								
								WHERE `id` 		= ? 
								");

		$query->bindValue(1, $first_name);
		$query->bindValue(2, $middle_name);
		$query->bindValue(3, $last_name);
		$query->bindValue(4, $gender);
		$query->bindValue(5, $dob);
		$query->bindValue(6, $sin);
		$query->bindValue(7, $home_phone);
		$query->bindValue(8, $cell_phone);
		$query->bindValue(9, $emerg_name);
		$query->bindValue(10, $emerg_email);
		$query->bindValue(11, $emerg_phone);
		$query->bindValue(12, $co_app);
		$query->bindValue(13, $co_name);
		$query->bindValue(14, $bio);
		$query->bindValue(15, $image_location);
		$query->bindValue(16, $id);
		
		try{
			$query->execute();
		}catch(PDOException $e){
			die($e->getMessage());
		}
		
	}
		
	//function created by me to parse date format
	public function parseDate($date) {
        try {
                $dt = new DateTime($date);
                return $dt;
        } catch (Exception $e) {
                try {
                        $date = str_replace('-', '/', $date);
                        $dt = new DateTime($date);
                        return $dt;
                } catch (Exception $e) {
                        return false;
                }
        }
}
	

	public function change_password($user_id, $password) {

		global $bcrypt;

		/* Two create a Hash you do */
		$password_hash = $bcrypt->genHash($password);

		$query = $this->db->prepare("UPDATE `users` SET `password` = ? WHERE `id` = ?");

		$query->bindValue(1, $password_hash);
		$query->bindValue(2, $user_id);				

		try{
			$query->execute();
			return true;
		} catch(PDOException $e){
			die($e->getMessage());
		}

	}

	public function recover($email, $generated_string) {

		if($generated_string == 0){
			return false;
		}else{
	
			$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `email` = ? AND `generated_string` = ?");

			$query->bindValue(1, $email);
			$query->bindValue(2, $generated_string);

			try{

				$query->execute();
				$rows = $query->fetchColumn();

				if($rows == 1){
					
					global $bcrypt;

					$username = $this->fetch_info('username', 'email', $email); // getting username for the use in the email.
					$user_id  = $this->fetch_info('id', 'email', $email);// We want to keep things standard and use the user's id for most of the operations. Therefore, we use id instead of email.
			
					$charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
					$generated_password = substr(str_shuffle($charset),0, 10);

					$this->change_password($user_id, $generated_password);

					$query = $this->db->prepare("UPDATE `users` SET `generated_string` = 0 WHERE `id` = ?");

					$query->bindValue(1, $user_id);
	
					$query->execute();

					mail($email, 'Your password', "Hello " . $username . ",\n\nYour your new password is: " . $generated_password . "\n\nPlease change your password once you have logged in using this password.\n\n-Example team");

				}else{
					return false;
				}

			} catch(PDOException $e){
				die($e->getMessage());
			}
		}
	}

    public function fetch_info($what, $field, $value){

		$allowed = array('id', 'username', 'first_name', 'middle_name','last_name', 'gender', 'dob', 'sin', 'home_phone', 'cell_phone','emerg_name','emerg_email','emerg_phone', 'co_app', 'co_name','bio', 'email'); // I have only added few, but you can add more. However do not add 'password' eventhough the parameters will only be given by you and not the user, in our system.
		if (!in_array($what, $allowed, true) || !in_array($field, $allowed, true)) {
		    throw new InvalidArgumentException;
		}else{
		
			$query = $this->db->prepare("SELECT $what FROM `users` WHERE $field = ?");

			$query->bindValue(1, $value);

			try{

				$query->execute();
				
			} catch(PDOException $e){

				die($e->getMessage());
			}

			return $query->fetchColumn();
		}
	}

	public function confirm_recover($email){

		$username = $this->fetch_info('username', 'email', $email);// We want the 'id' WHERE 'email' = user's email ($email)

		$unique = uniqid('',true);
		$random = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ'),0, 10);
		
		$generated_string = $unique . $random; // a random and unique string

		$query = $this->db->prepare("UPDATE `users` SET `generated_string` = ? WHERE `email` = ?");

		$query->bindValue(1, $generated_string);
		$query->bindValue(2, $email);

		try{
			
			$query->execute();

			mail($email, 'Recover Password', "Hello " . $username. ",\r\nPlease click the link below:\r\n\r\nhttp://www.example.com/recover.php?email=" . $email . "&generated_string=" . $generated_string . "\r\n\r\n We will generate a new password for you and send it back to your email.\r\n\r\n-- Example team");			
			
		} catch(PDOException $e){
			die($e->getMessage());
		}
	}

	public function user_exists($username) {
	
		$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `username`= ?");
		$query->bindValue(1, $username);
	
		try{

			$query->execute();
			$rows = $query->fetchColumn();

			if($rows == 1){
				return true;
			}else{
				return false;
			}

		} catch (PDOException $e){
			die($e->getMessage());
		}

	}
	 
	public function email_exists($email) {

		$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `email`= ?");
		$query->bindValue(1, $email);
	
		try{

			$query->execute();
			$rows = $query->fetchColumn();

			if($rows == 1){
				return true;
			}else{
				return false;
			}

		} catch (PDOException $e){
			die($e->getMessage());
		}

	}

	public function register($username, $password, $email){

		global $bcrypt; // making the $bcrypt variable global so we can use here

		$time 		= time();
		$ip 		= $_SERVER['REMOTE_ADDR']; // getting the users IP address
		$email_code = $email_code = uniqid('code_',true); // Creating a unique string.
		
		$password   = $bcrypt->genHash($password);

		$query 	= $this->db->prepare("INSERT INTO `users` (`username`, `password`, `email`, `ip`, `time`, `email_code`) VALUES (?, ?, ?, ?, ?, ?) ");

		$query->bindValue(1, $username);
		$query->bindValue(2, $password);
		$query->bindValue(3, $email);
		$query->bindValue(4, $ip);
		$query->bindValue(5, $time);
		$query->bindValue(6, $email_code);

		try{
			$query->execute();

			mail($email, 'Please activate your account', "Hello " . $username. ",\r\nThank you for registering with us. Please visit the link below so we can activate your account:\r\n\r\nhttp://www.example.com/activate.php?email=" . $email . "&email_code=" . $email_code . "\r\n\r\n-- Example team");
		}catch(PDOException $e){
			die($e->getMessage());
		}	
	}

	public function activate($email, $email_code) {
		
		$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `email` = ? AND `email_code` = ? AND `confirmed` = ?");

		$query->bindValue(1, $email);
		$query->bindValue(2, $email_code);
		$query->bindValue(3, 0);

		try{

			$query->execute();
			$rows = $query->fetchColumn();

			if($rows == 1){
				
				$query_2 = $this->db->prepare("UPDATE `users` SET `confirmed` = ? WHERE `email` = ?");

				$query_2->bindValue(1, 1);
				$query_2->bindValue(2, $email);				

				$query_2->execute();
				return true;

			}else{
				return false;
			}

		} catch(PDOException $e){
			die($e->getMessage());
		}

	}


	public function email_confirmed($username) {

		$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `username`= ? AND `confirmed` = ?");
		$query->bindValue(1, $username);
		$query->bindValue(2, 1);
		
		try{
			
			$query->execute();
			$rows = $query->fetchColumn();

			if($rows == 1){
				return true;
			}else{
				return false;
			}

		} catch(PDOException $e){
			die($e->getMessage());
		}

	}

	public function login($username, $password) {

		global $bcrypt;  // Again make get the bcrypt variable, which is defined in init.php, which is included in login.php where this function is called

		$query = $this->db->prepare("SELECT `password`, `id` FROM `users` WHERE `username` = ?");
		$query->bindValue(1, $username);

		try{
			
			$query->execute();
			$data 				= $query->fetch();
			$stored_password 	= $data['password']; // stored hashed password
			$id   				= $data['id']; // id of the user to be returned if the password is verified, below.
			
			if($bcrypt->verify($password, $stored_password) === true){ // using the verify method to compare the password with the stored hashed password.
				return $id;	// returning the user's id.
			}else{
				return false;	
			}

		}catch(PDOException $e){
			die($e->getMessage());
		}
	
	}

	public function userdata($id) {

		$query = $this->db->prepare("SELECT * FROM `users` WHERE `id`= ?");
		$query->bindValue(1, $id);

		try{

			$query->execute();

			return $query->fetch();

		} catch(PDOException $e){

			die($e->getMessage());
		}

	}
	  	  	 
	public function get_users() {

		$query = $this->db->prepare("SELECT * FROM `users` ORDER BY `time` DESC");
		
		try{
			$query->execute();
		}catch(PDOException $e){
			die($e->getMessage());
		}

		return $query->fetchAll();

	}	
}

Re: multiple checkbox storing and retrieving

Posted: Tue Jan 14, 2014 9:15 am
by Celauran
At least part of the problem is that you're just passing $_POST['co_app'] straight in.

Code: Select all

$co_app = htmlentities(trim($_POST['co_app']));
...
$users->update_user($first_name, $middle_name, $last_name, $gender, $dob, $sin, $home_phone, $cell_phone, $emerg_name,$emerg_email, $emerg_phone, $co_app, ...);
update_user doesn't convert it to a string nor are you converting it to one prior to passing it into update_user.

Why not replace line 176 with this instead?

Code: Select all

$co_app = implode(',', $_POST['co_app']);

Re: multiple checkbox storing and retrieving

Posted: Tue Jan 14, 2014 9:23 am
by jaad
it works!..... I have selected two checkbox spouse and roommate and both have been saved to my database with a comma in between. the only thing left is when I go back to my update page the checkbox aren't showing a tick inside of them.

Re: multiple checkbox storing and retrieving

Posted: Tue Jan 14, 2014 9:32 am
by Celauran
You'll first need to explode that value back into an array, then check if each checkbox value is in that array.

Code: Select all

$co_app = explode(',', $whatever_the_database_field_is_called);

Code: Select all

<input type="checkbox" name="co_app[]" value="roommate" <?= in_array('roommate', $co_app) ? 'checked="checked"' : ''; ?>>

Re: multiple checkbox storing and retrieving

Posted: Tue Jan 14, 2014 9:47 am
by jaad
i get this returned to me

Co-Application:
Notice: Undefined variable: co_app in C:\xampp\htdocs\lar\settings.php on line 288

Warning: in_array() expects parameter 2 to be array, null given in C:\xampp\htdocs\lar\settings.php on line 288
> Spouse Notice: Undefined variable: co_app in C:\xampp\htdocs\lar\settings.php on line 289

Warning: in_array() expects parameter 2 to be array, null given in C:\xampp\htdocs\lar\settings.php on line 289
> Roommate Notice: Undefined variable: co_app in C:\xampp\htdocs\lar\settings.php on line 290

Warning: in_array() expects parameter 2 to be array, null given in C:\xampp\htdocs\lar\settings.php on line 290
> None

form

Code: Select all

<input type="checkbox" name="co_app[]" id="co_app1" value="spouse"<?= in_array('spouse', $co_app) ? 'checked="checked"' : ''; ?>> Spouse
                          <input type="checkbox" name="co_app[]" id="co_app2" value="roommate"<?= in_array('roommate', $co_app) ? 'checked="checked"' : ''; ?>> Roommate
                          <input type="checkbox" name="co_app[]" id="co_app3" value="none"<?= in_array('none', $co_app) ? 'checked="checked"' : ''; ?>> None

Re: multiple checkbox storing and retrieving

Posted: Tue Jan 14, 2014 9:50 am
by Celauran
Looks like something went wrong with the explode() call and $co_app is null rather than an array. Let's take a look at that.

Re: multiple checkbox storing and retrieving

Posted: Tue Jan 14, 2014 9:54 am
by jaad
$co_app = explode(',', ['co_app']);

I tried doing a var_dump($co_app); and got nothing echoing on the page

I already have $co_app = implode(',', ['co_app']); on the line above. Shouldn't I give the explode function another variable name?