我想下面的$ _POST陣列插入到MySQL表一個MySQL表:
Array (
[name] => asd
[number] => 2
[date_of_birth] => 2008-06-17
[address] => asd
[email] => [email protected]
[gender] => male
[salary] => 22212
[date_of_join] => 2015-04-08
[degree_of_learning] => bechelore degree
)
我嘗試使用此代碼,我沒有得到任何錯誤,但陣列未插入我的表:
<?php
include('db.php');
$columns = implode(", ",array_keys($_POST));
$escaped_values = array_map('mysql_real_escape_string', array_values($_POST));
$values = implode("', '", $escaped_values);
$sql = "INSERT INTO `trainers`($columns) VALUES ('$values');";
echo $sql;
mysql_query($sql);
?>
這裏是echo $sql
輸出:
INSERT INTO `trainers`(name, number, date_of_birth, address, email,
gender, salary, date_of_join, degree_of_learning) VALUES ('asd', '2',
'2008-06-17', 'asd', '[email protected]', 'male', '22212', '2015-04-08',
'bechelore degree ');
我試着直接插入到服務器上,它工作,但它不能在我的PHP代碼中工作。
我的表定義是:
CREATE TABLE IF NOT EXISTS trainers (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
number varchar(255) NOT NULL,
date_of_birth date NOT NULL,
address varchar(255) NOT NULL,
email varchar(255) NOT NULL,
gender varchar(255) NOT NULL,
salary int(11) NOT NULL,
date_of_join date NOT NULL,
degree_of_learning varchar(255) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2;
將所有POST變量和盲目地插入到數據庫中可能被認爲是危險的。您是否嘗試過使用準備好的語句? – Jens
我沒有得到任何錯誤, 但它不插入我的表 –
陣列([名稱] => ASD [數字] => 2 DATE_OF_BIRTH] => 2008-06-17 [地址] => ASD [郵件] => [email protected] [gender] =>男性[salary] => 22212 [date_of_join] => 2015-04-08 [degree_of_learning] => bechelore度) 這是我的$ _POST數組 –