我是$_SESSIONS的新手,但需要它在不同的PHP文件之间重用变量.在下面的代码中我想在另一个PHP文件中使用变量$word,但我不确定如何做到这一点.
<?PHP if (isset($_POST["search"])) { //include database connection $word = MysqL_real_escape_string($_POST["search"]); $word = htmlentities($word); $sql = ("SELECT task_id,task_date FROM customer JOIN task ON customer.id = task.customer_id WHERE mobil = $word ORDER BY task_date DESC LIMIT 0,10"); $results = MysqL_query($sql); if (MysqL_num_rows($results)==0) { echo $word," text bla"; }else { echo $word," text bla bla"; while ($row = MysqL_fetch_assoc($results)) { echo '<pre>',print_r($row),'<pre>'; } } }?>
期待您的建议.
—更新会话仍然无法在page2.PHP上运行?—
我不明白为什么$_SESSION不起作用.一个page1.PHP我可以回显($_ SESSION [‘word’])并获得正确的值,但是我得到一个page2.PHP(‘$’.“_ SESSION [‘word’]没有设置,因为你从来没有在文件一“);
我测试了以下所有解决方案,但没有一个在page2.PHP上工作=相同的结果.
<?PHP session_start(); //if we got something through $_POST if (isset($_POST["search"])) { // include database connection $connect = MysqL_connect('localhost','root','NomiS123') or die(MysqL_error()); MysqL_select_db('workcard'); // sanitize user input $word = MysqL_real_escape_string($_POST["search"]); $word = htmlentities($word); // build search query to the database $sql = ("SELECT task_id,10"); // get results $_SESSION['word'] = $word; $results = MysqL_query($sql); if (MysqL_num_rows($results)==0) { $_SESSION['word'] = $word; echo($_SESSION['word']. "<br>"); var_dump($_SESSION); echo "<br>"; echo "link link <br>"; echo "<a href=\"../page2.PHP/\">new card</a> <br>"; echo "<a href=\"//cykelc/\">New Search</a>"; } else { echo $word," bla bla text <br> Create card <br>"; echo "Edit info on: ",$word,"<br>"; echo "<a href=\"//cykelc/\">New Search</a> <br>"; while ($row = MysqL_fetch_assoc($results)) { echo '<pre>','<pre>'; } //$results->free(); } } // MysqL_close($connect); ?>
<?PHP session_start(); if(isset($_SESSION['word'])) { $word = $_SESSION['word']; echo($word); } else { die('$'."_SESSION['word'] isn't set because you had never been at file one"); } ?>
我对此疯狂.
更新 – 已解决
我测试了以下所有建议,但没有一个工作,这是奇怪的,因为我可以设置和回显page1.PHP和page2.PHP上的sesson_id(),但在page2.PHP我有一个不同的sesson_id().我开始研究我的MAMP会话设置,但一切都是正确的设置.解决方案是“简单地”放置session_start();在page2.PHP的最顶部.最重要的是,我甚至在所有事情之前都是<!DOCTYPE html>等解决过的经验教训:-)
首先,你必须通过session_start()启动seeion;直接打开PHP’标签'(<?PHP session_start(); ...?>)
然后,您必须将变量保存到会话中.
你可以使用$_SESSION [‘word’] = $word;以此目的.
在另一个文件中,您还必须使用session_start();在<?PHP'标签'之后的第一个. 然后你可以通过$word = $_SESSION [‘word’];来访问旧变量. 您现在也可以在第二个文件中使用$word.但是你只能在它被设置时使用它(并且你在第一个文件之前的位置). 文件一:
<?PHP session_start(); if (isset($_POST["search"])) { //include database connection $word = MysqL_real_escape_string($_POST["search"]); $word = htmlentities($word); $_SESSION['word'] = $word; $sql = ("SELECT task_id,'<pre>'; } } }?>
文件二:
<?PHP session_start(); if(isset($_SESSION['word'])) { $word = $_SESSION['word']; } else { die('$'."_SESSION['word'] isn't set because you had never been at file one"); } echo $word; ?>
希望这可以帮助 原文链接:https://www.f2er.com/php/133836.html