Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Feb 2019
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    How to QUERY AND ECHO Data INTO HTML INPUT fields in php mysqli using cookies?

    Code:
    <?php 
       	
       	session_start();
       	
       	
       	
       	$user = $_COOKIE["member_id"];
       	
       	$result = $con->query("select * from user where user_id ='$user'");
       	
       	
       	
       	$row = $result->fetch_array(MYSQLI_BOTH);
       	?>
       	
       	
       	
       	<?php
       	
       	
       
       	
       	
       	
       //	$user = $_COOKIE["member_id"];
       	
       //	$user = $_SESSION["member_id"];
       	
       	$result = $con->query("select * from user where user_id='$user'");
       	
       	$row = $result->fetch_array(MYSQLI_BOTH);
       	
    //   	session_start();
       	
       	
       	$_SESSION[userPic1] = $row['userPic'];
       	$_SESSION[first_name2] = $row['first_name'];
       	$_SESSION[middle_name2] = $row['middle_name'];
       	$_SESSION[last_name2] = $row['last_name'];
       	$_SESSION[e_mail2] = $row['e_mail'];
       	$_SESSION[user_name2] = $row['user_name'];
       	$_SESSION[date_of_birth2] = $row['date_of_birth'];
        $_SESSION[gender2] = $row['gender'];
        $_SESSION[date_joined2] = $row['account_created'];
       	
       	?>
       	<?php 
       	
       	if(isset($_POST['user_account_settings'])){
       		
       		
       			
       		$update_first_name = $_POST['first_name1'];
       		$update_middle_name = $_POST['middle_name1'];
       		$update_last_name = $_POST['last_name1'];
       		$update_e_mail = $_POST['e_mail1'];
       		$update_user_name = $_POST['user_name1'];
       		
       		$sql = $con->query("UPDATE user SET first_name = '{$update_first_name}', middle_name = '{$update_middle_name}', last_name = '{$update_last_name}', e_mail = '{$update_e_mail}', user_name = '{$update_user_name}' where user_id= $user");
       		
       		header('Location: user-account-settings.php');
       		
    }
       	
       	
       	?>
    
    
    <!doctype html>
    <html>
    <head> 
    
    <style>
    body { margin:0; padding:0; background-color:#ccc;}
    .fileuploadholder{
        width:200px;
        height:200px;
        margin: 60px auto 0px auto;
        background-color:#FFF;
        border:1px solid #CCC;
        padding:6px;
        }
    </style>
    
    
    <link href="Master.css" rel="stylesheet" type="text/css" />
    <link href="Menu.css" rel="stylesheet" type="text/css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="jquery-1.11.3-jquery.min.js"></script>
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"/>
    <meta charset="utf-8">
    <title>User account settings</title>
    </head>
    <body>
    <nav>
     <div class="toggle">
     <i class="fa fa-bars menu" aria-hidden="true"></i>
     </div>  
     
      <ul>
    
    
    
    
    
    	<ul>
    	<li><a href="welcome.php" title="">Home</a></li>
    	<li><a href="#" title="">About Us</a>
    	<li><a href="#" title="" class="current">Services</a>
    	<li><a href="#" title="">Our Work</a>
    	<li><a href="privacy_settings.php" title="">Privacy settings</a>
    	<li><a href="change_user_password.php" title="">Change password</a>
    	<li><a href="delete-account.php" title="">Delete account</a>
    	</ul>
    </div>    
      </ul>
      </nav>
       	<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
       	<script type="text/javascript">
       	    $(document).ready(function(){
       	   	    $('.menu').click(function(){
       	   	   	    $('ul').toggleClass('active');
       	   	    })
       	    })
       	    </script>
      </div>
      </div>
             
             <div class="LeftBody"></div>
             <div class="RightBody">
             
             
            
             
                  <?php
                                $q = mysqli_query($con,"SELECT * FROM user where user_id='$user'");
                            while($row = mysqli_fetch_assoc($q)){
                                    echo $row[''];
                                    if($row['userPic'] == ""){
                                            echo "<img width='100' height='100' src='pictures/default.jpg' alt='Default Profile Pic'>";
                                    } else {
                                            echo "<img width='100' height='100' src='/home/commun57/public_html/userProfilePic/".$row['userPic']."' alt='Profile Pic'>";
                                    }
                                    echo "<br>";
                            }
                    ?>
             
             
              <body>
             
             <form action="" method="post" name="user_account_settings_form" enctype="multipart/form-data" id="user_account_settings_form">
             
              
              <div class="fileuploadholder">
              <input type="file" name="file">
              <input type="submit" name="file" value="upload">
              </div>
             
             <label for="first_name1">  First name: </label>
             <div class="FormElement">
             <input name="first_name1" type="text" maxlength="50" required="required" class="editText" id="first_name1 value="<?php echo $_COOKIE[first_name];?>">
             </div>
             
             <label for="middle_name1"> Middle name: </label>
             <div class="FormElement">
             <input name="middle_name1" type="text" maxlength="50" class="editText" id="middle_name1" value="<?php  echo $_SESSION[middle_name2]; ?>">
             </div>
             
             <label for="last_name1">  Last name: </label>
             <div class="FormElement">
             <input name="last_name1" type="text" maxlength="50" required="required" class="editText" id="last_name1" value="<?php echo $_SESSION[last_name]; ?>">
             </div>
             
             <label for="e_mail1">  E-mail: </label>
             <span id="email_availability"></span>
             <div class="FormElement">
             <input name="e_mail1" type="email" minlength="4" maxlength="50" required="required" class="editText" id="e_mail1" value="<?php echo $_COOKIE[e_mail];?>">
             </div>
             
            
    
             <label for="user_name1">  Username: </label>
             <span id="user_name_availability"></span>
             <div class="FormElement">
             <input name="user_name1" type="text" minlength="4" maxlength="20" required="required" class="editText" id="user_name1" value="<?php echo $_SESSION[user_name2]; ?>">
             </div>
             
             
             
             <label for="date_of_birth1">  Date of birth: </label>
             <div class="FormElement">
             <input name="date_of_birth1" type="date" required="required" class="editText" id="date_of_birth1" disabled="disabled" value="<?php echo $_SESSION[date_of_birth2]; ?>">
             </div>
             
             
             
            
            <label for="gender1">  Gender: </label>
             <span id="email_availability"></span>
             <div class="FormElement">
             <input name="gender1" type="text"  required="required" class="editText" id="gender1" disabled="disabled" value="<?php echo $_SESSION[gender2]; ?>">
             </div>
            
            
            
             
             <label for="date_joined1">  Date joined: </label>
             <div class="FormElement">
             <input name="date_joined1" type="datetime"  maxlength="50" required="required" class="editText" id="date_joined1" disabled="disabled" value="<?php echo $_SESSION[date_joined2]; ?>">
             </div>
             
             <div class="FormElement">
             <input name="user_account_settings" type="submit" class="button" id="user_account_settings" value="Save">
            </div>
            
             </form>
             
             </div>
             <div class="Footer"></div>
          </div>
          
          
          
      </body>
      </html>
    Last edited by vinyl-junkie; Feb 3rd, 2019 at 03:19 AM. Reason: added code tags

  2. #2
    Senior Coder deathshadow's Avatar
    Join Date
    Feb 2016
    Location
    Keene, NH
    Posts
    3,329
    Thanks
    4
    Thanked 480 Times in 468 Posts
    There's some pretty big issues with your code here, so let's just go down the list.

    First off, this is NOT information you want to be putting into a cookie where you're using it for these types of queries. It goes client side and as such could be altered or used to compromise things. Avoid sending anything client side relating to the current user you don't have to, and user ID numbers are most certainly one of those things. It's why we have sessions. It looks like you tried to use sessions at one point -- stick with that.

    To that same end I highly suggest regenerating the session cookie on every page-load so that the value is constantly randomized making it harder for your sessions to get hacked.

    Next, two thirds or more the entire reason the old mysql_ functions were axed was for the prepare/execute model of doing things. To that end it isn't just bad practice, but outright insecure junk to be slopping variables into your query strings. That is an outdated outmoded approach that does nothing but open up massive security holes... and something we were all supposed to stop doing nearly a decade and a half ago when PHP 5 dropped! It's been 15 years, why is this still a thing people are taught?!?

    You're also blindly trusting that the cookie or session exists, don't do that.

    So where you have something like this:

    Code:
       	
       	session_start();
       	
       	
       	
       	$user = $_COOKIE["member_id"];
       	
       	$result = $con->query("select * from user where user_id ='$user'");
       	
       	
       	
       	$row = $result->fetch_array(MYSQLI_BOTH);
       	?>
    I would suggest something more like this:

    Code:
    	session_start();
    	session_regenerate_id();
    	if (array_key_exists('member_id', $_SESSION)) {
    		$stmt = $con->prepare('
    			SELECT *
    			FROM user
    			WHERE user_id = ?
    		');
    		// assumes session ID is set, you REALLY should check this FIRST!
    		$stmt->bindParam('i', $_SESSION['member_id']);
    		$stmt->execute();
    		// I have no clue what your user fields are, guessing wildly
    		$stmt->bindResult($userId, $userName);
    		if ($stmt->fetch()) {
    		} else {
    			// not found, send error and set as guest
    		}
    	} else {
    		// not logged in, set as guest 
    	}
    Though this begins to show mysqli's weakness and why I would HIGHLY suggest that if you're not too deep into this project, you switch over to PDO. Mysqli is pretty much brain dead in how it works, particularly with prepare+statements having an entirely different mechanism and interface than query/exec.

    Code:
    	session_start();
    	session_regenerate_id();
    	if (array_key_exists('member_id', $_SESSION)) {
    		// assuming $db is a connected PDO object
    		$stmt = $db->prepare('
    			SELECT *
    			FROM user
    			WHERE user_id = ?
    		');
    		$stmt->execute([$_SESSION['member_id']]);
    		if ($user = $stmt->fetch(PDO::FETCH_ASSOC)) {
    		} else {
    			// not found, send error and set as guest
    		}
    	} else {
    		// not logged in, set as guest 
    	}
    Far simpler. mysqli is just made of /FAIL/.

    Though honestly I would likely only do this once when the user logs in, and store all the current user's information in the session. That way you don't have to query it ever again. Do something like:

    Code:
    		if ($_SESSION['user'] = $stmt->fetch(PDO::FETCH_ASSOC)) {
    			// login successful
    		} else {
    			// set as guest
    			$_SESSION['user'] = [
    				'user_id' => -1,
    				'user_name' => 'guest'
    			]
    		}
    When they log in... Nowhere else in your site would you ever have to query that again. To log them out, just set $_SESSION['user'] back to the guest values. I often use -1 as the id for the guest account. Easy to check for.

    The basic idea being the less queries you have to do on every page-load, the better.

    Same goes for all those "variables for NOTHING" you were creating for that second query -- not only a massive security hole, but a waste of memory making copies of things that don't need copies.

    Code:
    	$stmt = $con->prepare('
    		UPDATE user
    		SET
    			first_name = ?,
    			middle_name = ?,
    			last_name = ?,
    			e_mail = ?,
    			user_name = ?
    		WHERE
    			user_id = ?
    	');
    	$stmt->bindParam(
    		'sssssi',
    		$_POST['first_name1'],
    		$_POST['middle_name_1'],
    		$_POST['last_name1'],
    		$_POST['e_mail1'],
    		$_POST['user_name1'],
    		$_SESSION['user_id']
    	);
    	if ($stmt->execute() && $stmt->affected_rows) {
    		// update successful 
    	} else {
    		// update failed
    	}
    As to the rest of your document, it's got problems. You're using a HTML 5 doctype, but have a bunch of attributes we don't use anymore. You no longer have to say type="text/javascript" on your SCRIPT tags or type="text/css" on your STYLE or CSS LINK tags(not that you ever really did as not one single browser EVER paid attention to that -- it's just now official!), you've got endless pointless JavaScript for nothing (and/or doing CSS' job!). Tour character encoding META is too late in the document forcing the browser to start over from scratch when it gets to it -- that should be the first tag after you open HEAD. You have no media targets on your stylesheets meaning you're sending your screen media layout to "all", you seem to have multiple stylesheets just making the page load take longer, and all those scripts in the HEAD are likely also delaying the page load since they're "blocking" in behavior.

    Seriously just axe the JS, you don't seem to be doing anything to warrant its presence on the page so far, especially the nube predator train wreck laundry list of how NOT to code JavaScript that is jQuery!

    Avoid saying things like "right" or "left" in your classes since that's presentational markup. Say what things are, NOT what you want them to look like since that appearance may not apply at all sizes or media targets.

    Flip your echo quotes, it's easier to use singles so your markup is doubles, it runs a hair faster, and since you're using echo use comma delimits instead of string addition.

    For example:

    Code:
    		echo '
    			<img
    				width="100" height="100"
    				src="/userProfilePic/', $row["userPic"], '"
    				alt="Profile Pic"
    			>';
    Far simpler/cleaner and runs a hair faster.

    BTW, you should NOT be needing the full local path if this is web served... if you're including public_html in your path client side, there is something REALLY jacked up with how it's hosting.

    Of course that entire section with the extra query of the user? You wouldn't need that if you stored it all in the session when the user logged in as I suggested. You could then just:

    Code:
    		echo '
    			<img
    				width="100" height="100"
    				src="/userProfilePic/', $_SESSION['user']['userPic'], '"
    				alt="', (
    					$_SESSION['user']['user_id'] == -1 ?
    					'Guest Picture' : 
    					$_SESSION['user']['user_name'] . "'s Picture"
    				), '"
    			>';
    Axing that entire second query, extra string, etc. Since all you have to do is store the user ONCE when they log in, you never have to manually query it again. Simpler.

    Oh, and don't be afraid of whitespace. Formatting is your friend.

    I'd have to see the form rendered, but I suspect you also have a slew of classes and DIV for nothing in there. As it sits it's incomplete form an accessibility standpoint for lacking a FIELDSET and I question the need for all those "SPAN for nothing" in there.

    Mind you, most of the above code is me guessing wildly as you don't seem to have a consistent naming convention for your tables/fields, and is more an example of what should be done and not direct code that can be cut/paste into your page. It will take some work to get you over to more modern techniques. (if changes we were supposed to switch to 14 years ago can be considered 'modern')

    Basically whatever source you're learning from is agonizingly out of date.
    “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies and the other way is to make it so complicated that there are no obvious deficiencies.” – C.A.R. Hoare, The 1980 ACM Turing Award Lecture
    http://www.cutcodedown.com


 

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •