简体   繁体   English

如何在php中调用函数/方法以将函数返回值插入mysql

[英]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)')"; 我需要中间以$ 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: 我需要将一个随机的字母数字字符串插入到名为“ customers”的表中,但是与其调用函数“ random_string()”而不是将“ random_string(10)”插入到我的表中,这为我的表提供了6个字段:

5   John    Smith   Jogsz@CiniCraft.com random_string(10)   0

How do I fix this? 我该如何解决?

$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. 我认为即使双引号将解析变量,但它们也不会解析函数。

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. 附带说明一下,如果变量的值来自外部,则该查询容易受到SQL Injection攻击。 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. 通过使用PreparedStatements,您可以摆脱在值周围使用单引号的麻烦。

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 在第一个语句中,调用函数并将值分配给变量,然后在INSERT...语句中,使用变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM