调用第3个会话变量后丢失前2个会话变量(php 5)

时间:2015-01-28 16:43:52

标签: php mysql session

这是我的情况(相对较新的php):我有一个页面" zoek_form.php"您可以在表单中输入2个搜索值(naam和categoriesie)。提交后,页面" zoek.php"加载并执行搜索(mysql 5.6)。要执行搜索,可从2个会话变量中获取2个值。到目前为止一切顺利,搜索工作并检索行。 但是现在我希望用户能够根据下拉列表在zoek.php中创建一个序列(通过ORDER BY)。所选值将存储在第3个会话变量中。但现在问题是:在选择序列并提交表单时,前2个会话值将丢失。我很疑惑为什么。会话变量的本质是只存储值并能够反复使用它们吗? (直到被覆盖或被杀)。 我当然使用session_start();在PHP脚本的开头(否则它根本不会工作;-)。有什么想法吗?

这里是zoek_form.php:

<html>
<head>
<title>Zoeken</title>
</head>
<body>

<?php session_start(); ?>
<form name="form1" method="POST" action="zoek.php">
<table border="0">
<tr><td>Naam product:</td>
<td><input type="text" size="50" name="form_naam"></td></tr>
<tr><td>Categorie:</td>
<td><input type="text" size="50" name="form_cat"></td></tr>
<tr><td></td>
<td align = "right"><input type="submit" name="B1" value="Zoeken">
</td></tr>
</table>
</form>

</body>
</html>

这里的zoek.php:

<html>
<head>
<title>Zoeken</title>
</head>
<body>

<form name="form1" method="POST" action="">
<table border="0">
<tr><td>Sorteer op:</td>
<td><select name="form_sort">
  <option value="Naam">Naam</option>
  <option value="Categorie">Categorie</option>  
</select></td>
<td><input type="submit" name="B1" value="Sorteer"></td></tr>
</table>
</form>

<?php

session_start();
require_once 'test_connect.php';
$_SESSION['form_naam'] = $_POST['form_naam'];
$_SESSION['form_cat'] = $_POST['form_cat'];
$_SESSION['form_sort'] = $_POST['form_sort'];
// The 3 lines below were used to check whether session vars were set
// echo  $_SESSION['form_naam'];
// echo  $_SESSION['form_cat'];
// echo  $_SESSION['form_sort'];

function sorteren() {
global $sorteer;
$sorteer = $_SESSION['form_sort'];
  if ($sorteer == "Naam") {
  $sorteer = "ORDER BY naam";
  }
  else {
  $sorteer = "ORDER BY categorie";
  }
 }

// Put values from zoek_form.php in vars.
$naam = $_SESSION['form_naam'];
$cat = $_SESSION['form_cat'];

// Check if user has set a sequence. If yes: call function sorteren(),
// if no: leave var $sorteer empty.
if (isset($_SESSION['form_sort'])) {
sorteren();
}
else {
$sorteer = "";
}

// Get rows from table product
$sql = "SELECT * FROM product WHERE naam LIKE '$naam%' OR categorie
LIKE '$cat%' $sorteer";
$result = $conn -> query($sql);

if ($result->num_rows > 0) {
// here code to retrieve rows etc.    
}

// Give result free
$result -> free();

// Close connection
$conn -> close();

?>

</body>
</html>

1 个答案:

答案 0 :(得分:2)

你在zoek.php中的表单不包含form_naamform_cat所以当你运行时

$_SESSION['form_naam'] = $_POST['form_naam'];
$_SESSION['form_cat'] = $_POST['form_cat'];

它将这些值设置为null。如果您想保留这些值,可以尝试在隐藏输入字段

的表单中再次传回它们
<input type="hidden" name="form_naam" value="<?= $_SESSION['form_naam'] ?>">
<input type="hidden" name="form_cat" value="<?= $_SESSION['form_cat'] ?>">

防止覆盖会话值的另一种方法是仅在设置$_POST值时更改它们

if(isset($_POST['form_naam']) && isset($_POST['form_cat'])) {
  $_SESSION['form_naam'] = $_POST['form_naam'];
  $_SESSION['form_cat'] = $_POST['form_cat'];
}