我创建了一个表单,要求用户在第一个文本字段插入一个名称,并在第二个文本字段上写一些内容(一些信息)。这是我的表单代码:
echo "<form method='post' action='insert.php?selected=$openFolder&id=$student'>
Information name:</br> <input name='infoName' type='text' /><br />
Information:<br />
<textarea name='text' rows='15' cols='60'>
</textarea><br />
<input type='submit' name='submit' value='Submit Information'/>
</form>";
到目前为止还不错。
现在,当表格提交时,我需要创建一个文件:
Filename-->用户在"infoName"文本字段中插入的名称
然后将"text"文本字段的内容插入到该文件中,并将整个文件存储到我的数据库中。
这是我的代码:
if (isset($_POST['submit']))
{
//Make sure that a file name is given by the user
if (!$_POST['infoName'])
{
echo "<center><font color='red'>You must complete the Information name field</font></center>";
}
else
{
$informationName = $_POST['infoName'];
$informationContent = $_POST['text'];
$newFile = fopen($informationName,"w");
$content = fwrite($newFile,$informationContent . "'n");
$content = addslashes($content);
fclose($newFile);
$theSize = filesize($informationName);
if(!get_magic_quotes_gpc())
{
$informationName = addslashes($informationName);
}
$query = "INSERT INTO $openFolder (studentID, name, size, type, content, insertedBy ) ".
"VALUES ('$student','$informationName', '$theSize', 'txt', '$content', '$username')";
mysql_query($query) or die('Error, query failed');
}
}
我的问题:
1) 文件是正确创建的,存储在我的数据库中,但其中没有正确的内容。由于某些原因,我没有将文本正确插入文件。。。
2) 除了存储在数据库中的文件外,我的目录中还会创建一个文件,我不希望发生这种情况。
请帮帮我。请随意对我的代码进行任何更改!请告诉我我做错了什么!
我发现原因是语句$content = addslashes($content);
。fwrite返回写入的字节数,而不是数据本身。正确的语句应该是$informationContent = addslashes($informationContent);
,并且应该在您的if(!get_magic_quotes_gpc())
条件内。还可以根据建议更改查询并替换变量。
还要确保检查fwrite的返回值。如果没有写入任何内容(===FALSE),请不要继续操作并报告错误。许多错误更难调试(比如本例),这只是因为我们经常编写假设编程。:)