电话簿问题

时间:2014-11-30 18:52:09

标签: php

我想创建一个数字电话簿,我可以在其中添加/删除条目。我可以添加没有问题,但当我尝试删除一个条目(每个无线电盒),总是会话数组的最后一个条目消失...

电话簿:(index.php)

<?php
session_start();
?>
<html>
	<head>
		<title>2PLF</title>
		<style>
			table{
				margin: 0 0 1rem 0;
			}
			table, table tr, table tr td{
				border: 0.1rem solid #444;
			}
			table tr th{
				border: 0.2rem solid #444;
			}
		</style>
	</head>
	<body>
	<form method="post">
		<h1>My phonebook</h1>

		<?php
		if(isset($_POST["add"])){
			header("location:new.php");
		}
		if(isset($_SESSION["new"])){
		
			foreach($_SESSION["new"] as $number => $name){
				$_SESSION["phonebook"][$number] = $name;
			}
			
			//clean up
			unset($_SESSION["new"]);
			
		}
		
		if(isset($_SESSION["phonebook"])){
			?>
			<table>
				<tr>
					<th>Number</th>
					<th>Name</th>
					<th>Select</th>
				</tr>
				<?php
				foreach($_SESSION["phonebook"] as $number => $name){
					echo '<tr>
					<td>'.$number.'</td>
					<td>'.$name.'</td>
					<td><input type="radio" name="radio"></td>
					</tr>';
					
				}
				
				if(isset($_POST["delete"]) && isset($_POST["radio"])){
					
						unset($_SESSION["phonebook"][$number]);
						header("location:index.php");
						
				}else if(isset($_POST["delete"]) && !isset($_POST["radio"])){
						echo "Please check your Input";
				}
				
				?>
			</table>
			<?php
			
		}
		?>
			<input name="add" type="submit" value="Add a new number">
			<input name="delete" type="submit" value="Delete an entry">
		</form>

	</body>
</html>

添加一个条目(new.php)

<?php
session_start();
?>
<html>
	<head>
		<title>2PLF</title>
	</head>
	<body>
	
		<h1>Add an entry</h1>
		
		<?php
			$success = false;
			if(isset($_POST["name"]) && isset($_POST["number"])){
				$success = true;
				$name = $_POST["name"];
				$number = $_POST["number"];
				
				$newEntry = array(
					$number => $name,
				);
				
				//put the array in a session array
				$_SESSION["new"] = $newEntry;
				
			}
		?>
		
		<form method="post">
			<input name="name" type="text" value="" placeholder="Name">
			<input name="number" type="text" value="" placeholder="Phone number">
			<input type="submit" value="Add entry">
		</form>
		
		<?php 
		if($success == true){
			if($name == "" || $number == ""){
				echo "Please enter a valid name and number";
			}else{
				header("location:index.php");
			}
		}
		?>
		
	</body>
</html>

请注意,所有收音机盒必须具有相同的名称。 我知道,index.php中有一些错误的代码,但我找不到......

谢谢!

1 个答案:

答案 0 :(得分:0)

您应该通过广播传递记录的标识。

<input type="radio" name="radio" value="'.$number.'">