break apart 3 fields that were merged

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
jaad
Forum Commoner
Posts: 95
Joined: Fri Jan 03, 2014 5:30 am
Location: Vancouver Canada

Re: break apart 3 fields that were merged

Post by jaad »

yes I was able to bring the 3 values from 3 different field into one database field with a concatenated "-" separator in between the the value. Bob;s my uncle on that one.
I don't know how to do step 1
I know how to do step 2
I dont know how to do step 3
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: break apart 3 fields that were merged

Post by social_experiment »

1. Retrieve data from DB - You'll need something of the user, a unique id value of sorts so you can retrieve only their information.
2. Done.
3. Put it in 3 text fields - This is your code below; looks ok to me?

Code: Select all

<?php
$sin    = $sin1 ."-". $sin2 ."-". $sin3;

$s =explode("-",$sin);
 /*
    one slight update - when accessing an numeric index in an array
    you use only the number, like 0, not '0'
 */
$sin1=$s[0];
$sin2=$s[1];
$sin3=$s[2];

?>
<form>
<input type = "text" size="3" value= "<?php echo $sin1;?>">
<input type = "text" size="3" value= "<?php echo $sin2;?>">
<input type = "text" size="3" value= "<?php echo $sin3;?>">
</form>
?>
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
User avatar
jaad
Forum Commoner
Posts: 95
Joined: Fri Jan 03, 2014 5:30 am
Location: Vancouver Canada

Re: break apart 3 fields that were merged

Post by jaad »

ok I tried it and I still get an error. I am not sure but my gut feeling tells me that I can't use the same variable $sin1,2,3 to bring back the data. here is why I think that
this is the block I have to enter the field into the database. the commented lines are from what you gave me. as you can see, $sin1,2,3 already have values assigned to it with $_POST ['S1'],['S2'],['S3'] I get an undefined index error when trying to insert into the input value of the form the value $sin1.

Code: Select all


					$sin1 	= $_POST['S1'];
					$sin2	= $_POST['S2'];
					$sin3	= $_POST['S3']; 
					$sin	= $sin1 ."-". $sin2 ."-". $sin3;
					//$s		= explode("-",$sin);
					//$sin1=$s[0];
					//$sin2=$s[1];
					//$sin3=$s[2];
my gut feeling tells me I should put that block you gave me into the function Updateuser() in my user class

public function update_user($first_name, $middle_name, $last_name, $gender, $dob, $sin, $bio, $image_location, $id){

Code: Select all

		$query = $this->db->prepare("UPDATE `users` SET
								`first_name`	= ?,
								`middle_name`	= ?,
								`last_name`		= ?,
								`gender`		= ?,
								`dob`			= ?,
								`sin`			= ?,
								`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, $bio);
		$query->bindValue(8, $image_location);
		$query->bindValue(9, $id);
		
		try{
			$query->execute();
		}catch(PDOException $e){
			die($e->getMessage());

                        IN HERE SOMEWHERE--------------------------------------------------------------------
		}
		
	}[]
Last edited by jaad on Sun Jan 12, 2014 4:53 am, edited 1 time in total.
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: break apart 3 fields that were merged

Post by social_experiment »

with the code you currently have, this below, do you receive any errors ?

Code: Select all

<?php
$sin1   = $_POST['S1'];
$sin2   = $_POST['S2'];
$sin3   = $_POST['S3']; 
$sin    = $sin1 ."-". $sin2 ."-". $sin3;
?>
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
User avatar
jaad
Forum Commoner
Posts: 95
Joined: Fri Jan 03, 2014 5:30 am
Location: Vancouver Canada

Re: break apart 3 fields that were merged

Post by jaad »

no error, works like a charm. I did a jump, clapped my hand several times, did a little dance and had a smile on my face like you never seen since this was the first time I ever came up with a code of my own that actually worked on the first try hahahaha
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: break apart 3 fields that were merged

Post by social_experiment »

jaad wrote:my gut feeling tells me I should put that block you gave me into the function Updateuser() in my user class
it depends; you could pass the data to that function (when it is already put together) or you can have it done inside the function. The position however is not in the location you think; it should happen before the TRY section
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
User avatar
jaad
Forum Commoner
Posts: 95
Joined: Fri Jan 03, 2014 5:30 am
Location: Vancouver Canada

Re: break apart 3 fields that were merged

Post by jaad »

nope.... not working

i get this:

<br /><b>Notice</b>: Undefined variable: sin2 in <b>C:\xampp\htdocs\lar\settings.php</b> on line <b>261</b><br />

Code: Select all


	public function update_user($first_name, $middle_name, $last_name, $gender, $dob, $sin, $bio, $image_location, $id){

		$query = $this->db->prepare("UPDATE `users` SET
								`first_name`	= ?,
								`middle_name`	= ?,
								`last_name`		= ?,
								`gender`		= ?,
								`dob`			= ?,
								`sin`			= ?,
								`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, $bio);
		$query->bindValue(8, $image_location);
		$query->bindValue(9, $id);
		$s		= explode("-",$sin);---------------------------------------------- this is where I inserted the block
					$sin1=$s[0];
					$sin2=$s[1];
					$sin3=$s[2];
		try{
			$query->execute();
		}catch(PDOException $e){
			die($e->getMessage());
		}
		
	}

