如果未添加用户,如何从聊天中添加用户

时间:2018-12-23 19:48:07

标签: php forms session pdo

我有网络聊天。用户可以添加自己的聊天室。我想按一下按钮,如果聊天不是他的,他可以加入,但是有问题。我有与加入聊天的用户一起使用的表,因此,如果用户加入了一些聊天,则在“已加入”表中插入用户ID和已加入的聊天ID。

如果用户再按一次“加入”按钮,那么他将从此聊天中删除。但是在我的代码中,用户按下加入即可加入聊天,但是当他再按下一次加入时,并不会从聊天中删除他的需要,所以他会再插入一次此聊天,但是当他单击第三次时,他会从中删除聊天

<?php
session_start();

		$sql="select * from joined order by id desc";
		$data=$db->prepare($sql);
		$data->execute();
		$joined=$data->fetchAll();
?>



<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width">
	<title>chat-room</title>
</head>
<body>


		 
   
	
<?php
if ($rows['username'] != $_SESSION["username"]) {
	?>
	
	<?php
}
?>

<form method="post">
<div class="none" style="display:none">

			<?php
	  if($joined){
		 foreach($joined as $join){
	?>

<input type="text" name="joined_id" value="<?php echo $join['id'];?>">

<?php
		 }
		}
?>
</div>
<input type="submit" name="joinChatRoom" id="joinChatRoom" value="Вступить в чат-комнату">

</form>
	


   <?php
		if(isset($_POST['joinChatRoom'])) {
		
			
		if (isset($_GET['ID'])){
	
			$joined_id = $_POST['joined_id'];
			$stmt = $db->prepare('SELECT * FROM joined WHERE ID=?');
			$stmt->bindParam(1, $joined_id, PDO::PARAM_INT);
			$stmt->execute();
			$row = $stmt->fetch(PDO::FETCH_ASSOC);
			
			if($row)
			{
				$joined_id = $_POST['joined_id'];	
				$pdoQuery = "DELETE FROM `joined` WHERE id = :id";
				$pdoResult = $db->prepare($pdoQuery);
				$pdoExec = $pdoResult->execute(array(":id"=>$joined_id));
			
			}

		else {
			$id=$_GET['ID'];
			$userId = $_SESSION['user_id'];
				$sql = 'INSERT INTO joined (user_id, chat_id) VALUES (?, ?)';
$query = $db->prepare($sql);
$query->execute([$userId, $id]);
			}
		}
		}
	

?>

1 个答案:

答案 0 :(得分:-1)

我已经更新了答案。这肯定会解决问题

<?php
session_start();
$_SESSION["user_id"] = 4;
?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width">
	<title>chat-room</title>
</head>
<body>

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

$current_user = -1;
if(isset($_SESSION['user_id'])){
  $current_user = $_SESSION['user_id'];
}
else{
  die("Invalid Session!");
}

//Declare button text. Should not contain underscores('_').
$possible_actions=array("Join Me","Leave");

try {
    $db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    if(isset($_POST['joinChatRoom'])) {            
        if (isset($_POST['chat_action'])){
            $action_info = explode("_",$_POST['chat_action']);
            $action_text = $action_info[0];
            $chat_id = (int)$action_info[1];
            
            if(strcmp($action_text,$possible_actions[1])==0)
            {
                $pdoQuery = "DELETE FROM join_chat_user WHERE chat_id=:chat_id AND user_id=:user_id";
                $pdoResult = $db->prepare($pdoQuery);
                $pdoExec = $pdoResult->execute(array(":chat_id"=>$chat_id,":user_id"=>$current_user));
                echo "You left!";
            
            }else {
                // prepare sql and bind parameters
                $stmt = $db->prepare("INSERT INTO join_chat_user (chat_id, user_id) VALUES (:chat_id, :user_id)");
                $stmt->bindParam(':chat_id', $chat_id);
                $stmt->bindParam(':user_id', $current_user);
                $stmt->execute();
                echo "You joined!";
            }
        }
    }else if(isset($_POST['addChatRoom'])){
        $sql="select count(DISTINCT(chat_id)) As 'class_count' from join_chat_user";
        $data=$db->prepare($sql);
        $data->execute();
        $count=(int)$data->fetch(PDO::FETCH_ASSOC)['class_count'];
        $count++;
        $stmt = $db->prepare("INSERT INTO join_chat_user (chat_id, user_id) VALUES (:chat_id, :user_id)");
        $stmt->bindParam(':chat_id', $count);
        $stmt->bindParam(':user_id', $current_user);
        $stmt->execute();
        echo "New chat created. You joined the new chat-$count!";
    }
    
    $sql="select chat_id,user_id from join_chat_user order by chat_id desc";
    $data=$db->prepare($sql);
    $data->execute();
    $joined=$data->fetchAll();
    $unique_chats = array();
    for($i=0;$i<sizeof($joined);$i++){
        if(!in_array($joined[$i]['chat_id'],$unique_chats)){
            array_push($unique_chats,$joined[$i]['chat_id']);
        }
    }
    ?>
    <form method="post">
    <table border="0">
    <thead>
        <tr>
            <th>Chat ID</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
    <?php
    foreach($unique_chats as $chat_id){
        $action_text=$possible_actions[0];
        $joined_users=array();
        foreach($joined as $record){
            if($record['chat_id']==$chat_id){
                array_push($joined_users,$record['user_id']);
            }
        }
        
        if(in_array($current_user,$joined_users)){
            $action_text=$possible_actions[1];
        }
        ?>
        <tr>
        <td><?php echo $chat_id; ?></td>
        <td><input type="radio" name="chat_action" value="<?php echo $action_text . "_" . $chat_id; ?>"><?php echo $action_text; ?></button></td>   
        </tr>
        <?php
    }
    ?>
    </tbody>
    </table>
<input type="submit" name="joinChatRoom" id="joinChatRoom" value="Вступить в чат-комнату">
<input type="submit" name="addChatRoom" id="addChatRoom" value="Add New Chat Room">
</form>
<?php
    
}
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }

$conn = null;
?>

这是它的显示方式。

user tries to join chat

after you join some chat

after you leave some chat

in case you create a new chat

相关问题