Create a topic'; if($_SESSION['signedIn'] == false) { //the user is not signed in echo 'Sorry, you have to be signed in to create a topic.'; } else { //the user is signed in if($_SERVER['REQUEST_METHOD'] != 'POST') { //the form hasn't been posted yet, display it //retrieve the categories from the database for use in the dropdown $sql = "SELECT catNo, catName, catDescr FROM categories"; $result = $conn->query($sql); if(!$result) { //the query failed, uh-oh :-( echo 'Error while selecting from database. Please try again later.'; } else { if($result->num_rows == 0) { //there are no categories, so a topic can't be posted if($_SESSION['userLevel'] == 1) { echo 'You have not created categories yet.'; } else { echo 'Before you can post a topic, you must wait for an admin to create some categories.'; } } else { echo '




'; echo '

'; echo '


'; } } } else { //start the transaction $query = "BEGIN WORK;"; if(!$conn->query($query)) { //Damn! the query failed, quit echo 'An error occured while creating your topic. Please try again later.'; } else { //the form has been posted, so save it //insert the topic into the topics table first, then we'll save the post into the posts table $sql = "INSERT INTO topics(topicSubject, topicDate, topicCat, topicBy) VALUES(?, NOW(), ?, ?)"; $stmt = $conn->prepare($sql); $stmt->bind_param('sii', $_POST['topicSubject'], $_POST['topicCat'], $_SESSION['userNo']); if(!$stmt->execute()) { //something went wrong, display the error echo 'An error occured while inserting your data. Please try again later.

' . $conn->error; $sql = "ROLLBACK;"; $conn->query($sql); } else { //the first query worked, now start the second, posts query //retrieve the id of the freshly created topic for usage in the posts query $topicid = $conn->insert_id; $sql = "INSERT INTO posts(postContent, postDate, postTopic, postBy) VALUES (?, NOW(), ?, ?)"; $stmt = $conn->prepare($sql); $stmt->bind_param('sii', $_POST['postContent'], $topicid, $_SESSION['userNo']); if(!$stmt->execute()) { //something went wrong, display the error echo 'An error occured while inserting your post. Please try again later.

' . $conn->error; $sql = "ROLLBACK;"; $conn->query($sql); } else { $sql = "COMMIT;"; $conn->query($sql); //after a lot of work, the query succeeded! echo 'You have succesfully created your new topic.'; } } } } } include 'footer.php'; ?>