如何将PHP数组中的值插入MySQL表? [英] How to insert values in a PHP array to a MySQL table?
问题描述
我正在创建一个注册表,其中包含姓名,电子邮件和电话号码字段.为了检查用户输入的有效性,我有一个函数validate_input()
,该函数返回一个数组$arr
,该数组包含用户输入的输入(如果用户输入有效).然后,将$arr
传递到一个单独的函数,该函数将arr
中的值插入到包含name
,email
和phone
字段的MySQL表user
中.
I am creating a registration form, with fields for Name, Email and Phone Number. To check the validity of user input, I have a function validate_input()
that returns an array $arr
containing input entered by the user (if user input is valid). $arr
is then passed to a separate function that inserts the values in arr
into a MySQL table user
containing fields for name
, email
and phone
.
我最初尝试了以下方法:
I initially tried the following:
$insert_query = "INSERT INTO user (name, email, phone)
VALUES ('$arr['name']',
'$arr['email']',
'$arr['phone']')";
$run_insert_query = mysqli_query($con, $insert_query);
但这没用.一些阅读显示这是将数组值插入数据库的错误方法.因此,我随后尝试了以下方法(基于此处接受的答案) :
But this didn't work. Some reading revealed that this is the wrong way to insert array values into the database. So I then tried the following (based on the accepted answer here):
$escaped_values = array_map('mysql_real_escape_string', array_values($arr));
$arr_values = implode(",", $escaped_values);
$insert_query = "INSERT INTO user (name, email, phone) VALUES ($arr_values)";
$run_query = mysqli_query($con, $insert_query);
但这也不起作用.关于如何进行这项工作的任何想法?
But this didn't work either. Any ideas on how to make this work?
推荐答案
您只是忘记了正确设置引号. 这是正确的语法:
You just forgot to set the quotes right. Here's the correct syntax:
$insert_query = "INSERT INTO user (name, email, phone)
VALUES ('".$arr['name']."',
'".$arr['email']."',
'".$arr['phone']."')";
这篇关于如何将PHP数组中的值插入MySQL表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!