使用 PHP 将数组插入 MySQL 数据库 [英] Insert array into MySQL database with PHP

查看:46
本文介绍了使用 PHP 将数组插入 MySQL 数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将以下数组存储在我的数据库中...

I have the following array I want to store in my database...

$insData = array(
    'uid' => $fbme['id'],
    'first_name' => $fbme['first_name'],
    'last_name' => $fbme['last_name'],
    'email' => isset($fbme['email']) ? $fbme['email'] : '',
    'link' => $fbme['link'],
    'affiliations' => $networks,
    'birthday' => $info[0]['birthday_date'],
    'current_location' => isset($fbme['location']['name']) ? $fbme['location']['name'] : '',
    'education_history' => $education,
    'work' => $workInfo,
    'hometown_location' => isset($fbme['hometown']['name']) ? $fbme['hometown']['name'] : '',
    'interests' => $info[0]['interests'],
    'locale' => $info[0]['locale'],
    'movies' => $movies,
    'music' => $music,
    'political' => $info[0]['political'],
    'relationship_status' => $info[0]['relationship_status'],
    'sex' =>  isset($fbme['gender']) ? $fbme['gender'] : '',
    'tv' => $television,
    'status' => '0',
    'created' => $now,
    'updated' => $now,
);

我试过在谷歌上搜索如何做到这一点,我能找到的只是说明我的数组需要在插入表之前被拆分的信息.这样对吗?很抱歉我的天真,对 php 很陌生.

I've tried searching google on how to do this and all I can find is information stating my array needs to be split, before inserting into the table. Is this correct? Sorry for the naivity, very new to php.

推荐答案

你不能直接向MySQL插入数组,因为MySQL不理解PHP 数据类型. MySQL 只理解 SQL.因此,要将数组插入 MySQL 数据库,您必须将其转换为 SQL 语句.这可以手动完成,也可以由库完成.输出应该是一个 INSERT 语句.

You can not insert an array directly to MySQL as MySQL doesn't understand PHP data types. MySQL only understands SQL. So to insert an array into a MySQL database you have to convert it to a SQL statement. This can be done manually or by a library. The output should be an INSERT statement.

PHP7 更新

自 PHP 5.5 起 mysql_real_escape_string 已被弃用,自 PHP7 起已移除.请参阅:php.net 关于新程序的文档.>

Since PHP 5.5 mysql_real_escape_string has been deprecated and as of PHP7 it has been removed. See: php.net's documentation on the new procedure.


原答案:

这是一个标准的 MySQL 插入语句.

Here is a standard MySQL insert statement.

INSERT INTO TABLE1(COLUMN1, COLUMN2, ....) VALUES (VALUE1, VALUE2..)

如果您有一个名为 fbdata 的表,其中的列显示在数组的键中,您可以使用这个小片段插入.以下是您的数组如何转换为该语句.

If you have a table with name fbdata with the columns which are presented in the keys of your array you can insert with this small snippet. Here is how your array is converted to this statement.

$columns = implode(", ",array_keys($insData));
$escaped_values = array_map('mysql_real_escape_string', array_values($insData));
$values  = implode(", ", $escaped_values);
$sql = "INSERT INTO `fbdata`($columns) VALUES ($values)";

这篇关于使用 PHP 将数组插入 MySQL 数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