Reintegrating a concatenated value into 3 input fields

Hello All,

My first post here, hope I don;t scare everyone. I’m Alan form Vancouver Canada, 2 months into php and still a newbie. Please excuse my grammar, English is not my native tongue.

my question:

I am working on developing a profile page for users of my site. one area of the site is to register an application to rent a unit in my building. part of the process of the application requires a user to write their social insurance number. I have picked up a neat little javascript utility that validate Canadian SIN with 3 input fields on a form. once the SN has been validated I then concatenate the 3 fields into one to make a complete SIN number xxx-xxx-xxx and save it into my database. all that works really well. Teh problem that I have is to explode this concatenated SIN number that was saved into my database back into the 3 input fields on the form if a user need to update their profile. I have been working at this for 3 days and have had that question floating in two other forum and nobody seems to know how I can do that. Are there any super Nija php coders in here that can help me?

here is what I have so far: NOTE: I included the whole thing in the event you are curious about different aspect of my script. Thanks a bunch for looking this over for me. I would truly appreciate feedback

page and form:



<?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));
					//list($s1, $s2, $s3) = explode('-', $sin);                               this is not working-------------------------------------------------------------------
                                                                                                                                    //this is where I try to explode the value
                                        $sin	= $sin1 ."-". $sin2 ."-". $sin3;
					$s		= explode("-", $sin);
					$s[0]	= $_POST['S1'];
					$s[1]	= $_POST['S2'];
					$s[2]	= $_POST['S3'];
					
					echo $sin1;
				
					
					//--------------------------------------------------------------------this is my calling function-----------------------------------------------------------
					
					$users->update_user($first_name, $middle_name, $last_name, $gender, $dob, $sin, $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>
	                    	<br><br>



THIS IS THE FORM BELOW_______________________________________________________________________________________


Social Insurance Number <input type = "text" id = "S1" name="S1" size =" 3" maxlength = "3" onkeyup = "validate(this,2)" value="<?php if (isset($s[0]) ){echo htmlentities(strip_tags($s[0]));} else { echo $user['S1']; }?>>
<input type = "text" id = "S2" name="S2" size =" 3" maxlength = "3" onkeyup = "validate(this,3)" value="<?php echo $s2;?>">
<input type = "text" id = "S3" name="S3" size =" 3" maxlength = "3" onkeyup = "validate(this,3)"value="<?php echo $s3;?>">
<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
}

This is my user Class and User_update function---------------


&lt;?php
class Users{
 	
	private $db;

	public function __construct($database) {
	    $this-&gt;db = $database;
	}	
	
