这是我当前的$_POST
输出。
Array
(
[fullname] => John Doe
[email] => john@john.com
[phone] => 123-455-6444
[address] => 23-10 My Address
[zip] => 12345
[fullname_2] => Array
(
[0] => M. Owen
[1] => V. Persie
)
[email_2] => Array
(
[0] => mowen@owen.com
[1] => vpersie@persie.com
)
[phone_2] => Array
(
[0] => 123-455-6555
[1] => 222-111-1111
)
[submit] => Submit
)
我希望上面的数据将存储到我当前的数据库格式,如下所示。
id | fullname | email | phone | address | zip | uid
----------------------------------------------------------------------------------------
1 | John Doe | john@john.com | 123-455-6444 | 23-10 My Address | 12345 | 1
2 | M. Owen | mowen@owen.com | | | | 1
3 | V. Persie | vpersie@persie.com | | | | 1
我越来越模糊如何将数组保存到MySQL。
$query = "INSERT INTO users SET fullname ='" . $fullname . "', email ='" . $email . "', phone='" . $phone . "', address ='" . $address . "', zip='" . $zip . "'";
$db->rq($query);
让我知道线索。
答案 0 :(得分:1)
修改此代码以满足您的需求:
$query = sprintf("INSERT INTO users (FieldName1, FieldName2, ...) VALUES ('%s', '%s', ...)", mysql_real_escape_string($value1), mysql_real_escape_string($value2), ...);
祝你好运!
答案 1 :(得分:1)
首先,我假设最后一列uid
引用了所有数据插入的用户ID,用于标记第一个元素和另外两个元素之间的连接。
其次我对Google的php DB包装器一无所知(或者你能为此提供任何代号)所以我认为它是code.google.com
上托管的众多db包装器项目之一。由于我不知道它是哪一个,你必须看自己等同于php function mysql_insert_id()。
完成您所需要的通用算法:
$_POST['fullname_2']
以收集下次查询的数据示例:
$lastId = $db->functionToGetLastId();
$valuesArray = array();
foreach($_POST['fullname_2'] as $key => $value){
$fullname = sanitizeFunction($value);
$email = sanitizeFunction($_POST['email_2'][$key]);
$phone = sanitizeFunction($_POST['phone_2'][$key]);
$valuesArray[] = "('{$fullname}','{$email}','{$phone}',{$lastId})";
}
$secondQuery = "INSERT INTO users (fullname,email,phone,uid) VALUES " . implode(',',$valuesArray);
$db->rq($secondQuery);
答案 2 :(得分:1)
最好使用PDO和准备好的查询,而不是“按原样”插入查询 像这样的东西
$fullname = $_POST['fullname'];
$phone = $_POST['phone'];
$conn = new PDO(...); //params of connection
$stmt = $conn->prepare('
INSERT INTO users
(fullname, phone)
VALUES
(?, ?)'
);
$stmt->execute(array(
$fullname,
$phone
));