I have this basic script checking to make sure a conversation doesn't already take place in the database, if it does, it should get that conversations ID number and send the user to that conversation, otherwise process the info. I'm halfway through and totally stuck as no matter what it doesn't seem to be checking correctly as it just keeps adding the same conversations...
edited to include further information:
Upon script initiate it will work and add a conversation as it should to the two databases I have:
ap_conversations:
conversation_id | user_one | user_two | time | delete
ap_messages:
message_id | message | sender_id | time_sent | time_read | conversation_id
if there is already a conversation in ap_conversations with the two users, I would like to send the user to THAT conversation rather than create a whole new one. Although the script won't do that and is just creating multiple conversations.
/////////// CREATE NEW CONVERSATION //////////////////////
if(isset($_POST['newmessage'])){
$to = $_POST['to'];
$text = $_POST['message'];
$message = str_replace("'","\\'",$text);
$userid = $_SESSION['userid'];
/// GET OTHER USER ID
$c_id = rand();
$getID = mysqli_fetch_assoc(mysqli_query($conn, "SELECT user_id FROM ap_users
WHERE '$to' LIKE CONCAT(first_name, '%', last_name)"));
$touserID = $getID['user_id'];
if(isset($touserID)){
/// CHECK CONVO DOESNT EXIST
$sql = "SELECT * from ap_conversations WHERE user_one = '$userid' AND user_two = '$touserid' OR user_two = '$userid' AND user_one = '$touserid' LIMIT 1";
$result = $conn->query($sql);
if($result->num_rows != 1){
mysqli_query($conn,"INSERT INTO `ap_conversations` (`conversation_id`, `user_one`, `user_two`, `time`, `delete`)
VALUES ('$c_id', '$userid', '$touserID', NOW(), '0');");
mysqli_query($conn,"INSERT INTO ap_messages (message_id, message, sender_id, time_sent, time_read, conversation_id)
VALUES ('','$message','$userid', NOW(), '', '$c_id')");
header('Location: messages.php?convoid='.$c_id.'');
} else {
$getconid = mysqli_fetch_assoc(mysqli_query($conn, "SELECT conversation_id FROM ap_conversations
WHERE user_one = '$userid' AND user_two = '$touserid' OR user_two = '$userid' AND user_one = '$touserid' LIMIT 1"));
$conid = $getconid['conversation_id'];
header('Location: messages.php?convo='.$conid.'');
}
} else {
header('Location: messages.php?error=2');
}
}