	public function update_user($first_name, $middle_name, $last_name, $gender, $dob, $sin, $bio, $image_location, $id){

		$query = $this-&gt;db-&gt;prepare("UPDATE `users` SET
								`first_name`	= ?,
								`middle_name`	= ?,
								`last_name`		= ?,
								`gender`		= ?,
								`dob`			= ?,
								`sin`			= ?,
								`bio`			= ?,
								`image_location`= ?
								
								WHERE `id` 		= ?
								");

		$query-&gt;bindValue(1, $first_name);
		$query-&gt;bindValue(2, $middle_name);
		$query-&gt;bindValue(3, $last_name);
		$query-&gt;bindValue(4, $gender);
		$query-&gt;bindValue(5, $dob);
		$query-&gt;bindValue(6, $sin);
		$query-&gt;bindValue(7, $bio);
		$query-&gt;bindValue(8, $image_location);
		$query-&gt;bindValue(9, $id);
		
		//$s		= explode("-",$sin);
					//$sin1=$s[0];
					//$sin2=$s[1];
					//$sin3=$s[2];
		try{
			$query-&gt;execute();
		}catch(PDOException $e){
			die($e-&gt;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-&gt;genHash($password);

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

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

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

	}

	public function recover($email, $generated_string) {

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

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

			try{

				$query-&gt;execute();
				$rows = $query-&gt;fetchColumn();

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

					$username = $this-&gt;fetch_info('username', 'email', $email); // getting username for the use in the email.
					$user_id  = $this-&gt;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-&gt;change_password($user_id, $generated_password);

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

					$query-&gt;bindValue(1, $user_id);
	
					$query-&gt;execute();

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

				}else{
					return false;
				}

			} catch(PDOException $e){
				die($e-&gt;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-&gt;db-&gt;prepare("SELECT $what FROM `users` WHERE $field = ?");

			$query-&gt;bindValue(1, $value);

			try{

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

				die($e-&gt;getMessage());
			}

			return $query-&gt;fetchColumn();
		}
	}

	public function confirm_recover($email){

		$username = $this-&gt;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-&gt;db-&gt;prepare("UPDATE `users` SET `generated_string` = ? WHERE `email` = ?");

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

		try{
			
			$query-&gt;execute();

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

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

			$query-&gt;execute();
			$rows = $query-&gt;fetchColumn();

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

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

	}
	
	public function email_exists($email) {

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

			$query-&gt;execute();
			$rows = $query-&gt;fetchColumn();

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

		} catch (PDOException $e){
			die($e-&gt;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-&gt;genHash($password);

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

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

		try{
			$query-&gt;execute();

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

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

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

		try{

			$query-&gt;execute();
			$rows = $query-&gt;fetchColumn();

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

				$query_2-&gt;bindValue(1, 1);
				$query_2-&gt;bindValue(2, $email);				

				$query_2-&gt;execute();
				return true;

			}else{
				return false;
			}

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

	}


	public function email_confirmed($username) {

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

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

		} catch(PDOException $e){
			die($e-&gt;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-&gt;db-&gt;prepare("SELECT `password`, `id` FROM `users` WHERE `username` = ?");
		$query-&gt;bindValue(1, $username);

		try{
			
			$query-&gt;execute();
			$data 				= $query-&gt;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-&gt;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-&gt;getMessage());
		}
	
	}

	public function userdata($id) {

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

		try{

			$query-&gt;execute();

			return $query-&gt;fetch();

		} catch(PDOException $e){

			die($e-&gt;getMessage());
		}

	}
	  	  	
	public function get_users() {

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

		return $query-&gt;fetchAll();

	}	
}

As I can see, you have a big field {sin} that is commented (it does not exist into your page) and also 3 “small” fields that will get the value.
However, you base those values on you {sin} field value (that does not exist in the HTML). So, the first thing that you need to do is to debug that field. After the … $image_location = htmlentities(trim($newpath)); line add

<?php

var_dump($_POST['sin']);
// and check the value of this POST

?>

And, another thing… your “s1” input gets the value from “$s[0]” OR “$user[‘S1’]” if no POST.
So, one field is from database and those other two are from your POST request (that, for now, it’s commented)

PS:

English is not my native tongue.

Funny! Tongue is the organ (from your mouth). You need to say “not my native language” :slight_smile:

hey thanks a lot for responding back. I have been playing around quite a lot with this and have tried god knows what to try to make it work.

What I have right now is a 3 field set S1-S2-S3. those are part of a javascript utility to validate the SIN number. once the sin number is validated I can then concatenate it into one number of 9 digit into my database under the [sin] . teh reason why I had blanked out the bottom input name=“sin” was because the java utility already uses that variable and it was conflicting with the javascript. a guy in another forum said it would be best to comment that input out and try to get the concatenated value back into the 3 fields S1- S2-S3. And that’s what I been trying to do for the last 4 days now lol. I’m not having any luck so far. can you help me out?

You complicated your code with the JavaScript and also, you can make it cleaner.
I don’t have time to write the entire code but, the idea is simple:

  1. send those 3 fields ($_POST[‘s1’], $_POST[‘s2’], $_POST[‘s3’])

  2. before you INSERT you concatenate them $SIN = $_POST[‘s1’] ‘-’.$_POST[‘s2’].‘-’.$_POST[‘s3’];

  3. when you get from database, to display (edit) make an explode

<?php

// ...

$sinParts = explode('-', $DB_rec['sin'])
if( count($sinParts) == 3 ) {
list($_POST['s1'], $_POST['s2'], $_POST['s3']) = $sinParts;
} else {
// you have some invalid value into your database
}

// ...


thank you very much for taking the time to write back. I have tried what you wrote and it unfortunately doesn’t work. I’ve tried dozens of other variation from other awesome forum members and didn’t have any luck with their version either. After having spent the last 5 days trying to figure this one out and not getting anywhere I decided to drop the idea of validating the SIN number and simply enter it raw into the database. Maybe one day I’ll come back to it and try to figure it out but for now I have had enough of that lol. thank a million bunch nevertheless for trying to help. I really appreciate it.