Php & MySql help

meanbot36

New Member
Messages
2
Reaction score
0
Points
0
I am transferring my website from a diff host and cant get my any of my forms to work.I have spent over 2 days trying to get a single GD shred of information into my database here at x10hosting can not figure out why it just wont work. Tried different approaches and could really use a fresh pair of eyes here thanx in advance.


Here is a live example of the error code. http://muscle.pcriot.com/test.php

php codebox 1 (my form) php codebox 2 (driver for the form).

PHP:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD><TITLE></TITLE>
<META content="text/html; charset=unicode" http-equiv=Content-Type>
<META name=description content="">
<META name=keywords content="">
<META name=GENERATOR content="MSHTML 8.00.6001.22967"></HEAD>
<BODY>
<P>
<TABLE cellPadding=1 width=201 background=backer.jpg height=186>
  <TBODY>
  <TR>
    <TD align=left>
      <FORM method="post" name="signup" action="logincreate.php">
      <CENTER><B><FONT color=#cccccc>Get started 
      here.</FONT></B></CENTER><BR>
      <LABEL for="firstname"></LABEL>&nbsp;&nbsp;<INPUT id="firstname" 
      onclick="this.value='';" value="first name...." size="25" 
      name="firstname"><BR>
      <LABEL for="lastname"></LABEL>&nbsp;&nbsp;<INPUT id="lastname"  
      onclick="this.value='';" value="last name...." size="25" 
      name="lastname"><BR>
      <LABEL for="email"></LABEL>&nbsp;&nbsp;<INPUT 
      id="email" onclick="this.value='';" value="Email..." size="25" type="email" name="email"> <BR>
      <FONT 
      color=#cccccc><B>&nbsp;&nbsp;Password:</B></FONT><BR><LABEL 
      for="password1"></LABEL>&nbsp;&nbsp;<INPUT id="password1" onclick="this.value='';" value="Password" size="25" type="password" name="password1"><FONT 
      color=#cccccc><B>&nbsp;&nbsp;(retype)</B></FONT><BR><LABEL 
      for="password2"></LABEL>&nbsp;&nbsp;<INPUT id="password2"  
      onclick="this.value='';" value="Password" size="25" type="password" 
      name="password2"><BR>&nbsp;&nbsp; &nbsp;&nbsp;<INPUT value="Sign Up" type="submit" name="submit"> </FORM>
      </TD>
      </TR>
      </TBODY>
PHP:
<?php
  require_once('connectvars.php');

  // Connect to the database
  $dbc = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

  if (isset($_POST['submit'])) {
    // Grab the profile data from the POST
    $firstname = mysql_real_escape_string($dbc, trim($_POST['firstname']));
    $lastname = mysql_real_escape_string($dbc, trim($_POST['lastname']));
    $password1 = mysql_real_escape_string($dbc, trim($_POST['password1']));
    $password2 = mysql_real_escape_string($dbc, trim($_POST['password2']));
    $email = mysql_real_escape_string($dbc, trim($_POST['email']));
    
function isValidEmail($email){
      $pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$";
     
      if (eregi($pattern, $email)){
         return true;
      }
      else {
         return false;
      }   
   }
                        
    if (!empty($firstname) && !empty($lastname) && !empty($password1) && !empty($password2) && !empty($email) && ($password1 == $password2)) {
      // Make sure someone isn't already registered using this email
      if (isValidEmail($_POST['email'])){
                echo " ";
            }
            else{
                echo "The email: ".$_POST['email']." is invalid!";
                echo "<a href='javascript:history.back(1);'>Click here to go back and try Again.</A>";
                exit();
                }
      $query = "SELECT * FROM meanbot_ta WHERE email = '$email'";
      $data = mysql_query($dbc, $query);
      if (mysql_num_rows($data) == 0) {
        // The email is unique, so insert the data into the database
        $query = "INSERT INTO meanbot_ta (firstname, lastname, email, blah, llogin) VALUES ('$firstname', '$lastname', '$email', SHA('$password1'), NOW())";
        mysql_query($dbc, $query);
        
echo '<p>Your new account has been successfully created. You\'re now ready to <a href="login.php">log in</a>, and setup your ACCOUNT. </p><BR /><BR /><BR />';
echo '<TABLE align="center" width="80%"><TR><TD  valign="top" width="60%"><font face="arial" size="5" color="#003399"><B>What is my next step?</font></B><br /> <font face="verdana" size="2" color="#666666">Now that you have a Account. You can make or edit your fitness log. Follow the <a href="login.php">log in</a> link to begin.<br /><br /> <B>*</B>You can allways make changes by loging in from our main page  then finding the link in the top left corn labeled "Edit profile".';
echo "</font></td><TD><fieldset><legend><U>Here is your log-in information.</u></legend>";
echo 'The User Name: '.$_POST['email'].'<BR />';
echo "The password: ".$_POST['password1']."<BR />";
echo "The email: ".$_POST['email']."</font><BR /><font face=\"verdana\" size=\"2\" color=\"#666666\">*Your email address.</font></fieldset></TD></TR></TABLE>";
        // Confirm success with the user

        mysql_close($dbc);
        
        exit();


      }
      else {
        // An account already exists for this email, so display an error message
        echo '<p class="error">An account already exists for this Email. Please use a try a different email.</p>';
        $email = "";
      }
    }
    else {
      echo '<p class="error">You must enter all of the sign-up data, including the desired password twice.</p>';
    }
  }

  mysql_close($dbc);
