Matt Andrzejczuk
Matt Andrzejczuk

Reputation: 2066

How to call a function/method in php to insert function return value to mysql

<?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?

Upvotes: 1

Views: 8690

Answers (3)

John Woo
John Woo

Reputation: 263803

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.

Upvotes: 2

agim
agim

Reputation: 1841

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

Upvotes: 0

Pankucins
Pankucins

Reputation: 1720

$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.

Upvotes: 3

Related Questions