我有以下功能:
function insert($database, $table, $data_array)
{
# Connect to MySQL server and select database
$mysql_connect = connect_to_database();
mysql_select_db ($database, $mysql_connect);
# Create column and data values for SQL command
foreach ($data_array as $key => $value)
{
$tmp_col[] = $key;
$tmp_dat[] = "'$value'";
}
$columns = join(",", $tmp_col);
$data = join(",", $tmp_dat);
# Create and execute SQL command
$sql = "INSERT INTO ".$table."(".$columns.")VALUES(". $data.");";
$result = mysql_query($sql, $mysql_connect);
# Report SQL error, if one occured, otherwise return result
if(mysql_error($mysql_connect))
{
echo "MySQL Update Error: ".mysql_error($mysql_connect);
$result = "";
}
else
{
return $result;
}
}
php中的值如下:
$content_table = "p_content";
$insert_array['title'] = $title;
$insert_array['content'] = $content;
$insert_array['url'] = $get_source;
$insert_array['video'] = $video;
$insert_array['date'] = $date;
insert(DATABASE, $content_table, $insert_array);
所有这些的结果添加了一行id(key,autoimcrement),url和date。标题,内容和视频都是空白的。如果我回显标题我得到正确的结果,如果我var_dump标题我得到字符串(15)" blablablabla",再次正确。
现在如果我设置$ title =" asdf&#34 ;;它被正确插入。内容和视频也是如此。
表格结构
id int(8)unsigned NO PRI NULL auto_increment
title varchar(1000)YES NULL
内容longtext YES NULL
video varchar(3000)YES NULL
url varchar(300)YES NULL
日期日期YES NULL
答案 0 :(得分:0)
尝试:
function insert($database, $table, $data_array)
{
# Connect to MySQL server and select database
$mysql_connect = connect_to_database();
mysql_select_db($database, $mysql_connect);
$cols = array();
$vals = array();
foreach ($data_array as $key => $value) {
$cols[] = "`" . $key . "`";
if (is_int($value) || is_float($value)) {
$vals[] = $value;
} else {
$vals[] = "'" . mysql_real_escape_string($value) . "'";
}
}
$sql = "INSERT INTO " . $table
. ' (' . implode(', ', $cols) . ') '
. 'VALUES (' . implode(', ', $vals) . ')';
$result = mysql_query($sql, $mysql_connect);
# Report SQL error, if one occured, otherwise return result
if(mysql_error($mysql_connect)) {
echo "MySQL Update Error: " . mysql_error($mysql_connect);
$result = ""; // FIXME should probably return false here
} else {
return $result;
}
}
重要强>
您的代码和上述内容可能容易受到SQL注入攻击。去了解他们。
答案 1 :(得分:0)
尝试在变量中添加引号。 :-)原因是你将MYSQL列类型设置为VARCHAR。插入数据需要用引号括住插入内容。
B.T.W。如果这是新代码,我建议切换到MYSQLI或PDO库。