2 回答

TA貢獻1802條經驗 獲得超5個贊
你需要從某個地方得到那個故事。有幾種方法可以到達那里。
如果要從文本文件加載它:
// Here we sanitize the story ID to avoid getting hacked:
$story_id = preg_replace('#[^a-zA-Z0-9_ -]#', '', $_POST['story']);
// Then we load the text file containing the story:
$path = 'stories/' . $story_id . '.txt';
$story_text = is_file($path) ? file_get_contents($path) : 'No such story!';
如果你想從數據庫加載它:
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("SELECT * FROM stories WHERE story_id = ? LIMIT 1");
$stmt->bind_param("s", $_POST['story']);
$stmt->execute();
$result = $stmt->get_result();
$story = $result->fetch_assoc();
$story_text = !empty($story['story_text']) ? $story['story_text'] : 'No such story!';
stories這假設您有一個名為字段story_id和的表story_text。
你也可以有一個單獨的文件,將你所有的故事分配到變量中(假設你真的只有幾個,加載未使用的故事對性能的影響是最小的):
$stories['Seaside'] = <<<EOL
Here is the seaside story.
EOL;
$stories['Mountain'] = <<<EOL
Here is the mountain story.
EOL;
然后在你的故事文件中,你“加載”它:
$story_text = !empty($stories[$_POST['story']) ? $stories[$_POST['story']] : 'No such story!';
然后(使用上述任何選項),只需:
<?php echo $story_text; ?>
在上述選項中,如果您正在尋找簡單且易于維護的東西,我會選擇文本文件加載來獲取您的故事文本。祝你講故事好運。:)
假設您想在故事中使用表單變量。您需要使用標記,例如{{ place }},并在輸出故事文本之前替換它們:
$story_text = str_replace('{{ name }}', $_POST['name'], $story_text);
$story_text = str_replace('{{ place }}', $_POST['place'], $story_text);
這會將“曾幾何時有 {{ name }} 探索 {{ place }}...”變成“曾幾何時有 Светослав 探索堪察加半島...”等。

TA貢獻1854條經驗 獲得超8個贊
...instead of <?php echo $_POST["story"]; ?> I want to print 200+ words story relating to what User has chosen.
使用條件if()或switch語句查看您的 $_POST['story'] 是否已設置并等于您的故事選項之一。
//--> ON story_get.php
//--> (Provided the $_POST variable in fact has the values assigned to the global array)
//--> use var_dump($_POST) on story_get.php to check if the global $_POST array has
//--> key/value pairs coming from your index.php page
// set variables that have your story information.
$seaside = //--> Your story about the sea side
$mountain = //--> Your story about the mountain
$output = null; //--> Empty variable to hold display info from conditional
//--> Now to see if the form element that selects story is set using isset
if(isset($_POST['story']){
//--> Now that we know the input in the form that holds the value for story isset
//--> Check to see if it is set and then declare a variable and assign it to that variable
$story = $_POST['story'];
if($story === 'sea'){
$output = $seaside;
}elseif($story === 'mount'){
$output = $mountain;
}else{
$output = //--> Set a default setting that displays output here if neither story is selected.
}
}
$output在 html 文檔中回顯您希望顯示故事內容的變量
<div>
<?=$output?>
<!--// OR //-->
<?php echo $output; ?>
</div>
- 2 回答
- 0 關注
- 133 瀏覽
添加回答
舉報