1
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];

function random_string($length) {
    $key = '';
    $keys = array_merge(range(0, 9), range('a', 'z'));

    for ($i = 0; $i < $length; $i++) {
        $key .= $keys[array_rand($keys)];
    }

    return $key;
}

if($email)
{

$connect = mysql_connect(" HOST ", " USERNAME ", " PASSWORD") or die("Couldn't Connect");

mysql_select_db("CiniCraftData") or die ("Couldn't Find Database"); 

            $query = "INSERT INTO customers (fname, lname, email, alphanum) VALUES ('$fname', '$lname', '$email', 'random_string(10)')";
            $result = mysql_query($query) or die("Some kind of error occured.");

            echo ("Welcome " + $username + ", you are now in my database!");

}
else die("You did not fill out the fields correctly, please try again.");

?>

I need help with the line in the middle that starts with $query = "INSER ... 'random_string(10)')";

I need a random alphanumeric string to be inserted into the table called "customers" but instead of calling the function "random_string()" it inserts "random_string(10)" into my table which gives me this for my table with 6 fields:

5   John    Smith   [email protected] random_string(10)   0

How do I fix this?

4
  • 4
    You shouldn't include the username and pass for your DB when you post questions Commented Dec 31, 2012 at 0:43
  • 1
    And most certainly not the server... Commented Dec 31, 2012 at 0:44
  • 1
    I'd change your server credentials... and quickly. Commented Dec 31, 2012 at 0:45
  • Compulsory comment - please use mysqli or pdo instead of mysql_* functions - they've been deprecated Commented Dec 31, 2012 at 0:47

3 Answers 3

3
$query = "INSERT INTO customers (fname, lname, email, alphanum) VALUES ('$fname', '$lname', '$email', '" . random_string(10) . "')";

This should work! I think that even though double quotes will parse variables, they wont parse functions.

Sign up to request clarification or add additional context in comments.

Comments

2

concatenate the function and your string,

$query = "INSERT INTO customers (fname, lname, email, alphanum) VALUES ('$fname', '$lname', '$email', '" . random_string(10) ."')";

As a sidenote, the query is vulnerable with SQL Injection if the values of the variable came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

Comments

0

make two statements of it. In the first statement you call your function and assign the value to a variable and then in your INSERT... statement you use the variable

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.