Search code examples
phpuser-registration

INSERT INTO members cannot be executed


This is the problematic part of code:

$query = mysql_query("INSERT INTO members 
(user, pass, mail, country, city, www, credo)
VALUES  ('$_POST[user]','$_POST[pass]', '$_POST[mail]',
'$_POST[country]', '$_POST[city]', '$_POST[www]', '$_POST[credo]')")
or die ("Error - Couldn't register user.");

I got the die error.
How could I find more specific part which cannot be executed ?
I tried to eliminate fields one by one - without result.


Solution

  • This should present you the reason behind your failed query, and at the very least prevent some security concerns:

    Small Improvement

    // Run by each $_POST entry and set it to empty if not found
    // Clean the value against tags and blank spaces at the edges
    $dataArr = array();
    foreach($_POST as $key => $value) {
        $dataArr[$key] = ($value == "undefined") ? '' : strip_tags(trim($value));
    }
    
    // try to perform the INSERT query or die with the returned mysql error
    $query = mysql_query("
      INSERT INTO members 
      (user, pass, mail, country, city, www, credo)
      VALUES (
        '".$dataArr["user"]."',
        '".$dataArr["pass"]."',
        '".$dataArr["mail"]."',
        '".$dataArr["country"]."',
        '".$dataArr["city"]."',
        '".$dataArr["www"]."',
        '".$dataArr["credo"]."'
      )
    ") or die ("Error:<br/>".mysql_error());
    

    Medium Improvement

    // Run by each $_POST entry and set it to empty if not found
    // Clean the value against tags and blank spaces at the edges
    $dataArr = array();
    foreach($_POST as $key => $value) {
        $dataArr[$key] = ($value == "undefined") ? '' : strip_tags(trim($value));
    }
    
    // escape everything
    $query = sprintf("
        INSERT INTO members 
        (user, pass, mail, country, city, www, credo) 
        value ('%s', '%s', '%s', '%s', '%s', '%s', '%s')",
        mysql_real_escape_string($dataArr["user"]), 
        mysql_real_escape_string($dataArr["pass"]), 
        mysql_real_escape_string($dataArr["mail"]), 
        mysql_real_escape_string($dataArr["country"]), 
        mysql_real_escape_string($dataArr["city"]), 
        mysql_real_escape_string($dataArr["www"]), 
        mysql_real_escape_string($dataArr["credo"])
    );
    
    // try to perform the INSERT query or die with the returned mysql error
    $result = mysql_query($query) or die ("Error:<br/>".mysql_error());
    

    Advanced Improvement

    If you're starting a new project, or at a point where you can still change your ways, I vividly recommend the use of PHP PDO to prevent many security issues related the current database connection you're using.