Is this small bit of code correct...

Discussion in 'PHP' started by jack_23, Jun 24, 2007.

  1. #1
    Is this small bit of code correct. I'm trying to add mysql_real_escape_string to all my queries. Is what i have below enough to stop SQL injections and other threats. Have i used it correctly

    $username = mysql_real_escape_string($_POST['username']);
    $check = mysql_query("SELECT username FROM accounts WHERE username = '$username'")
    or die(mysql_error());
    $check2 = mysql_num_rows($check);
    PHP:
    Also, can you take a small look at the code i have below

    
    //retrieve form data in a variable
    $firstname  = mysql_real_escape_string($_POST['firstname']);
    $lastname  	= mysql_real_escape_string($_POST['lastname']);
    $username 	= mysql_real_escape_string($_POST['username']);
    $password  	= mysql_real_escape_string($_POST['password']);
    
    ////// How to i add mysql_real_escape_string to the code below//////
    $DOB 		= date("Y-m-d", mktime(0,0,0,$_POST['DOBmm'],$_POST['DOBdd'],$_POST['DOByyyy'])); // keep the DOB as one
    PHP:
    Also, do i need to add stripslashes anywhere in my code, sorry i am new to the security of PHP
     
    jack_23, Jun 24, 2007 IP
  2. iRAY

    iRAY Peon

    Messages:
    21
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    1) Yes, you are correct. You can also use addslashes() when mysql_real_escape_string() is not available.

    2) If $DOB variable will be used in SQL query only, than you don't need escape characters, because date() return safe-formatted string.

    Yes. Welcome to the PHP :)
    Fortunately, there are lot of pre-coded DB layers for PHP which do this for you.
     
    iRAY, Jun 24, 2007 IP
  3. HuggyCT2

    HuggyCT2 Guest

    Messages:
    222
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I personally would just make a php function to check wether you need to use the functions.

    Something like:


    
    <?php
    	function clean($var) // Clean post data and get
    		{
    		if (get_magic_quotes_gpc())
    			{
    			$var = strip_tags($var);
    			return $var;
    		}else{
    			$var = addslashes(strip_tags($var));
    			return $var;
    			}
    		}
    ?>
    
    PHP:
     
    HuggyCT2, Jun 24, 2007 IP