Code: Select all


Social Insurance Number <input type = "text" id = "S1" name="S1" size =" 3" maxlength = "3" onkeyup = "validate(this,2)" value="<?php echo $sin1;?>">
<input type = "text" id = "S2" name="S2" size =" 200" maxlength = "200" onkeyup = "validate(this,3)" value="<?php echo $sin2;?>">
<input type = "text" id = "S3" name="S3" size =" 4" maxlength = "3" onkeyup = "validate(this,3)"value="<?php echo $sin3;?>">
<br/><br/>
<input type="button" value="Validate Number" onclick="CheckNumber(sin)"/>
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: break apart 3 fields that were merged

Post by social_experiment »

<b>Notice</b>: Undefined variable: sin2 in <b>C:\xampp\htdocs\lar\settings.php</b> on line <b>261</b>

this is being issued because the variable $sin2 isn't defined within the function. I think it will be better to pass this data to the function. It seems you are already doing it in the parameters of the function. The code you added can be removed from this method;
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: break apart 3 fields that were merged

Post by Celauran »

That's a problem of scope. $sin exists inside the update_user method because you passed it in as a parameter. $s, $sin1, $sin2, and $sin3 are being created within that method and is therefore the only place they exist. Moreover, I don't think update_user should be responsible for this. Your get_user (or whatever method you use to retrieve a user's information from the database) should fetch all the DB columns you need, including SIN. Exploding it into three parts for display purposes can be done right where it's being displayed IMO.
User avatar
jaad
Forum Commoner
Posts: 95
Joined: Fri Jan 03, 2014 5:30 am
Location: Vancouver Canada

Re: break apart 3 fields that were merged

Post by jaad »

ok let's look at this again... Yesterday I was able to write to the database with a sin number. today I am able to write still to the database but it writes the notice that my variable is not defined. lol.

let me upload my page again and my class and lets see if we can make this puppy work. We can't be too far off.

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']));
					$bio 			= htmlentities(trim($_POST['bio']));
					$image_location	= htmlentities(trim($newpath));
					
					$sin1 	= $_POST['S1'];
					$sin2	= $_POST['S2'];
					$sin3	= $_POST['S3']; 
					$sin	= $sin1 ."-". $sin2 ."-". $sin3;
					echo $sin1;------------------------------------------------------------------tried echo $sin1 to see if I am geting anything from there and i get nothing
				//	list($s1, $s2, $s3) = explode('-', $sin);  
					$s		= explode("-",$sin);
                                        echo $s;----------------------------------------------------------------------------------------------------- I get nothing here either
					$sin1=$s[0];
					$sin2=$s[1];
					$sin3=$s[2];
					echo$sin1 ------------------------------------------------------------------------------------I get nothing from here either
					$users->update_user($first_name, $middle_name, $last_name, $gender, $dob, $sin, $bio, $image_location, $user_id);
					header('Location: settings.php?success');
					exit();
				echo $sin;-------------------------------------------------------------------------------------I get nothing from here either
				} 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>
	                    	<br><br>
