将数组插入 mysql (userCake)
insert array into mysql (userCake)
我正在用 userCake 源代码建立一个网站。此时此刻,我有一个数组要插入到我的 MySQL 数据库中。
我从表单中获取数组的数据。这是构建数组的代码:
$pauzes = array();
foreach($users as $usr)
{
$pauzes = array_merge($pauzes, array(
$usr['username'] => $_POST[$usr['username']]));
}
当我在这段代码之后调用 print_r($pauzes) 时,可能的输出可能是:
Array ( [jules] => 12.30-13.00 [marc] => 12.30-13.00 [nick] =>
13.30-14.00 [paulo] => --- [kevin] => --- [rick] => --- [sanam] => --- [yvette] => --- [bas] => --- [bruce] => --- )
('---'表示没有选择时间)
userCake 的工作方式我将不得不使用 bind_param,但我无法发送数组 (???)
我找到了一些代码如何从数组中获取数据,所以输出应该类似于 username-time
这是将数据写入数据库的函数:
function add_pauze($datum, $pauzes)
{
GLOBAL $mysqli, $db_table_prefix;
// array $pauzes opdelen in aparte stukken zodat deze kan worden opgeslagen in de database
if(is_array($pauzes))
{
$data = array();
foreach($pauzes as $row){
$naam = mysqli_real_escape_string($mysqli,$row['username']);
$tijd = mysqli_real_escape_string($mysqli, $row['tijd'] );
$data[] = "($naam', '$tijd')";
}
}
$stmt = $mysqli->prepare("INSERT INTO " . $db_table_prefix . "pauzes
(
datum,
gegevens
)
VALUES
" . implode(',', $data) ."
");
$stmt->bind_param("ss", $datum, $naam, $tijd);
$result = $stmt->execute();
$stmt->close();
return($result);
}
当我现在尝试插入数据时,我收到了几个关于非法字符串偏移的警告。我相信这是因为 $naam ($row['username']) 和 $tijd ($row['tijd']) 没有在数组中定义?
我尝试将构建数组的代码更改为如下内容:
$pauzes = array();
foreach($users as $usr)
{
$pauzes = array_merge($pauzes, array(
"username" => $usr['username'] , "tijd" => $_POST[$usr['username']]));
}
但是我的数组不再正确了:
Array ( [username] => bruce [tijd] => --- )
所以现在我想知道如何将我的数组(右边的一个在这个 post 之上)插入我的数据库。
提前致谢!
--- 更新信息 ---
我更改了构建数组的代码:
$pauzes = array("user" => array(), "pauze" => array());
foreach($users as $usr)
{
array_push($pauzes['user'], $usr['username']);
array_push($pauzes['pauze'], $_POST[$usr['id']]);
}
当我执行 print_r($pauzes) 时,输出是:
Array ( [user] => Array ( [0] => jules [1] => marc [2] => nick [3] =>
paulo [4] => kevin [5] => rick [6] => sanam [7] => yvette [8] => bas
[9] => bruce ) [pauze] => Array ( [0] => 13.30-14.00 [1] => --- [2] =>
--- [3] => 13.00-13.30 [4] => --- [5] => 12.00-12.30 [6] => --- [7] => --- [8] => --- [9] => --- ) )
函数 add_pauze 已更新,如下所示:
function add_pauze($datum, $pauzes)
{
GLOBAL $mysqli, $db_table_prefix;
// array $pauzes opdelen in aparte stukken zodat deze kan worden opgeslagen in de database
if(is_array($pauzes))
{
$data = array();
foreach($pauzes as $row){
$naam = $row['user'];
$tijd = $row['pauze'];
$data[] = "('$naam', '$tijd')";
}
}
$stmt = $mysqli->prepare("INSERT INTO " . $db_table_prefix . "pauzes
(
datum,
naam,
tijd
)
VALUES
" . implode(',', $data) ."
");
$stmt->bind_param("ss", $datum, $naam, $tijd);
$result = $stmt->execute();
$stmt->close();
return($result);
}
当我在这个函数中回显 sql 语句时,输出是:
INSERT INTO applepauzes ( datum, naam, tijd ) VALUES ('', ''),('', '')
这是因为 user 和 pauze 索引未识别。
我在数据库中的 table applepauzes 列是:
- id
- 数据
- 纳姆
- tijd
in naam 需要存储用户名。
tijd 休息时间(暂停)需要存储。
如评论中所述,当我执行 print_r($datum) 时,输出为:
2015-02-21 (current date when writing)
我解决了我的问题。
我将构建数组的代码更改为:
$pauze_users = array("users" => array());
$pauze_tijd = array("tijd" => array());
foreach($users as $usr)
{
array_push($pauze_users, $usr['username']);
array_push($pauze_tijd, $_POST[$usr['id']]);
}
之后,我确保数据是正确的,并使用以下代码将其放入 SQL 语句中:
$count_users = count($pauze_users);
$sql;
for($i = 0; $i < $count_users; $i++)
{
$sql .= "(" . $datum . ", " . $pauze_users[$i] . ", " . $pauze_tijd[$i] . ") ";
}
使用这段代码,我将得到如下输出:
(2015-02-22, jules, 11.30-12.00) (2015-02-22, marc, 12.30-13.00)
(2015-02-22, nick, ---) (2015-02-22, paulo, 12.00-12.30) (2015-02-22,
kevin, ---) (2015-02-22, rick, ---) (2015-02-22, sanam, ---)
(2015-02-22, yvette, ---) (2015-02-22, bas, ---) (2015-02-22, bruce,
---)
(我知道我需要在数据之间放置 << , >> 以使其可以接受 SQL
感谢您帮助我解决了问题!
好的,首先您使用的是准备好的语句,但错误地绑定了您的值。你给 mysqli::prepare
的 sql 应该是这样的:
INSERT INTO applepauzes (datum, naam, tijd) VALUES (?,?,?)
对每个用户重复 (?,?,?)
。然后使用 mysqli::bind_param
将数据绑定到这些值。不幸的是 mysqli::bind_param
让你一次绑定它们并接受可变数量的参数 - 每个要绑定的参数一个,而且它们必须通过引用,这使得它更加烦人。
因此,让我们获取您的数据...为了 运行 SQL 语句,我们最终需要的是一个如下所示的数组:
Array(
0 => '2015-02-21',
1 => 'juels',
2 => '12.30-13.00',
3 => '2015-02-21',
4 => 'marc',
5 => '12.30-1:00'
// repeat for each user in the same order
)
然而,为了正确地制作查询,我们需要组织如下内容:
Array (
0 => array(
0 => '2015-02-21',
1 => 'juels',
2 => '12.30-13.00'
),
1 => array(
3 => '2015-02-21',
4 => 'marc',
5 => '12.30-1:00'
),
// repeat for every user record
)
我假设 $_POST
看起来像:
Array(
'juels' => '12.30-13.00',
'marc' => '12.30-13.00',
// etc
)
所以我们需要做的第一件事就是妥善组织:
$pauzes = array();
foreach ($users as $u) {
$username = $u['username'];
// if a user has an entry in the Form then add it to
// $pauzes array for insert into the DB
if (isset($_POST[$username]) {
// even though we want numeric keys eventually we
// we will use the field names here so that its not ambiguous
// later and we can easily reroder them
$pauzes[] = array(
'naam' => $username,
'tijd' => $_POST[$username]
)
}
}
// call out function
add_pauzes(date('Y-m-d'), $pauzes);
所以现在我们进入了问题的核心...... mysqli
的实际插入:
// add an array typehint so that the function
// only takes an array
function add_pauze($datum, array $pauzes)
{
GLOBAL $mysqli, $db_table_prefix;
// first we need to prepare our base array structure
$records = array();
$params = array();
foreach ($pauzes as $pauze) {
$prefix = $pauze['username'];
// give the items unique keys so we can reference them
// in the flat array $params
$records[$prefix] = array(
$prefix . 'datum' => $datum,
$prefix . 'naam' => $pauze['username'],
$prefix . 'tijd' => $pauze['tijd']
);
$params = array_merge($params, $records[$prefix]);
}
print_r($params);
// get our total number of records for insertion
// eg. each array in $records represents a set of values
// for a db record in the table
$recordCount = count($records);
// create placeholders (?,?,?), one for each $record element
$placeholders = array_fill(0, $recordCount, '(?,?,?)');
// create the SQL string for our insert using
// sprintf will substitute our the %s for the other arguments
// we give it...
$sql = sprintf(
'INSERT INTO %spauzes (datum, naam, tijd) VALUES %s',
$db_table_prefix,
implode(',', $placeholders)
);
// prepare out statmement
$stmt = $mysqli->prepare($sql);
// we have to use references to bind the params
// and to make it easy we want to do so with call_user_func_array
// so setablish an array of arguemnts the first being th param
// type and then so loop over $params and assign the values to
// $args by reference
$args = array(str_repeat('s', count($params)));
foreach ($params as $k => &$v) {
$args[$k] = &$v;
}
// bind all of our params using a callable and an array
// of arguments to be passed into that callable
call_user_func_array(array($stmt, 'bind_param'), $args);
$result = $stmt->execute();
$stmt->close();
return $result;
}
如果您只是想将一个数组(或任何任意 PHP 结构)插入到 MySQL table 中并能够将其取回,请考虑以下事项。注意:您将无法通过 SQL 语句轻松检查任何数组元素。
将此添加到您的 table:
json TEXT NOT NULL COMMENT 'opaque array of stuff'
使用 json_encode($array)
将数组转换为字符串,然后将该字符串插入 json
列。
将 json
列选择到 $json
后,执行此操作以取回数组:
$array = json_decode($json, true);
我正在用 userCake 源代码建立一个网站。此时此刻,我有一个数组要插入到我的 MySQL 数据库中。
我从表单中获取数组的数据。这是构建数组的代码:
$pauzes = array();
foreach($users as $usr)
{
$pauzes = array_merge($pauzes, array(
$usr['username'] => $_POST[$usr['username']]));
}
当我在这段代码之后调用 print_r($pauzes) 时,可能的输出可能是:
Array ( [jules] => 12.30-13.00 [marc] => 12.30-13.00 [nick] => 13.30-14.00 [paulo] => --- [kevin] => --- [rick] => --- [sanam] => --- [yvette] => --- [bas] => --- [bruce] => --- )
('---'表示没有选择时间)
userCake 的工作方式我将不得不使用 bind_param,但我无法发送数组 (???) 我找到了一些代码如何从数组中获取数据,所以输出应该类似于 username-time
这是将数据写入数据库的函数:
function add_pauze($datum, $pauzes)
{
GLOBAL $mysqli, $db_table_prefix;
// array $pauzes opdelen in aparte stukken zodat deze kan worden opgeslagen in de database
if(is_array($pauzes))
{
$data = array();
foreach($pauzes as $row){
$naam = mysqli_real_escape_string($mysqli,$row['username']);
$tijd = mysqli_real_escape_string($mysqli, $row['tijd'] );
$data[] = "($naam', '$tijd')";
}
}
$stmt = $mysqli->prepare("INSERT INTO " . $db_table_prefix . "pauzes
(
datum,
gegevens
)
VALUES
" . implode(',', $data) ."
");
$stmt->bind_param("ss", $datum, $naam, $tijd);
$result = $stmt->execute();
$stmt->close();
return($result);
}
当我现在尝试插入数据时,我收到了几个关于非法字符串偏移的警告。我相信这是因为 $naam ($row['username']) 和 $tijd ($row['tijd']) 没有在数组中定义?
我尝试将构建数组的代码更改为如下内容:
$pauzes = array();
foreach($users as $usr)
{
$pauzes = array_merge($pauzes, array(
"username" => $usr['username'] , "tijd" => $_POST[$usr['username']]));
}
但是我的数组不再正确了:
Array ( [username] => bruce [tijd] => --- )
所以现在我想知道如何将我的数组(右边的一个在这个 post 之上)插入我的数据库。
提前致谢!
--- 更新信息 ---
我更改了构建数组的代码:
$pauzes = array("user" => array(), "pauze" => array());
foreach($users as $usr)
{
array_push($pauzes['user'], $usr['username']);
array_push($pauzes['pauze'], $_POST[$usr['id']]);
}
当我执行 print_r($pauzes) 时,输出是:
Array ( [user] => Array ( [0] => jules [1] => marc [2] => nick [3] => paulo [4] => kevin [5] => rick [6] => sanam [7] => yvette [8] => bas [9] => bruce ) [pauze] => Array ( [0] => 13.30-14.00 [1] => --- [2] => --- [3] => 13.00-13.30 [4] => --- [5] => 12.00-12.30 [6] => --- [7] => --- [8] => --- [9] => --- ) )
函数 add_pauze 已更新,如下所示:
function add_pauze($datum, $pauzes)
{
GLOBAL $mysqli, $db_table_prefix;
// array $pauzes opdelen in aparte stukken zodat deze kan worden opgeslagen in de database
if(is_array($pauzes))
{
$data = array();
foreach($pauzes as $row){
$naam = $row['user'];
$tijd = $row['pauze'];
$data[] = "('$naam', '$tijd')";
}
}
$stmt = $mysqli->prepare("INSERT INTO " . $db_table_prefix . "pauzes
(
datum,
naam,
tijd
)
VALUES
" . implode(',', $data) ."
");
$stmt->bind_param("ss", $datum, $naam, $tijd);
$result = $stmt->execute();
$stmt->close();
return($result);
}
当我在这个函数中回显 sql 语句时,输出是:
INSERT INTO applepauzes ( datum, naam, tijd ) VALUES ('', ''),('', '')
这是因为 user 和 pauze 索引未识别。
我在数据库中的 table applepauzes 列是:
- id
- 数据
- 纳姆
- tijd
in naam 需要存储用户名。 tijd 休息时间(暂停)需要存储。
如评论中所述,当我执行 print_r($datum) 时,输出为:
2015-02-21 (current date when writing)
我解决了我的问题。
我将构建数组的代码更改为:
$pauze_users = array("users" => array());
$pauze_tijd = array("tijd" => array());
foreach($users as $usr)
{
array_push($pauze_users, $usr['username']);
array_push($pauze_tijd, $_POST[$usr['id']]);
}
之后,我确保数据是正确的,并使用以下代码将其放入 SQL 语句中:
$count_users = count($pauze_users);
$sql;
for($i = 0; $i < $count_users; $i++)
{
$sql .= "(" . $datum . ", " . $pauze_users[$i] . ", " . $pauze_tijd[$i] . ") ";
}
使用这段代码,我将得到如下输出:
(2015-02-22, jules, 11.30-12.00) (2015-02-22, marc, 12.30-13.00) (2015-02-22, nick, ---) (2015-02-22, paulo, 12.00-12.30) (2015-02-22, kevin, ---) (2015-02-22, rick, ---) (2015-02-22, sanam, ---) (2015-02-22, yvette, ---) (2015-02-22, bas, ---) (2015-02-22, bruce, ---)
(我知道我需要在数据之间放置 << , >> 以使其可以接受 SQL
感谢您帮助我解决了问题!
好的,首先您使用的是准备好的语句,但错误地绑定了您的值。你给 mysqli::prepare
的 sql 应该是这样的:
INSERT INTO applepauzes (datum, naam, tijd) VALUES (?,?,?)
对每个用户重复 (?,?,?)
。然后使用 mysqli::bind_param
将数据绑定到这些值。不幸的是 mysqli::bind_param
让你一次绑定它们并接受可变数量的参数 - 每个要绑定的参数一个,而且它们必须通过引用,这使得它更加烦人。
因此,让我们获取您的数据...为了 运行 SQL 语句,我们最终需要的是一个如下所示的数组:
Array(
0 => '2015-02-21',
1 => 'juels',
2 => '12.30-13.00',
3 => '2015-02-21',
4 => 'marc',
5 => '12.30-1:00'
// repeat for each user in the same order
)
然而,为了正确地制作查询,我们需要组织如下内容:
Array (
0 => array(
0 => '2015-02-21',
1 => 'juels',
2 => '12.30-13.00'
),
1 => array(
3 => '2015-02-21',
4 => 'marc',
5 => '12.30-1:00'
),
// repeat for every user record
)
我假设 $_POST
看起来像:
Array(
'juels' => '12.30-13.00',
'marc' => '12.30-13.00',
// etc
)
所以我们需要做的第一件事就是妥善组织:
$pauzes = array();
foreach ($users as $u) {
$username = $u['username'];
// if a user has an entry in the Form then add it to
// $pauzes array for insert into the DB
if (isset($_POST[$username]) {
// even though we want numeric keys eventually we
// we will use the field names here so that its not ambiguous
// later and we can easily reroder them
$pauzes[] = array(
'naam' => $username,
'tijd' => $_POST[$username]
)
}
}
// call out function
add_pauzes(date('Y-m-d'), $pauzes);
所以现在我们进入了问题的核心...... mysqli
的实际插入:
// add an array typehint so that the function
// only takes an array
function add_pauze($datum, array $pauzes)
{
GLOBAL $mysqli, $db_table_prefix;
// first we need to prepare our base array structure
$records = array();
$params = array();
foreach ($pauzes as $pauze) {
$prefix = $pauze['username'];
// give the items unique keys so we can reference them
// in the flat array $params
$records[$prefix] = array(
$prefix . 'datum' => $datum,
$prefix . 'naam' => $pauze['username'],
$prefix . 'tijd' => $pauze['tijd']
);
$params = array_merge($params, $records[$prefix]);
}
print_r($params);
// get our total number of records for insertion
// eg. each array in $records represents a set of values
// for a db record in the table
$recordCount = count($records);
// create placeholders (?,?,?), one for each $record element
$placeholders = array_fill(0, $recordCount, '(?,?,?)');
// create the SQL string for our insert using
// sprintf will substitute our the %s for the other arguments
// we give it...
$sql = sprintf(
'INSERT INTO %spauzes (datum, naam, tijd) VALUES %s',
$db_table_prefix,
implode(',', $placeholders)
);
// prepare out statmement
$stmt = $mysqli->prepare($sql);
// we have to use references to bind the params
// and to make it easy we want to do so with call_user_func_array
// so setablish an array of arguemnts the first being th param
// type and then so loop over $params and assign the values to
// $args by reference
$args = array(str_repeat('s', count($params)));
foreach ($params as $k => &$v) {
$args[$k] = &$v;
}
// bind all of our params using a callable and an array
// of arguments to be passed into that callable
call_user_func_array(array($stmt, 'bind_param'), $args);
$result = $stmt->execute();
$stmt->close();
return $result;
}
如果您只是想将一个数组(或任何任意 PHP 结构)插入到 MySQL table 中并能够将其取回,请考虑以下事项。注意:您将无法通过 SQL 语句轻松检查任何数组元素。
将此添加到您的 table:
json TEXT NOT NULL COMMENT 'opaque array of stuff'
使用 json_encode($array)
将数组转换为字符串,然后将该字符串插入 json
列。
将 json
列选择到 $json
后,执行此操作以取回数组:
$array = json_decode($json, true);