我有一个表单将用户输入提交到以下php脚本(我已经排除了定义mysql信息的行):
if (isset($_POST['ttname'])); {
$dbc = @mysql_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME) OR die('No DB connection');
$ttarray = array(1=> $_POST['mon1'], $_POST['mon2'], $_POST['mon3'], $_POST['mon4'], $_POST['mon5'], $_POST['tue1'], $_POST['tue2'], $_POST['tue3'], $_POST['tue4'],
$_POST['tue5'], $_POST['wed1'], $_POST['wed2'], $_POST['wed3'], $_POST['wed4'], $_POST['wed5'], $_POST['thu1'], $_POST['thu2'], $_POST['thu3'], $_POST['thu4'],
$_POST['thu5'], $_POST['fri1'], $_POST['fri2'], $_POST['fri3'], $_POST['fri4'], $_POST['fri5']);
$name = $_POST['ttname'];
$tt = implode(',', $ttarray);
$query = "INSERT INTO Timetable ('NAME','TIMETABLE')
VALUES ($name,$tt)";
$result = mysql_query($query,$dbc) or die('Query Failed');
}
但是,每当我尝试向表单提交数据时,查询都无法执行。
我会很高兴能帮助向我解释为什么会这样。
答案 0 :(得分:1)
至少是这样的:
$tt = mysql_real_escape_string(implode(',', $ttarray));
$query = "INSERT INTO Timetable ('NAME','TIMETABLE') VALUES ('$name','$tt')";
1)$tt
根本没有转义
2)您已经厌倦了插入比可用字段更多的值。通过将$tt
更改为'$tt'
,您可以使字段数相同。
答案 1 :(得分:1)
你将4个参数传递给mysql_connect,AFAIK数据库必须不才能成为其中之一。
resource mysql_connect ([ string $server = ini_get("mysql.default_host") [, string $username = ini_get("mysql.default_user") [, string $password = ini_get("mysql.default_password") [, bool $new_link = false [, int $client_flags = 0 ]]]]] )
非常简短地重写你的代码(非常详细):
if (isset($_POST['ttname']));
{
$dbc = mysql_connect(DB_HOST, DB_USER, DB_PASS) OR die('No DB connection');
mysql_select_db(DB_NAME);
$ttarray = array($_POST['mon1'], $_POST['mon2'], $_POST['mon3'], $_POST['mon4'], $_POST['mon5'], $_POST['tue1'], $_POST['tue2'], $_POST['tue3'], $_POST['tue4'],
$_POST['tue5'], $_POST['wed1'], $_POST['wed2'], $_POST['wed3'], $_POST['wed4'], $_POST['wed5'], $_POST['thu1'], $_POST['thu2'], $_POST['thu3'], $_POST['thu4'],
$_POST['thu5'], $_POST['fri1'], $_POST['fri2'], $_POST['fri3'], $_POST['fri4'], $_POST['fri5']);
$sanitized = array();
foreach($ttarray as $value)
{
$sanitized[] = mysql_real_escape_string($value);
}
$name = mysql_real_escape_string($_POST['ttname']);
$tt = implode(',', $sanitized);
$query = "INSERT INTO Timetable ('name','timetable') VALUES ('".$name."', '".$tt."')";
$result = mysql_query($query, $dbc) or die('Query Failed');
}
但我强烈建议您将来使用PDO和预备语句来防止类似的高缺陷查询。 mysql_real_escape_string是一个很棒的函数,但它不是100%准确,并且不会使您的查询注入防范。