Social Insurance Number <input type = "text" id = "S1" name="S1" size =" 150" maxlength = "150" onkeyup = "validate(this,2)" value="<?php echo $sin1;?>">
<input type = "text" id = "S2" name="S2" size =" 200" maxlength = "200" onkeyup = "validate(this,3)" value="<?php echo $sin2;?>">
<input type = "text" id = "S3" name="S3" size =" 150" maxlength = "150" onkeyup = "validate(this,3)"value="<?php echo $sin3;?>">
<br/><br/>
<input type="button" value="Validate Number" onclick="CheckNumber(sin)"/>
                           
                        </li>
                            
                          <?php /* <h4>Social Insurance #:</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>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
}
------------------------------------------------------ and here is the User class

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, $bio, $image_location, $id){

		$query = $this->db->prepare("UPDATE `users` SET
								`first_name`	= ?,
								`middle_name`	= ?,
								`last_name`		= ?,
								`gender`		= ?,
								`dob`			= ?,
								`sin`			= ?,
								`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, $bio);
		$query->bindValue(8, $image_location);
		$query->bindValue(9, $id);
		
		//$s		= explode("-",$sin);
					//$sin1=$s[0];
					//$sin2=$s[1];
					//$sin3=$s[2];
		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', '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();

	}	
}
User avatar
jaad
Forum Commoner
Posts: 95
Joined: Fri Jan 03, 2014 5:30 am
Location: Vancouver Canada

Re: break apart 3 fields that were merged

Post by jaad »

ok, I've analyzed the situation from a practical point of view. I'm definitely not a programer but I do have common sense. You guys tell me if this makes sense.

OK the situation is as follow:

1- I can enter the sin number in the 3 different input field; I can validate it; I can concatenate it and then save it into my database.
2- If I update any other field in my form I get the expected update result, so I know I have a good connection and that my update query works fine.
3- the sin number does not get updated for a reason that I am trying to figure out.
4- I was given a mean to explode the value coming from the database and gave 3 different variables name to each element that were separated by a "-"
5- it's not updating the field in the form
6- what I am thinking is the exploded value that I have is in the wrong place.
7- what would make sense to me is if all the other fields are getting updated then what I should do is somehow catch the value that is coming from the database on its way out of the update query and explode the value before it reach the form and the 3 different fields that makes the sin number in the form.
8- the only place I can think of doing that is right into the update query script that sits into my user class in the function update_user, but you guys think it is not a good idea.
9- I;ve tried putting it right after the function that calls the update query just before my form.
10- if none of these option work I am thinking I should create another update query that would only update the sin number after the update query that updated everything has ran.

does that make any sense to you guys?
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: break apart 3 fields that were merged

Post by social_experiment »

jaad wrote: 7- what would make sense to me is if all the other fields are getting updated then what I should do is somehow catch the value that is coming from the database on its way out of the update query and explode the value before it reach the form and the 3 different fields that makes the sin number in the form.
8- the only place I can think of doing that is right into the update query script that sits into my user class in the function update_user, but you guys think it is not a good idea.
;) you should keep working with the code, regardless of our opinions; at this time it is necessary to get the code working so that should be your main goal. Once you have it working / figured out, return to it and improve or refactor it.

Can you do a var_dump() of the $_POST variable that updates your database?

Code: Select all

<?php
 var_dump($_POST);
?>
It should be near these lines in your current code

Code: Select all

<?php
// display all data within the $_POST array
var_dump($_POST);
// want to stop the execution of the update function
// so comment it out

/*
$users->update_user($first_name, $middle_name, $last_name, $gender, $dob, $sin, $bio, $image_location, $user_id);
header('Location: settings.php?success');
exit();
*/
?>
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
User avatar
jaad
Forum Commoner
Posts: 95
Joined: Fri Jan 03, 2014 5:30 am
Location: Vancouver Canada

Re: break apart 3 fields that were merged

Post by jaad »

nothing! nothing is showing up

what is even stranger is I loged out and loged back in again and went to the update page and all my information was there lol. and the update function was commented out

oh wait! I forgot. there is a select function as well that brings the date from the database into the update page. maybe that what it is...

what's this function by teh way:

Code: Select all


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

		$allowed = array('id', 'username', 'first_name', 'middle_name','last_name', 'gender', 'dob', 'sin', '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();
		}
	}
it is in my user class. I havent gone though the whole thing yet from the tutorial
User avatar
jaad
Forum Commoner
Posts: 95
Joined: Fri Jan 03, 2014 5:30 am
Location: Vancouver Canada

Re: break apart 3 fields that were merged

Post by jaad »

I uncommented the user_update function and move the var_dump($_POST); around on teh page here and there and I ended up getting this: ***array(0) { }**** everywhere I put it and refresh my browser.
User avatar
jaad
Forum Commoner
Posts: 95
Joined: Fri Jan 03, 2014 5:30 am
Location: Vancouver Canada

Re: break apart 3 fields that were merged

Post by jaad »

is there something is this javascript that inhibit me from entering value in the form fields?
I think this is what the problem is... I decided to insert 3 more fields in my database s1, s2 and s3. Even then I can't get the buggers to come back on the update form.

Code: Select all

</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;
}

}
Post Reply