为什么这段代码不起作用?
<?php
$filen = "C:/wamp/www/uppgifter/saves/speltva.txt";
$s=fopen($filen,'a+');
$f=fopen($filen,'r');
if(isset($_POST['nyttspel'])) {
$result = "--";
$s=fopen($filen,'w');
fwrite ($s, $result);
fclose($s);
} else {
$f=fopen($filen,'r');
$result = fgets($f);
}
if(isset($_POST['sten'])) {
if ($result[0] == "-")
$result[0] == "a";
else
$result[1] == "a";
}
if(isset($_POST['sax'])) {
if ($result[0] == "-")
$result[0] == "b";
else
$result[1] == "b";
}
if(isset($_POST['pase'])) {
if ($result[0] == "-")
$result[0] == "c";
else
$result[1] == "c";
}
fclose($f);
$s=fopen($filen,'w');
fwrite ($s, $result);
echo $result;
?>
<form method=post action=stensax.php>
<center>
<input type='submit' name=nyttspel value=NYTT SPEL>
<input type='submit' name=sten value=STEN>
<input type='submit' name=sax value=SAX>
<input type='submit' name=pase value=PÅSE>
</center>
我想把它放在&#34; - &#34;在文件中首先作为游戏板。当有人选择&#34; sten&#34; (摇滚)它应该改变第一个&#34; - &#34;进入&#34; a&#34;如果它是空的,否则改变第二个&#34; - &#34;到&#34; a&#34;。当我按下&#34; nyttspel&#34; (新游戏),它用空游戏板填充.txt文件,就像它应该的那样,但是当我按下任何其他按钮时没有任何反应。那是为什么?
答案 0 :(得分:3)
在你的比较中,你应该分配,而不是比较。例如:
错:
if(isset($_POST['sten'])) {
if ($result[0] == "-")
$result[0] == "a"; // comparing
else
$result[1] == "a";
}
右:
if(isset($_POST['sten'])) {
if ($result[0] == "-")
$result[0] = "a"; // assigning
else
$result[1] = "a";
}
答案 1 :(得分:0)
我在您的代码中发现了几个问题:
==
),您应该使用作业(=
)<center>
标记echo
打印数组(只返回Array
)</form>
关闭您的表单虽然使用==
比较在技术上没有任何问题,但使用===
比较会更好。此外,将HTML属性的值放在""
或''
以下代码实现了我提到的所有改进,除了阅读/写作(因为我不确定你到底想要实现的目标):
<?php
$filen = "speltva.txt";
$s=fopen($filen,'a+');
$f=fopen($filen,'r');
if(isset($_POST['nyttspel'])) {
$result = "--";
$s=fopen($filen,'w');
fwrite ($s, $result);
fclose($s);
} else {
$f=fopen($filen,'r');
$result = fgets($f);
}
if(isset($_POST['sten'])) {
if ($result[0] === "-")
$result[0] = "a";
else
$result[1] = "a";
}
if(isset($_POST['sax'])) {
if ($result[0] === "-")
$result[0] = "b";
else
$result[1] = "b";
}
if(isset($_POST['pase'])) {
if ($result[0] === "-")
$result[0] = "c";
else
$result[1] = "c";
}
fclose($f);
$s=fopen($filen,'w');
fwrite ($s, $result);
print_r($result);
?>
<form method="post" action="stensax.php" style="text-align:center">
<input type="submit" name="nyttspel" value="NYTT SPEL">
<input type="submit" name="sten" value="STEN">
<input type="submit" name="sax" value="SAX">
<input type="submit" name="pase" value="PÅSE">
</form>