?>

</body></html>
Just incase your lazy and did not go to the page i noted previously as my error code. This is the error i am receiving
Warning: mysql_real_escape_string() expects parameter 1 to be string, resource given in /home/meanbot/public_html/logincreate.php on line 10

for lines 11,12,13,14 too.
 

essellar

Community Advocate
Community Support
Messages
3,295
Reaction score
227
Points
63
It means what it says. You've got the statement backwards, so

Code:
$firstname = mysql_real_escape_string($dbc, trim($_POST['firstname']));

should be

Code:
$firstname = mysql_real_escape_string(trim($_POST['firstname']), $dbc);
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
If you read the documentation, you'll see that mysql_real_escape_string takes the string to escape as the first argument and the DB connection resource as the second argument.

There are a number of outdated extensions and practices used in the code (assuming the sample code is representative of the production code). When you've no other important tasks, you should update it.

  • The old mysql extension has been supplanted twice over. Replace it with PDO, the most up-to-date DB access extension. It has many advantages, including prepared statements, which are immune to SQL injection through statement parameters.
  • The ereg functions have been replaced by the preg_* functions, and are deprecated as of PHP 5.3.
  • Close all tags. In particular, <input> and <br> tags aren't closed in the sample.
  • Use CSS for styling & layout, not HTML elements such as tables and the non-semantic <center>, <b> and <font>. Even <br> can be done away with; give your <input>s block display and float the <label>s. Elements should define only the structure of the document, not its presentation.
  • Placing field descriptions inside the inputs has a couple of usability problems: when a user enters text into a field, the field loses its label (though this isn't as big a problem on the sample form, it should still be avoided), and the technique doesn't work well with anything other than mainstream browsers (for example, screen readers, spiders and some mobile devices won't be able to handle the form as effectively). It's particularly problematic in your implementation, for if the user goes back to a field, the click handler will erase anything they've already typed. Instead, use those currently empty <label> elements.
  • Even though HTML is largely case insensitive, the recommendation is that element names and attributes should be lower case.

Good description of the problem, by the way. It made it very easy to diagnose the problem & write a response. Including the error in the post was absolutely necessary, beyond reasons of laziness. If the server hadn't been working, we wouldn't have been able to get the error message.
 
Last edited:

meanbot36

New Member
Messages
2
Reaction score
0
Points
0
Problem solved::
@mission i am looking at all the updating you suggested, this may take awhile. I will post a updated version of this when im done. Thank you for your post.
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
Here's a rewrite of the code (untested) with the suggestions factored in. I also did away with exit(), which has the same problems as die() when outputting HTML. There are a few parts that need to be filled in (marked with "..."). For examples of the class LocalDB used below, see "Re: Display all that would be secret while Mysql is broken" and "Re:
PHP:
 MySQL and PHP[/URL]" (there are quite a few other threads with examples; search them out, if you're curious). There is still room for improvement. For example, you could define the form in one place, and use that info to both construct the form and validate it. You should also separate out the database access code into a separate [URL="http://en.wikipedia.org/wiki/Data_access_layer"]data access layer[/URL]. These both could be considered part of a larger improvement: [URL="http://en.wikipedia.org/wiki/Separation_of_concerns"]separating concerns[/URL] to reduce [URL="http://en.wikipedia.org/wiki/Coupling_(computer_science)"]coupling[/URL]. 

[code]CREATE TABLE meanbot_ta.users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    firstname VARCHAR(64) NOT NULL, 
    lastname VARCHAR(64),
    email VARCHAR(256) NOT NULL UNIQUE, 
    blah CHAR(40) NOT NULL, 
    llogin TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
[/code]

[html]<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
  <head>
    <title>Account Signup</title>
    <meta content="text/html; charset=unicode" http-equiv="Content-Type" />
    <style type="text/css">
      form#signup {
        float: left; /* shrink-wrap */
        background-image: url(backer.jpg);
      }

      label {
        text-align: right;
        float: left;
        background-color: #CCC;
        min-width: 8em;
        margin-right: 0.25em;
        padding: 0 0.25em;
      }
      input {
        display: block;
      }
      input[type="submit"] {
        margin-left: 12em;
      }
    </style>
  </head>
  <body>
    <form method="post" name="signup" action="logincreate.php">
      <fieldset>
        <legend>Get started here.</legend>
        
        <label for="firstname">First Name</label>
        <input id="firstname" name="firstname" value="" size='25'/>
        
        <label for="lastname">Last Name</label>
        <input id="lastname" name="lastname" value="" size='25'/>
        
        <label for="email">E-Mail</label>
        <input id="email" name="email" value="" size='25'/>
        
        <label for="password1">Password</label>
        <input id="password1" name="password1" value="" size='25' type='password'/>
        
        <label for="password2">Confirm password</label>
        <input id="password2" name="password2" value="" size='25' type='password'/>
        
        <input id="submit" name="submit" value="Sign Up" size='25' type='submit'/>
        
      </fieldset>
    </form>
  </body>
</html>[/html]

[php]<?php
// for class LocalDB
require_once('LocalDB.php');

$fields = array(
    'firstname' => array('filter' => FILTER_SANITIZE_STRING, 'label' => 'first name'),
    'lastname' => array('filter' => FILTER_SANITIZE_STRING, 'label' => 'last name'),
    'email' => array('filter' => FILTER_VALIDATE_EMAIL, 'label' => 'e-mail address'),
    'password1' => array('filter' => FILTER_UNSAFE_RAW, 'label' => 'password'),
    'password2' => array('filter' => FILTER_UNSAFE_RAW, 'label' => 'password confirmation'),
);

if (isset($_POST['submit'])) {
    // Validation
    $errors=array();
    $data = filter_var_array($_POST, $fields);
    foreach ($data as $field => $value) {
        if (is_null($value)) {
            $errors[$field] = "You must enter your {$fields[$field]['label']}.";
        } elseif (False === $value) {
            // validation failed
            if (empty($_POST[$field])) {
                $errors[$field] = "You must enter your {$fields[$field]['label']}.";
            } else {
                $errors[$field] = "'{$_POST[$field]}' isn't a valid {$fields[$field]['label']}.";
            }
        } else {
            $user[":$field"] = $value;
        }
    }
    // password confirmation test
    if ($data['password2'] && $data['password1'] != $data['password2']) {
        $errors['password2'] = "Passwords do not match.";
    } else {
        unset($user[':password2']);
    }

    if ($errors) {
        // redisplay form, with errors beside each input field that failed validation. Make
        // sure to refill form values with data that user entered.
        ...
    } else { // validation successful
        try {
            $db = LocalDB::connect();
            $createUserQuery = $db->prepare("INSERT INTO meanbot_ta.users (firstname, lastname, email, blah) VALUES (:firstname, :lastname, :email, SHA(:password1))");

            $createUserQuery->execute($user);
            // Creation successful. Display success message, log in user, and display profile editing form.
            ?>
            <p>Your new account has been successfully created. You can start filling out your profile below.</p>
            <?php
            ...
            /* e.g.:
            login($user[':email'], $user[':password1']);
            include('edit/profile.php');
            */
        } catch (PDOException $exc) {
            switch ($createUserQuery->errorCode()) {
            case '23000': // duplicate primary key; user exists
                ?>
                <p class="error">An account already exists for this e-mail address. Please use a try a different email.</p>
                <?php
                break;
                
            default: // internal error. Inform user & log
                ?>
                <p class="error">I had an internal error when trying to communicate with the database. It's been logged, and we'll look into it. Please try again later.</p>
                <?php
                // log error
                ...
                break;
            } /* end switch errorCode */
        } /* end catch PDOException */
    } /* end validation successful */
} /* end form submitted */
?>
 
Last edited:
Top