我的PHP代码有问题,我是初学者,我需要一些帮助。我试图创建一个函数,它将使用write在3个变量的文件中写入输入文本,但似乎当我将所有内容都放入函数时它无法正常工作。
这是我的代码:
<!doctype html>
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<form action="test.php" method="post">
<input type="text" name="text">
<input type="text" name="text1">
<input type="text" name="text2">
<input type="submit" name="submit" value="write">
</form>
<?php
$text = $_POST['text'];
$text1 = $_POST['text1'];
$text2 = $_POST['text2'];
function start($text,$text1,$text2)
{
if(isset($_POST['submit']))
{
$text_total = "$text $text1 $text2 \r\n";
$file = fopen("text.txt", "a+");
fwrite($file, $text_total);
fclose($file);
}
}
start();
?>
<body>
</body>
</html>
答案 0 :(得分:3)
将字符串参数传递给函数调用
<?php
$text = $_POST['text'];
$text1 = $_POST['text1'];
$text2 = $_POST['text2'];
function start($text,$text1,$text2)
{
if(isset($_POST['submit']))
{
$text_total = "$text $text1 $text2 \r\n";
$file = fopen("text.txt", "a+");
fwrite($file, $text_total);
fclose($file);
}
}
start($text,$text1,$text2);
?>
答案 1 :(得分:0)
您的函数参数缺失是您的问题。还要检查表单是否已提交。这是为了更好的练习。
<?php
function start($text,$text1,$text2)
{
if(isset($_POST['submit']))
{
$text_total = "$text $text1 $text2 \r\n";
$file = fopen("text.txt", "a+");
fwrite($file, $text_total);
fclose($file);
}
}
if(isset($_POST['submit'])){
unset($_POST['submit']); //This is to make sure it's executed one time only
$text = $_POST['text'];
$text1 = $_POST['text1'];
$text2 = $_POST['text2'];
start($text,$text1,$text2);
}
?>
答案 2 :(得分:-1)
您必须在test.php文件中添加:
<?php
$text = $_POST['text'];
$text1 = $_POST['text1'];
$text2 = $_POST['text2'];
function start($text,$text1,$text2)
{
if(isset($_POST['submit']))
{
$text_total = "$text $text1 $text2 \r\n";
$file = fopen("text.txt", "a+");
fwrite($file, $text_total);
fclose($file);
}
}
start();
你不能和html一起使用