What is the best approach to replacing data in a database? I have a site which allows users to register. I have a page for them to reset their password if needs be. I'm not sure how to replace the existing password with their new password.

Should I be looking at dbase_replace_record()?

Now sure how to go about doing this.

Kind regards,

Labtec.

    Labtec wrote:

    Should I be looking at dbase_replace_record()?

    Are you really using dBase? I note that the PHP manual states:

    We recommend that you do not use dBase files as your production database. Choose any real SQL server instead; » MySQL or » Postgres are common choices with PHP. dBase support is here to allow you to import and export data to and from your web database, because the file format is commonly understood by Windows spreadsheets and organizers.

    If not, what database extension are you using? What are the relevant tables? I presume that you are hashing the passwords with a salt value?

      I'm using WAMP on my local machine and I also run a domain which I upload things to.

      I am encrypting the password using the md5() function before inserting the pass into the database. I have 1 database with 2 tables in.

      Members table - id, username, pasword, email.

      I have got the registration form done fine. It works as intended. When the user loses/forgets their password, I have a forgotten pass page where they enter their email address. I send them an email with a link inside which I pass the username and id through the url and use the $_GET global to retrieve them on that page. From there, I select the existing password from the database depending on the id being matched but I don't know how to replace the password with the new password.

        Labtec wrote:

        I'm using WAMP on my local machine

        That is, you are using MySQL as the database system. You should still answer my question as to what database extension you are using. If it is the legacy MySQL extension, then you would do well to switch to the PDO extension or MySQLi extension.

        Labtec wrote:

        I am encrypting the password using the md5() function before inserting the pass into the database. I have 1 database with 2 tables in.

        Members table - id, username, pasword, email.

        That is not good enough. At the very least, you should have another column to store a user specific randomly generated salt value, which is repeatedly combined with a hash of the password to obtain the hash to be stored.

        Labtec wrote:

        From there, I select the existing password from the database depending on the id being matched but I don't know how to replace the password with the new password.

        The same way that you check their password, except that instead of comparing hashes, you store the resulting hash.

          I'm not sure how to check what database extension I am using. Sorry, I am still very new to php.

          I will read into Salts, I have heard the term before but never read up about it.

          Thank you for your help so far.

          Kind regards,

          Labtec.

            Labtec wrote:

            I'm not sure how to check what database extension I am using.

            If you post a code sample here, we may be able to identify it. What material are you using to learn PHP?

              I usually refer to php.net or w3schools. If I need specifics I usually google it and try a few sites out or come to forums.

              Here is the code from recoverpass.php (the action file for users to reset):

              <?php
              session_start();
              ?>
              <html>
              <head>
              <link rel="stylesheet" type="text/css" href="styles/email.css" />
              </head>
              </html>
              <?php
              //ACTION SCRIPT
              
              /*FUNCTION TO GENERATE A NEW PASSWORD FOR THE USER. RETURNS A NEW PASSWORD TO THE CALLING CODE*/
              function get_new_pass(){
                  $chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
              	$size = strlen($chars);
              	$length = 8;
              
              for($i = 0;$i < $length;$i++){
                  $new_pass .= $chars[rand(0, $size-1)]; 
              }
              return $new_pass;
              }
              
              
              /*FUNCTION TO SANITIZE USER INPUT. RETURNS USER INPUT STRIPPED OF ANY SPECIAL CHARACTERS*/
              function check_input($data) {
              
              $con = mysql_connect("localhost", "root", "");
                 if(!$con){
                    $_SESSION['connection_error'] = "Connection error directly in action script.";
                    header("Location: index.php");
                    }
              $illegalChars = array('!','@','#','$','%','^','&','*','(',')','+','=','-','[',']','.',';',',','/','{','}','|','"',':','<','>','?','~','£'); 
              $data = str_replace($illegalChars,'',$data);
              $data = trim($data);
              $data = stripslashes($data);
              $data = htmlspecialchars($data, ENT_QUOTES);
              $data = mysql_real_escape_string($data,$con);
              return $data;
              }
              
              $email = $_POST['email'];
              
              if(!isset($email)){
                  $_SESSION['no_email'] = "Please fill in the form.";
              	header("Location: password_recovery.php");
              }
              else{
              
                 if(!filter_var($email, FILTER_VALIDATE_EMAIL)){//IF IT IS NOT A VALID EMAIL...
                    $_SESSION["email"] = "Email is not valid";//CREATE SESSION TO USE IN index.php AS ERROR MESSAGE.
                    header("Location: index.php");//LOCATE USER TO index.php
                 }
                 else{
              
                require("connectdb.php");//CONNECT TO DATABASE AND SELECT DATABASE.
                $sql = mysql_query("SELECT * FROM members WHERE email='{$email}'");//SELECT EVERYTHING FROM MEMBERS TABLE ONLY WHERE email TABLE FIELD MATCHES THE USER INPUT EMAIL.
                $count = mysql_num_rows($sql);//COUNT HOW MANY ROWS WERE MATCHED.
              
                if($count == 1){//IF EMAILS WERE MATCHED...
              
                   $row = mysql_fetch_array($sql);   
              	 $id = intval($row['id']);
                   $get_user = $row['username'];//RETRIEVE USERNAME FROM DATABASE.
              
                    if($id && $get_user){
                       $to = $email;//STORED EMAIL IN VARIABLE
                       $sub = "Deus Ex Demo Upload/Download - Password Recovery";//EMAIL SUBJECT FIELD.
                       $body = "<p class='lucida'>Hello, {$get_user}<br /><br />";//EMAIL BODY CONTENT.
                       $body .= "You have received this email because you have lost/forgotten your password.<br />";
              		 $body .= "Please visit the link below to reset your password.";
              		 $body .= "<a href='reset_pass.php?id=".urlencode($id)."&user=".urlencode($get_user)."'>Reset Your Password</a>";
                       $body .= "Kind Regards,<br />";
                       $body .= "<span class='blue'>Labtec</span></p><br />";
                       $headers = "From: labtec@dxdu.com\r\n" . "X-Mailer: php";
                       $headers .= "Reply-To: labtec@dxdu.com\r\n";
                       $headers .= "Return-Path: labtec@dxdu.com\r\n";
                       $headers .= "MIME-Version: 1.0\r\n";
                       $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
              
                       if(mail($to, $sub, $body, $headers)){
                          $_SESSION['pass_sent'] = "Password Recovery Successful. You will shorty receive an email confirming your password.";
              	        //header("Location: index.php");
                       }
                       else{
                          $_SESSION['pass_not_reset'] = "There was an error sending your password via email. Please contact the site administrator.
              	                                       Sorry for any inconvenience.";
                          //header("Location: password_recovery.php");										 
                       }
                   }
                   else{
                      $_SESSION['pass_not_reset'] = "There was an error sending your password via email. Please contact the site administrator.
              	                                 Sorry for any inconvenience.";
              	    //header("Location: password_recovery.php");		
                   }
                }
                else{//IF NO EMAILS WERE MATCHED IN THE TABLE
                   $_SESSION['invalidemail'] = "Invalid Email Address";//CREATE SESSION TO USE IN pass_rec.php
                   //header("Location: password_recovery.php");//LOCATE USER TO pass_rec.php
                }
                 }
              }
              ?>
              

              As you can see, the email sends a url which also passes the id and user values.

              Then on reset_pass.php (the link within the email), I retrieve the id and username (used to determine the correct pass to change) I then select the row depending on the id value and select the password field value. Here is the code:

              reset_pass.php (also used as the action file for the form):

              <?php session_start(); ?>
              <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
                   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
              
              <html xmlns="http://www.w3.org/1999/xhtml">
              <head>
                   <title>Deus Ex Demo Reset Password</title>
              	 <link rel="stylesheet" type="text/css" href="styles/main.css" />
              </head>
              <body>
              <div id="container">
                  <a href="membersarea.php">
              	   <img src="images/mainbanner_v3.png" alt="DXDU Logo" id="logo" title="Deus Ex Demo Uploader Logo" border="0" />
              	</a>
              
              <div id="passResetDiv">
                   <p class="lucida" id="new_pass_p">Please enter your new password into the field below.</p>
              
              	 <form id="reset_pass_form" method="POST" action="reset_pass.php">
                       <p><label for="newpass" id="passLabel">Enter Password:</label><input type="text" name="newpass" id="newpass" size="30" maxlength="10" /></p>
                       <p><label for="submit"></label><input type="button" name="submit" value="Proceed" /></p>
                   </form>
              	 <?php
              
              	 function check_input($data) {
                       $con = mysql_connect("localhost", "root", "");
                           if(!$con){
                           $_SESSION['connection_error'] = "Connection error directly in action script.";
                           header("Location: index.php");
                           }
              
                       $illegalChars = array('!','@','#','$','%','^','&','*','(',')','+','=','-','[',']','.',';',',','/','{','}','|','"',':','<','>','?','~','£'); 
                       $data = str_replace($illegalChars,'',$data);
                       $data = trim($data);
                       $data = stripslashes($data);
                       $data = htmlspecialchars($data, ENT_QUOTES);
                       $data = mysql_real_escape_string($data,$con);
                       return $data;
                   }
              
              	 $pass = check_input($_POST['newpass']);
              
              	 if(isset($pass)){
              	    $id = $_GET['id'];
              	    $user = $_GET['user'];
              
              		require("connectdb.php");
              		$sql = mysql_query("SELECT password FROM members WHERE id='{$id}'");
              		if(!$sql){
              		    $_SESSION['select_query'] = "Query Failed.";
              		    header("Location: reset_pass.php");
              		}
              		else{
              		    $qry = mysql_query("INSERT $pass INTO members");
              		}
              
              
              	 }
              	 else{
              	     $_SESSION['enter_value'] = "Please enter an email address into the field before proceeding.";
              	     header("Location: reset_pass.php");
              	 }
              
              	 ?>
              </div>
              
              
              
              
              
              <!--FOOTER CONTENT-->
              <div id="footerDiv">
                  <img src="images/hkbanner.jpg" alt="HunterKillerz Clan Logo" title="HunterKillerz Clan Logo" id="hk" border="0" />
              	<div id="hkDiv">
              	    <a href="http://z3.invisionfree.com/HunterKillerz/index.php?act=idx" id="clanLink" target="_blank">[HK]Hunter Killers Forum</a><br />
              	    <p id="visit">Please visit [HK]'s Official Clan Forums.</p>
              	    <p id="designer">Site designed by <span id="labtec">[HK]Labtec</span></p>
              	</div>
              	<p class="footP">Please visit the links to the right as they are all Deus Ex related with some good resources to help get you setup.
              	                 Feel free to email me and suggest any links to be added to the footer.</p>
              	<a href="http://www.dxalpha.com/" target="_blank">
              	    <img src="images/alphalogo.gif" alt="Alpha Logo" title="Alpha Logo" class="alpha" border="0" />
                  </a>
              	<a href="http://kentie.net/" target="_blank">
              	    <img src="images/kentie.jpg" alt="Kentie Logo" title="Kentie Logo" class="kentie" border=" 0" />
                  </a>
              	<a href="http://thc.b1.jcink.com/index.php" target="_blank">
              	    <img src="images/thclogo.jpg" alt="THC Clan Logo" title="THC Clan Logo" class="thc" border="0" />
                  </a>
              </div>
              </div>
              </body>
              </html>
              

              Kind regards,

              Labtec.

                Labtec;11008607 wrote:

                I'm not sure how to check what database extension I am using.

                If you're using the [man]mysql[/man] extension, the functions will be prepended with 'mysql'. Likewise for [man]MySQLi[/man] and [man]PDO[/man], the prefix would be 'mysqli' or 'pdo_' (respectively). If using the OOP approach, it'd be a rather obvious variation (you'd see "new MySQLi" or "new PDO").

                Labtec;11008615 wrote:

                I usually refer to php.net or w3schools.

                The former is a good resource for PHP, and the latter is a terrible resource for... well pretty much anything. Don't become a w3fool!

                As for your code... lots of issues. For example, here's a critique of your check_input() function:

                1. $con = mysql_connect("localhost", "root", ""); 

                  Why are you connecting to a database? This isn't connect_to_db_and_then_check_input() - it's just check_input(). Even if it was, why would you want to call mysql_connect() for every piece of input rather than only once?

                2.        if(!$con){ 
                            $_SESSION['connection_error'] = "Connection error directly in action script."; 
                            header("Location: index.php"); 
                            } 

                  Ignoring the fact that the 'Location' header requires an absolute URI (although you shouldn't ignore this requirement), why do you set a redirect header but then continue on processing the rest of the code? Furthermore, how does 'index.php' handle these error messages? Does it check for various keys set in the $_SESSION array, meaning if you want to define a new error message, you have to edit all of your scripts to check for a new specific key? Seems like it would be a lot more efficient (and easier) to use a generic key e.g. $_SESSION['errors'] and store an array of strings inside of it.

                3.              $illegalChars = array('!','@','#','$','%','^','&','*','(',')','+','=','-','[',']','.',';',',','/','{','}','|','"',':','<','>','?','~','£');  

                  Why are any of those characters "illegal" ? What's wrong with them? If I want a very secure password like '!@p?&ass$w%ord', why would you want to strip those characters out (leaving me with a password of 'password' instead)?

                4. $data = trim($data);

                  Likewise, if I want to prepend (or suffix) my password with several spaces (something the run-of-the-mill password cracker probably doesn't account for), why are you removing those spaces? I don't go randomly pressing my spacebar a few times without reason and just assume that the web application will be kind enough to clean up after me.

                5. $data = stripslashes($data); 

                  Why are you stripping slashes from the input? The only time you should want to do that is to reverse the effects of [man]addslashes/man and/or magic_quotes_gpc. That is to say, you shouldn't ever be doing that (since you shouldn't ever be using either of those two things in the first place).

                6. $data = htmlspecialchars($data, ENT_QUOTES);

                  Why do this for all data when you receive it? If you don't want data from the DB to be interpreted as HTML, it'd be much more appropriate to use this function when retrieving that data - not when storing it. (Otherwise you lose the original data and can only work with a mangled version of it.)

                7. $data = mysql_real_escape_string($data,$con); 

                  This suggests that check_input() should only be called on string data, e.g. it would be inappropriate for things such as numerical data. If that is your intent, then "check_input_string" or something of the like would probably be a more informative name for this function (that way you wouldn't be tempted to use it on numbers or anything like that).

                What's worse is that you don't even use that function for all user-supplied data before using said data inside a SQL query. In other words, you're leaving yourself vulnerable to SQL injection attacks and/or just plain SQL errors. See [man]security.database.sql-injection[/man] for an introduction to the former.

                Finally, the heart of the matter - resetting the user's password in your database. This SQL query:

                $qry = mysql_query("INSERT $pass INTO members"); 

                makes no sense. You'd end up with something like:

                INSERT abcd123 INTO members

                which has a number of problems:

                1. You shouldn't be INSERT'ing data at all; you should be UPDATE'ing an existing tuple in the table. That means you should be using an UPDATE query.

                2. The MySQL manual shows that the INSERT query should look like:

                  INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
                      [INTO] [i][b]tbl_name[/b][/i]

                  However, you've got random data between "INSERT" and "INTO".

                3. Furthermore, all string data must be delimited in SQL queries (just as they would in PHP code) - e.g. using single quotes.

                Instead, you should be executing a query that looks more like:

                UPDATE your_sql_table
                SET the_password_column = 'some_new_value'
                WHERE a_primary_or_candidate_key_column = 'some_key_value'

                where the primary/candidate key column would depend upon how you've designed the table (e.g. it could be a username or user ID).

                  Thank you so much for all that input, I will keep all of it in mind. I actually got that function off another forum where I had help for another issue. The reason I didn't want any special characters inserted is because I was under the impression any of those characters could potentially damage my code/database. Is that only the case with double and single quotes? I also wanted it 'easy-to-read' from the database, rather than having the converted html chars.

                  The reason I connect to the host within the function is because when I host my website on my domain, it is running a different version of PHP than my WAMP server. I was given help off another forum and was told I should connect to the server/host before trying to use mysql_real_escape_string - (I was receiving error messages at the time).

                  What I have decided to do is go back to my main index.php page, and the 2 forms (register and login) will have their action files re-written. All the flaws you pointed out really concerns me. If I am going to go live, I want it to be coded as robust as possible.

                  Are there any tips/advice you would give someone who is writing an action file. What things would you do first? Are there any 'must-do' things that you do within your action files before doing anything else??

                  Apart from my function, what else is wrong with my code? Is it an absolute shambles? Can it be saved and modified slightly or would it be best to actually start from scratch?

                  Thanks once again for the long reply, I'll keep browsing over it and familiarizing myself with my errors.

                  Kind regards,

                  Labtec.

                    Labtec;11008687 wrote:

                    The reason I didn't want any special characters inserted is because I was under the impression any of those characters could potentially damage my code/database.

                    They can damage nothing if dealt with properly. You are of course free to make any restrictions on input you see fit (although it may be more user friendly to allow input and then escape it properly), but never just strip things out. If I input "john" as my username and "\doe" as my passwrod and you strip slashes, both when the account is created and when I log in, I will be able to login using either "doe" or "\doe". Since I thought you stored "\doe", this is what I use. Should you one day start allowing slashes, I'd no longer be able to login.

                    Always inform the user of invalid input, tell them what would be valid and present the input back to the user so that they may correct it.

                    Labtec;11008687 wrote:

                    Is that only the case with double and single quotes? I also wanted it 'easy-to-read' from the database, rather than having the converted html chars.

                    Sometimes yes, sometimes no. It always depend on where you try using them. Some databases will have issues with both, others with either and some depending on settings. SQL Standard dictates that strings be delimited only by single quotes, thus meaning that double quotes are never an issue inside a string literal. However, iirc MySQL can allow double quoted string literals unless running in strict mode.

                    The standard states that single quotes are escaped by single quotes inside string literal, i.e. this is one string literal containin one single quote

                    'a string with '' single quote' 
                    

                    But once again, MySQL may be doing other stuff unless running in strict mode (always do run it in strict mode by the way), by allowing single quotes to be escaped by .

                    The reason you need to connect to the DB before using mysqli_real_escape_string is that it will ask that particular db about what to escape and how to escapeit.

                    Labtec;11008687 wrote:

                    The reason I connect to the host within the function is because when I host my website on my domain, it is running a different version of PHP than my WAMP server.

                    I fail to see the reason for this. Wether you use the same PHP version or not, you should still be able to connect to the DB in the exact same manner. While ot works doing so inside the function, this also means connecting once every time you run the function. It could be fixed by

                    function lots_of_stuff_happening($input)
                    {
                    	# Notice the use of mysqli, rather than mysql
                    	# Personally I prefer PDO, but use either that or mysqli, never mysql
                    	static $con = mysqli_connect('...');
                    }
                    

                    Inside a function, use of the static keyword means the variable is initiated once and then retains it value between calls. However, it's still bad to do it this way, since, as brad points out, your function is called "check_input". If it's called "check_input", it should check input. If it's called connect_to_db_check_input_and_save_stuff_to_file, it should do those things. And apart from making for long and hard to read names, it makes the functions long and hard to read (and maintain) as well, which is why you should try to keep functions focused on doing one thing or one group of things. For example, function check_input($input, $type) might deal with string, date, integer and float data types. But unless it does, you should listen to brad and rename it check_string.

                    Next issue with check_input is that it doesn't check input for just any reason. It applies first htmlchars to it, which means the input will only ever be suitable for use as output in html pages, and secondly it escapes it for insertion into a particular MySQL database. Apply htmlspecialchars or htmlentities only when you output stuff in an html page, do not store it that way. Escape it for db insertion (or updates) just before you insert (or update) into the db.

                    Personally I usually go with prepared statements when inserting things, since that means I don't have to worry about how to escape particular data or when it's done. Example using PDO

                    $string = "Some input containing ' single quote";
                    $date = "2001-10-15";
                    $int = 10;
                    
                    $db = new PDO('connection stuff here');
                    $db->prepare('INSERT INTO tbl(string_col, date_col, int_col) VALUES(:arraykey_one, :arraykey_two, :third_name)');
                    $db->execute(array('arraykey_one' => $string, 'arraykey_two' => $date, 'third_name' => $int));
                    

                    This way you send the data separately from the query and the DB will know how to handle the specifics of each item. You may also prepare a query once, then iterate over execute multiple times using different array data for insertion/update.
                    But, as long as you either escape data as the very last thing before a direct query or use prepared statements, you're fine. Some people might tell you not to use prepared statement unless you will execute more than once. I've never bothered to check if preparing a statement takes more time than escaping arguments, but I suspect it's too little differerence to matter. Use which ever method you prefer (but do go with either PDO or mysqli)!

                    Labtec;11008687 wrote:

                    connect to the server/host before trying to use mysql_real_escape_string

                    Which as I explained above is that it needs to ask the DB what to escape and how to escape it since it depends on server settings.

                    What I have decided to do is go back to my main index.php page, and the 2 forms (register and login) will have their action files re-written. All the flaws you pointed out really concerns me. If I am going to go live, I want it to be coded as robust as possible.

                    Labtec;11008687 wrote:

                    Are there any tips/advice you would give someone who is writing an action file. What things would you do first? Are there any 'must-do' things that you do within your action files before doing anything else??

                    I usually have an require file which deals with things I need in most, if not all scripts. That file may contain all of the stuff that needs to be done, or it may in turn require other files. Do note that I rarely include a file, since if it's missing, I'd expect something to be very wrong, and thus I use require instead.

                    For example, you might find this at the top of all my script files that are intended to be executed rather than included by something else

                    require 'settings.php';
                    

                    And then settings.php might look like

                    # Deal with autoloading files when classes are referenced
                    # This means that if I reference SomeClass, then the file "SomeClass.php" is automatically required (once)
                    function __autoload($class_name) {
                    	require_once '/path/to/phpclasses/'.$class_name . '.php';
                    }
                    
                    # and perhaps
                    $db = new mysqli(...);
                    
                    # Then you might have all your functions dealing with validation and sanitation in
                    require 'validation.php';
                    require 'sanitation.php';
                    

                    And now that you have a connection to your DB, you should also change your functions to take the connection as a parameter instead

                    function dbstring($input, $db) {
                    	return $db->real_escape_string($input);
                    }
                    
                    Labtec;11008687 wrote:

                    Apart from my function, what else is wrong with my code? Is it an absolute shambles? Can it be saved and modified slightly or would it be best to actually start from scratch?

                    Do whatever you feel more confortable with or believes will take less time. You'll learn either way 🙂

                    I'd also like to add that I believe it's bad having a redirect inside a function like "check_input" for the same reasons as discussed before. Have the function check input and return false if the check fails. Then have the calling code decide what to do. Sometimes you may wish for a redirect, other times you might wish to redisplay the same page with user input redisplayed to the user along with an error message...

                    And on the notion of redirect and pages processing form posts, you might wish to always redirect the user after a successful post, since the user might otherwise reload the same page and send the same data again (rather than reload the page they were redirected to which posts no new data). Do note that you might actually redirect them to the exact same page (depending on how you build things).

                      johanafm;11008777 wrote:

                      They can damage nothing if dealt with properly. You are of course free to make any restrictions on input you see fit (although it may be more user friendly to allow input and then escape it properly), but never just strip things out. If I input "john" as my username and "\doe" as my passwrod and you strip slashes, both when the account is created and when I log in, I will be able to login using either "doe" or "\doe". Since I thought you stored "\doe", this is what I use. Should you one day start allowing slashes, I'd no longer be able to login.

                      Always inform the user of invalid input, tell them what would be valid and present the input back to the user so that they may correct it.

                      So it's always better to let the user enter what they wish and just escape the data before inserting? Are there any characters that you do not allow users to enter when writing your scripts? I will be taking your advice anyhow and letting the user enter what they wish, escaping the data before insertion? If a user entered something like L@bte< into a name field, in your experience would you allow that data to be entered or would you ask for a re-input?

                      johanafm;11008777 wrote:

                      Sometimes yes, sometimes no. It always depend on where you try using them. Some databases will have issues with both, others with either and some depending on settings. SQL Standard dictates that strings be delimited only by single quotes, thus meaning that double quotes are never an issue inside a string literal. However, iirc MySQL can allow double quoted string literals unless running in strict mode.

                      The standard states that single quotes are escaped by single quotes inside string literal, i.e. this is one string literal containin one single quote

                      'a string with '' single quote' 
                      

                      But once again, MySQL may be doing other stuff unless running in strict mode (always do run it in strict mode by the way), by allowing single quotes to be escaped by .

                      How can I check what mode I am using? Or how can I use that mode? Sorry if this question doesn't make sense but I have never heard of that.

                      johanafm;11008777 wrote:

                      Next issue with check_input is that it doesn't check input for just any reason. It applies first htmlchars to it, which means the input will only ever be suitable for use as output in html pages, and secondly it escapes it for insertion into a particular MySQL database. Apply htmlspecialchars or htmlentities only when you output stuff in an html page, do not store it that way. Escape it for db insertion (or updates) just before you insert (or update) into the db.

                      Would it be better to use that type of function when reading the data from the database then? Is it bad to create many functions which do a menial task or should you try and make your functions do as much as possible?

                      johanafm;11008777 wrote:

                      Personally I usually go with prepared statements when inserting things, since that means I don't have to worry about how to escape particular data or when it's done. Example using PDO

                      $string = "Some input containing ' single quote";
                      $date = "2001-10-15";
                      $int = 10;
                      
                      $db = new PDO('connection stuff here');
                      $db->prepare('INSERT INTO tbl(string_col, date_col, int_col) VALUES(:arraykey_one, :arraykey_two, :third_name)');
                      $db->execute(array('arraykey_one' => $string, 'arraykey_two' => $date, 'third_name' => $int));
                      

                      This way you send the data separately from the query and the DB will know how to handle the specifics of each item. You may also prepare a query once, then iterate over execute multiple times using different array data for insertion/update.
                      But, as long as you either escape data as the very last thing before a direct query or use prepared statements, you're fine. Some people might tell you not to use prepared statement unless you will execute more than once. I've never bothered to check if preparing a statement takes more time than escaping arguments, but I suspect it's too little differerence to matter. Use which ever method you prefer (but do go with either PDO or mysqli)!

                      How do I start using mysqli? Do I literally just use mysqli_connect(); or do I have to change some settings?

                      johanafm;11008777 wrote:

                      I'd also like to add that I believe it's bad having a redirect inside a function like "check_input" for the same reasons as discussed before. Have the function check input and return false if the check fails. Then have the calling code decide what to do. Sometimes you may wish for a redirect, other times you might wish to redisplay the same page with user input redisplayed to the user along with an error message...

                      And on the notion of redirect and pages processing form posts, you might wish to always redirect the user after a successful post, since the user might otherwise reload the same page and send the same data again (rather than reload the page they were redirected to which posts no new data). Do note that you might actually redirect them to the exact same page (depending on how you build things).

                      How do I redisplay the data on the form page? I will keep reading and reading over this thread as it was quite hard to understand. My code seems to always be built on if statements and I want to get out of that and start making my code easier to read and more effective to use.

                      Can you recommend any good PHP tutorials, even from beginner to advanced. I'm lacking resources which is really frustrating for me as I seem to have picked the language/syntax up quite quickly but haven't been able go that step further. There are many beginner tutorials which I have read but they seem repetitive talking about basic basic php like variables, types etc. A lot of them also seem to be dated a while ago so i'm not sure on a good, reliable source to learn php from (apart from maybe php.net but again it seems a little too complex to understand the wording, as in they kinda expect you to know what you're doing).

                      Kind regards,

                      TY

                      Labtec.

                        Labtec wrote:

                        or should you try and make your functions do as much as possible?

                        Your functions should each do one thing and do it thoroughly.

                        Your original check_input() function, by contrast, is doing three or four things (depending on whether you think of "checking for a connection" and "redirecting if there is no connection" as one or two things - probably two as there are likely to be reasons to do one without the other; the other two being checking input (actually changing input) and escaping data for use in a MySQL query.

                        Labtec wrote:

                        Can you recommend any good PHP tutorials,

                        Don't restrict yourself to PHP tutorials. Look for programming tutorials, as the principles are pretty much the same whatever the language.

                        but again it seems a little too complex to understand the wording, as in they kinda expect you to know what you're doing

                        I.e., programming 🙂

                          Write a Reply...