Jump to content

Fishcakes

Members
  • Posts

    40
  • Joined

  • Last visited

Everything posted by Fishcakes

  1. I'm creating a forum and I created a button which deletes from the SQL database and also the file (image/pdf or mp4) Could I get some guidance on how to turn the SQL query into a prepared statement? As at the moment I've made it so only a User of their thread can delete their own thread (I intend to implement moderators that can delete threads also). Do I need to do additional security checks on a $_SESSION variable? <?php include 'Dbh.php' ; class DeleteThread extends Dbh { public function DisplayDeleteButton($number) { if($UserOfThread == $CurrentUser) { echo " <form action='Includes/ClassDeleteThread_ViewThreadPage.php' method='post' enctype'multipart/form-data'> <input type='submit' name='Delete Thread' value='Delete'/> <input type='hidden' name='name' value=$number> </form>" ; } } public function DeleteThreadFromDataBase($PostID, $UserOfThread, $CurrentUser) { if($UserOfThread == $CurrentUser) { $sql = "DELETE FROM `Threads` WHERE id = $PostID"; $result = $this->connect()->query($sql); echo "success" ; } else { echo "failure" ; } } public function DeleteFileFromServer($UserOfThread, $CurrentUser,$FilePath) { if($UserOfThread == $CurrentUser) { $UploadDirectory = "../upload/" ; $ThumbnailDirectory = "../upload/Thumbnails/" ; $FilePath = $UploadDirectory . $FilePath ; $ThumbnailDirectory = $ThumbnailDirectory . $FilePath ; unlink($FilePath); echo "<P> Upload File Deleted" ; unlink($ThumbnailDirectory); echo "<P> Thumbnail File Deleted" ; } else { echo "<P> You are not the owner of this thread nor a mod" ; } } } $CurrentUser = $_POST['CurrentUser'] ; $UserOfThread = $_POST['UserOfThread'] ; $PostID = $_POST['id'] ; $FilePath = $_POST['FilePath'] ; echo $CurrentUser; echo $UserOfThread; echo $PostID; echo $FilePath; $Gen = new DeleteThread(); $Gen->DeleteThreadFromDataBase($PostID, $UserOfThread, $CurrentUser) ; $Gen->DeleteFileFromServer($UserOfThread, $CurrentUser, $FilePath); Also a question on global variables: When the user clicks the delete button which the code is on the viewthread.php and the CurrentUser variable comes from the $User variable which is derived from $User = $_SESSION['username'] ; <form action='Includes/ClassDeleteThread_ViewThreadPage.php' method='post' enctype'multipart/form-data' onclick='return confirm('Are you sure?')'> <input type='submit' name='Delete Thread' value='Delete'/> <input type='hidden' name='id' value=$number> <input type='hidden' name='CurrentUser' value=$User> <input type='hidden' name='UserOfThread' value=$UserOfThread> <input type='hidden' name='FilePath' value=$imageURL> </form> Is here a way that end users can spoof the $_SESSION['username'] variable? Thanks
  2. Hi On retrieving data from my database I use the following function to insert HTML line breaks to retain how the comment looks $CommentText= nl2br($data['CommentText']); However I'd look users to to be able to quote using the ">" character (like in reddit - so say they want to 'quote' something from a book or article) So I'm trying to wrap my head around how to do this. Would I the string for "<br>>" (to find the line break then the additional ">") and then how would I take all of the characters after the ">" to the next "<br>"? The below function is what I have started with public function Convert_Quotation($CommentText) { $FindQuote = substr($CommentText, strpos($CommentText, '<br>>') + 50); return $CommentText ; } //function end
  3. Yes I did Yes that was just me testing something I tried it here for instance and this works in a test file <html> <head> <title>Country</title> </head> <body> <form method="POST" action=""> Select Your Country <select name="country" onchange="this.form.submit()"> <option value="" disabled selected>--select--</option> <option value="india">India</option> <option value="us">Us</option> <option value="europe">Europe</option> </select> </form> <?php if(isset($_POST["country"])){ $country=$_POST["country"]; echo "select country is => ".$country; } ?> </body> </html>
  4. Hi So my webpage puts out a load of data formatted like the below for my forum So I'm currently working on the ModTools dropdown and I'd like to be able to select from the drop down then pick an item which runs a php command (to delete a forum thread Or lock the thread or delete and ban user this kind of thing) so at the moment I am working on the MODTOOLS dropdown box So I created this class and this function class ModTools extends GetModList { public function DisplayModTools($PostId, $User) { //If statement to check user is logged in if(isset($_SESSION['username'])){ $Output = " <form id='DropdownForm' action='' method='post'> <select name='modSelected' id='ModTool' onchange=’this.form.submit()'> <option value=''>ModTools</option> <option value=$PostId>Delete</option> <option value=$PostId>ShitLib</option> <option value='$PostId>Offtopic</option> </select> </form> "; return $Output ; } //endif statement }//end func } Then I have this php in my index.php file near the bottom if(isset($_POST["modSelected"])){ $Dropdownstatus=$_POST["Delete"]; echo "select dropdown modlist is => ".$Dropdownstatus; } But it doesn't seem to echo out the last echo command?
  5. OK I'll have a go at cleaning it into a function I can call but essentially I am taking in a row of data into an array with also has an array KEY (Which i link to the "id" of the comment) $ParentComments[$PostID] = " I then take in the level 1 comments (ie. replies to a top level comment) with a variable $ParentId for the array key which will take the "ParentId" which should match the "$PostId" variable above. $replies[$ParentId] = " So now I have the top level comments in $ParentComments and I have the responses to these top level comments in $replies I now want to write a foreach loop which spits out the top level comments like so but after it echos that comment I want to Check if the $replies array contains a response by matching the $ParentComments[$PostId] against the $replies[$ParentId foreach ($ParentComments as $key => $toplevelcomment) { echo $toplevelcomment ; //It is this point that I would now like to check the $replies array //Then if the $key matches the array key of $replies array //echo that comment }
  6. So I take into an array from SQL like so public function ShowComments($Number) { $datas = $this->GetPosts($Number) ; echo "type equals: " . gettype($datas) . "<P>"; foreach ($datas as $data) { //May need this later to output pictures // $imageURL = 'upload/'.rawurlencode($row["filename"]); $CommentText= nl2br($data['CommentText']); $avatarFilePath = $data['avatar']; $id = $data['IDOfThread']; $PostID = $data['id'] ; $ParentId = $data['ParentId']; convertYoutube($CommentText); $oFlairs = new cFlairs(); $oFlairs->DisplayFlairs($CommentText); //Work out Margin for comment replies $levelNumber = $data['level']; $Level = $data['level'] * 75; // Used to multiply the margin to create nested comments //$Level = 1 * 75 ; $margin = "<div class='divTableCell' style='margin-left: $Level" . "px ; '/>"; //input the margin in child comments //$margin = "<div class='divTableCell' style='margin-left: 75" . "px ; '>"; //input the margin in child comments $ParentComment[] = ""; //Get parent comments into an array if (empty($data['ParentId'])) { $ParentComments[$PostID] = " <div class='divTabledata'> <div class='divTableCell'> <div class ='UserAndAvatarCommentBox'> <div > <img src=$avatarFilePath alt='' /> </div> <div class='profileUsername'> {$data['User']} </div> </div> <div class='pointsincommentbox'> {$data['Upvotes']}points</div> <div class='divTableComment'> $CommentText <br> <div> <div class='divCommentLinks'> <button type='button'> ⬆</button> <button type='button'> ⬇</button> <div> $PostID </div> <button type='button'> view comment </button> <button type='button'>report </button> <button type='button'>permalink</button> <button type='button' class ='CommentChildButton'>reply</button> <div class ='OpenChildCommentBox'> <form action='CommentUpload.php' method='post' enctype='multipart/form-data'> <table> <tr> <td></td> </tr> <input type='text' value=$PostID name='PostId' /> <input type='text' value='1' name='level' /> <tr> <td>Comment: </td> <td> <textarea name='CommentText' cols='100' datas='10' > Enter your posts... </textarea> </td> <td></td> </tr> <tr> <td></td> <td><input type='submit' name='submit' value='Submit'/></td> <td></td> </tr> </table> </form> </div> </div> </div> </div> </div> </div> \n"; } Above I use the $ParentComments[$PostID] = " etc etc" to build the top level comment I then take the Level 1 comments which are all the comments that are a reply to a top level comment Ie. ParentComment -ResponseComment //Get child comments into an array level 1 if ($data['ParentId'] && $data['level'] == 1 ) { $replies[$ParentId] = " <div class='divTabledata'> <div class='divTableCell' style='margin-left:75px'> <div class ='UserAndAvatarCommentBox'> <div > <img src=$avatarFilePath alt='' /> </div> <div class='profileUsername'> {$data['User']} </div> </div> <div class='pointsincommentbox'> {$data['Upvotes']}points</div> <div class='divTableComment'> $CommentText <br> <div class='divCommentLinks'> <button type='button'> ⬆</button> <button type='button'> ⬇</button> <div> $PostID </div> <button type='button'> view comment </button> <button type='button'>report </button> <button type='button'>permalink</button> <button type='button' class ='CommentChildButton'>reply</button> <div class ='OpenChildCommentBox'> <form action='CommentUpload.php' method='post' enctype='multipart/form-data'> <table> <tr> <td></td> </tr> <input type='text' value=$PostID name='PostId' /> <input type='text' value={$data['level']} name='level' /> <tr> <td>Comment: </td> <td> <textarea name='CommentText' cols='100' datas='10' > Enter your posts... </textarea> </td> <td></td> </tr> <tr> <td></td> <td><input type='submit' name='submit' value='Submit'/></td> <td></td> </tr> </table> </form> </div> </div> </div> </div> </div> </div> \n"; } I tried outputting these like the following however it seems to output only 1 of the child comments under the correct Parent comment (the other comments in response to that comment don't show). Is there a better way to do this? foreach ($ParentComments as $key => $reply) { echo $reply ; foreach ($replies as $childKey => $childReply) { if ($key == $childKey) { echo $childReply ; foreach ($Level2 as $Key2 => $Level2Reply) { if ($Key2 == $childKey) { echo $Level2Reply ; } } } } }//foreach loop */
  7. So I'm trying to create a comment system with the comment SQL table looking like this describe Posts -> ; +---------------+-----------------+------+-----+---------------------+-------------------------------+ | Field | Type | Null | Key | Default | Extra | +---------------+-----------------+------+-----+---------------------+-------------------------------+ | id | int(6) unsigned | NO | PRI | NULL | auto_increment | | User | varchar(30) | NO | | NULL | | | PostTimeStamp | timestamp | NO | | current_timestamp() | on update current_timestamp() | | CommentText | varchar(8000) | YES | | NULL | | | IDOfThread | int(11) | YES | | NULL | | | Upvotes | int(11) | NO | | 0 | | | ParentId | int(11) | YES | | NULL | | | level | int(11) | YES | | NULL | So I then pull from the SQL table like this - creating an array for each 'level' of the data and how I want the comment to be displayed while ($row = mysqli_fetch_array($query)) { //May need this later to output pictures // $imageURL = 'upload/'.rawurlencode($row["filename"]); $CommentText = nl2br($row['CommentText']); $avatarFilePath = $row['avatar']; $id = $row['IDOfThread']; $PostID = $row['id'] ; $ParentId = $row['ParentId']; convertYoutube($CommentText); //Work out Margin for comment replies $Level = $row['level'] * 75; // Used to multiply the margin to create nested comments echo $Level ; //$Level = 1 * 75 ; $margin = "<div class='divTableCell' style='margin-left: $Level" . "px ; '>"; //input the margin in child comments //$margin = "<div class='divTableCell' style='margin-left: 75" . "px ; '>"; //input the margin in child comments $ParentComment = ""; //Get parent comments into an array if (empty($row['ParentId'])) { $ParentComments[$PostID] = " <div class='divTableRow'> <div class='divTableCell'> <div class ='UserAndAvatarCommentBox'> <div > <img src=$avatarFilePath alt='' /> </div> <div class='profileUsername'> {$row['User']} </div> </div> <div class='pointsincommentbox'> {$row['Upvotes']}points</div> <div class='divTableComment'> $CommentText <br> <div> <div class='divCommentLinks'> <button type='button'> ⬆</button> <button type='button'> ⬇</button> <div> $PostID </div> <button type='button'> view comment </button> <button type='button'>report </button> <button type='button'>permalink</button> <button type='button' class ='CommentChildButton'>reply</button> <div class ='OpenChildCommentBox'> <form action='CommentUpload.php' method='post' enctype='multipart/form-data'> <table> <tr> <td></td> </tr> <input type='text' value=$PostID name='PostId' /> <input type='text' value='1' name='level' /> <tr> <td>Comment: </td> <td> <textarea name='CommentText' cols='100' rows='10' > Enter your posts... </textarea> </td> <td></td> </tr> <tr> <td></td> <td><input type='submit' name='submit' value='Submit'/></td> <td></td> </tr> </table> </form> </div> </div> </div> </div> </div> </div> \n"; } //Get child comments into an array level 1 if ($row['ParentId'] && $row['level'] == 1 ) { $replies[$ParentId] = " <div class='divTableRow'> <div class='divTableCell' style='margin-left:75px'> <div class ='UserAndAvatarCommentBox'> <div > <img src=$avatarFilePath alt='' /> </div> <div class='profileUsername'> {$row['User']} </div> </div> <div class='pointsincommentbox'> {$row['Upvotes']}points</div> <div class='divTableComment'> $CommentText <br> <div class='divCommentLinks'> <button type='button'> ⬆</button> <button type='button'> ⬇</button> <div> $PostID </div> <button type='button'> view comment </button> <button type='button'>report </button> <button type='button'>permalink</button> <button type='button' class ='CommentChildButton'>reply</button> <div class ='OpenChildCommentBox'> <form action='CommentUpload.php' method='post' enctype='multipart/form-data'> <table> <tr> <td></td> </tr> <input type='text' value=$PostID name='PostId' /> <input type='text' value={$row['level']} name='level' /> <tr> <td>Comment: </td> <td> <textarea name='CommentText' cols='100' rows='10' > Enter your posts... </textarea> </td> <td></td> </tr> <tr> <td></td> <td><input type='submit' name='submit' value='Submit'/></td> <td></td> </tr> </table> </form> </div> </div> </div> </div> </div> </div> \n"; } //Get child comments into an array level 2 if ($row['ParentId'] && $row['level'] == 2 ) { $Level2[$ParentId] = " $margin <div class ='UserAndAvatarCommentBox'> <div > <img src=$avatarFilePath alt='' /> </div> <div class='profileUsername'> {$row['User']} </div> </div> <div class='pointsincommentbox'> {$row['Upvotes']}points</div> <div class='divTableComment'> $CommentText <br> <div class='divCommentLinks'> <button type='button'> ⬆</button> <button type='button'> ⬇</button> <div> $PostID </div> <button type='button'> view comment </button> <button type='button'>report </button> <button type='button'>permalink</button> <button type='button' class ='CommentChildButton'>reply</button> <div class ='OpenChildCommentBox'> <form action='ChildCommentUpload.php' method='post' enctype='multipart/form-data'> <table> <tr> <td></td> </tr> <input type='text' value=$PostID name='PostId' /> <input type='text' value={$row['level']} name='Level' /> <tr> <td>Comment: </td> <td> <textarea name='CommentText' cols='100' rows='10' > Enter your posts... </textarea> </td> <td></td> </tr> <tr> <td></td> <td><input type='submit' name='submit' value='Submit'/></td> <td></td> </tr> </table> </form> </div> </div> </div> </div> </div> </div> \n"; } } Then after the data has been put into arrays I then output it using this foreach statement foreach ($ParentComments as $key => $reply) { echo $reply ; foreach ($replies as $childKey => $childReply) { if ($key == $childKey) { echo $childReply ; foreach ($Level2 as $Key2 => $Level2Reply) { if ($childKey == $Key2) { echo $Level2Reply ; } } } } } So the problem I'm having is if you have a top level comment like TopLevelComment Then respond to it you get TopLevelComment -Level1ReplyComment However if you respond again to the top level comment it only shows the new comment like TopLevelComment -NewLevel1Comment Why would it do this rather than add another comment beneath the top level comment?
  8. This is the code of my indexx file I don't think it's a problem with my code though as even my previous backups of my website aren't working. And I also tried creating a phpinfo file with only phpinfo(); inside it and that isn't showing the php info screen So I think it's more a problem with my PHP install on debian and maybe I'm missing some php modules on debian for php 8.0 or something <?php include('classHeader.php'); include 'dbconnect.php'; session_start(); //Outputs header located in classHeader.php $HeaderFromClass = new HeaderClass(); echo $HeaderFromClass->get_Header(); //Second part changes depending on whether a user is logged in echo $HeaderFromClass->get_Header2ndPart(); ?> <body> <div class ='grid-container'> <?php //Get the Threads and output them onto the screen in a grid container $query = mysqli_query($conn, "select Threads.id as ThreadId, Title, Users, filename,url, LEFT(ThreadBody, 8000) as body, date_format(Thread_date, '%D %b %Y %l:%i %p') as ftime , count(Posts.IdOfThread) as num_posts from Threads Left join Posts on Threads.id = Posts.IdOfThread group by Threads.id order by Thread_date desc;") or die (mysqli_error($conn)); while ($row = mysqli_fetch_array($query)) { $videoURL = 'upload/' . rawurlencode($row["filename"]); $imageURL = 'upload/Thumbnails/'.rawurlencode($row["filename"]); $PostBody = nl2br($row['body']); echo " <div class ='grid-item'> <div class='ThreadComment'> <a href='viewthread.php?id={$row['ThreadId']}'> Comments:{$row['num_posts']} </a><br> </div> <div class='ThreadNumber'> <a href='viewthread.php?id={$row['ThreadId']}'> Post {$row['ThreadId']}</a><br> </div> <div class='indexpageUser'><a href='profile.php?id={$row['Users']}'> {$row['Users']} </a></div> <h2><a href='viewthread.php?id={$row['ThreadId']}'> {$row['Title']} </a></h2> <a href='{$row['url']}'> {$row['url']}</a> <div class='mainpageUpvoteCount'> {$row['upvotes']} </div>" ; //If user is logged in display upvote arrows. if(isset($_SESSION['username'])){ echo " <div class='mainpageupvote' id='upvote'><form action='upvotes.php' method='post' enctype='multipart/form-data' ><button name='ThreadID' value={$row['ThreadId']}> ⬆ </button></form></div> <div class='mainpagedownvote'><button onclick='downvote()' value={$row['ThreadId']} > ⬇</button></div> "; } echo "<div class ='img-block'>" ; //If file is a PDF display standard PDF icon else select the filename from the uploads folder if(strpos($imageURL, "pdf") !== false){ echo "<a href='viewthread.php?id={$row['ThreadId']}'><img src='Icons/PDF.jpg' alt='' /> </a> " ; } if(strpos($videoURL, "mp4") !== false){ $videocode = "<embed src=$videoURL autostart='false' height='200' width='200'/></embed>" ; echo $videocode ; } if(strpos($videoURL, "webm") !== false){ $videocode = "<embed src=$videoURL autostart='false' height='200' width='200'/></embed>" ; echo $videocode ; } else { echo "<a href='viewthread.php?id={$row['ThreadId']}'><img src={$row['$imageURL']}$imageURL alt='' /> </a>"; } echo " </div> <p>$PostBody </p> </div> \n"; } /* " <div class ='grid-item'> <div class='ThreadComment'> <a href='viewthread.php?id={$row['ThreadId']}'> Comments:{$row['num_posts']} </a><br> </div> <div class='ThreadNumber'> <a href='viewthread.php?id={$row['ThreadId']}'> Post {$row['ThreadId']}</a><br> </div> <div class='indexpageUser'>{$row['Users']} </div> <h2><a href='viewthread.php?id={$row['ThreadId']}'> {$row['Title']} </a></h2> <div class='mainpageUpvoteCount'> {$row['upvotes']} </div> <div class='mainpageupvote' id='upvote'><button onclick='upvote()' class='upvotes' value={$row['ThreadId']}> ⬆ </button></div> <div class='mainpagedownvote'><button onclick='downvote()' class='upvotes' value={$row['ThreadId']} > ⬇</button></div> <div class ='img-block'>" ; //If file is a PDF display standard PDF icon else select the filename from the uploads folder if(strpos($imageURL, "pdf") !== false){ echo "<a href='viewthread.php?id={$row['ThreadId']}'><img src='Icons/PDF.jpg' alt='' /> </a> " ; } else { echo "<a href='viewthread.php?id={$row['ThreadId']}'><img src={$row['$imageURL']}$imageURL alt='' /> </a>"; } echo " </div> <p>$PostBody </p> </div> \n"; */ ?> </body> </html> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script> $('#grid-container').click(function(){ $('#grid-item').animate({height:'600px'}, 500); $('#grid-item').animate({width:'600px'}, 500); }); function upvote(){ $.ajax({ type: "POST", url: "upvotes.php", data: {$row['ThreadId']}, success:function( msg ) { alert( "Data Saved: " + msg ); } }); } </script> <script> function downvote(){ $.ajax({ type: "POST", url: "upvotes.php", data: name: $("select[name='players']").val()}, success:function( msg ) { alert( "Data Saved: " + msg ); } }); } </script>
  9. See below my website is showing like this I think debian upgraded from php 7.3 or 4 to 8.0 I am wondering if I am missing some php packages if run php -v at terminal I get php -v PHP 8.0.7 (cli) (built: Jun 4 2021 23:17:30) ( NTS ) Copyright (c) The PHP Group Zend Engine v4.0.7, Copyright (c) Zend Technologies with Zend OPcache v8.0.7, Copyright (c), by Zend Technologies and if I run php -m at terminal i get php -m [PHP Modules] calendar Core ctype date dom exif FFI fileinfo filter ftp gd gettext hash iconv json libxml mysqli mysqlnd openssl pcntl pcre PDO pdo_mysql Phar posix readline Reflection session shmop SimpleXML sockets sodium SPL standard sysvmsg sysvsem sysvshm tokenizer xml xmlreader xmlwriter xsl Zend OPcache zlib [Zend Modules] Zend OPcache
  10. I tried parsing through first https://www.jadaliyya.com/Details/28167/The-Empire-of-Sexuality-An-Interview-with-Joseph-Massad then even tried www.google.com and on both I get the following returned post_url equals: www.google.compost_title equals: testpost_Threadybody equals: Enter your posts... URL equals: www.google.com www.google.com is not a valid URL Web page redirects after 2 seconds. And here is the if statement that handles my filter for URLs if(isset($_POST["submit"]) && !empty($_POST["url"]) && !empty($_POST["Title"])){ $URL = $conn -> real_escape_string($_POST["url"]) ; $BodyText = $conn -> real_escape_string(nl2br($_POST["ThreadBody"])) ; echo "<P>URL equals: " ; echo $URL ; echo "<P>" ; //Change to embed for youtube. if (filter_var($URL, FILTER_VALIDATE_URL)) { echo("$URL is a valid URL"); //Check if url is a youtube url if (strpos($URL,'youtube') !== false) { echo 'Youtube exists.'; $URL = preg_replace("/\s*[a-zA-Z\/\/:\.]*youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i","<iframe width=\"420\" height=\"315\" src=\"//www.youtube.com/embed/$1\" frameborder=\"0\" allowfullscreen></iframe>",$URL); } else { echo 'Youtube is not included .'; $URL = "<ahref ='" . $URL . "</a>" ; } $Title = $conn -> real_escape_string($_POST["Title"]) ; $User = $_SESSION['username']; $sql = "INSERT INTO Threads (Title, Users, ThreadBody, url) VALUES ('$Title', '$User','$BodyText','$URL')"; if (mysqli_query($conn, $sql)) { echo "New record has been added successfully !"; } else { echo "Error: " . $sql . ":-" . mysqli_error($conn); } } else { echo("$URL is not a valid URL"); }
  11. Hi I am currently mostly learning procedural PHP but had a question about security. Are hackers able to see connections to databases in procedural programming? Would connections to databases need to be called from classes and methods instead? Or does it not matter that much?
  12. Thanks yeah I managed to work out you could select just the one column like so select Posts.*, Users.avatar from Posts
  13. Hi I'm trying to figure out why this statement produces the below select Posts.id as PostsId, Posts.User as PostsUser, CommentText,IdOfThread, ParentId from Posts join Users on Users.User=Posts.User where Posts.IdOfThread = '281'; | PostsId | PostsUser | CommentText | IdOfThread | ParentId | +---------+-----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+----------+ | 136 | JoeySteel | | 281 | NULL | | 137 | JoeySteel | test | 281 | NULL | | 138 | JoeySteel | Test Comment Child | 281 | 136 | | 139 | JoeySteel | Test Comment Child | 281 | 136 | | 140 | JoeySteel | <img src="https://lemmygrad.ml/pictrs/image/5aqjdOcJ15.jpg" /> | 281 | NULL | | 141 | JoeySteel | He’s pretty understated. He had some funny observations about people who we put to work that had no prior experience and just was all “it was an uphill battle but they knew what they were doing eventually and worked just as well as any other specialist.” Him complaining about the lack of taxis was pretty funny too. Also gesticulating as communication when his escorts weren’t available. | 281 | NULL | +---------+-----------+----- Which is basically all the info I want. However I also need the avatar column from the Users table. However when I modify the statement to include "Users.avatar" it returns that it doesn't exist select Posts.id as PostsId, Posts.User as PostsUser, CommentText,IdOfThread, ParentId from Posts join Users on Users.User=Posts.User,Users.avatar where Posts.IdOfThread = '281'; ERROR 1146 (42S02): Table 'Users.avatar' doesn't exist However you can see that Users.avatar does exist describe Users ; +----------+-----------------+------+-----+---------------------+-------------------------------+ | Field | Type | Null | Key | Default | Extra | +----------+-----------------+------+-----+---------------------+-------------------------------+ | id | int(6) unsigned | NO | PRI | NULL | auto_increment | | User | varchar(30) | NO | | NULL | | | Password | varchar(50) | YES | | NULL | | | DateReg | timestamp | NO | | current_timestamp() | on update current_timestamp() | | avatar | varchar(150) | YES | | NULL | | +----------+-----------------+------+-----+---------------------+-------------------------------+ I have tried using the left and right joins (which didn't seem to make a difference) as well as "full outer join" (Mariadb didn't recognise that) Thanks
  14. So I implemented it like this and my page loads fine however it doesn't retrieve any of the comments Also looking at the code you wrote should I have a children column on the my Posts table(comments table)? Also when I comment on my site? <!DOCTYPE html> <html> <header> <link href="styles.css" rel="stylesheet" type="text/css" media="all"> <title> Image Board</title> <div class="header"> <a href="index.php" class="logo">ONLINE</a> <div class="header-right"> <a class="active" href="#home">Home</a> <a href="#news">News</a> <a href="#contact">Education</a> <a href="#about">Tech</a> </div> </div> </header> <body> <!-- <a href="CreateThread.php"> <h1>Create Thread</h1> </a> --> <div class ='Thread-grid-container'> <?php include 'dbconnect.php'; $number = intval($_GET['id']) ; session_start(); $_SESSION['id'] = $number ; $query = mysqli_query($conn, "SELECT * FROM Threads where id=$number") or die (mysqli_error($conn)); //Output Grid layout for a Thread post while ($row = mysqli_fetch_array($query)) { //output picture from upload folder $imageURL = 'upload/'.rawurlencode($row["filename"]); //Check if filename is a pdf otherwise output for image if(strpos($imageURL, "pdf") !== false){ echo " <div class ='Thread-grid-item'> <div class='ThreadNumber'> Post {$row['id']}<br> </div> <div class='UserOnThread'>{$row['Users']} </div> <h2>{$row['Title']} </h2> <button type='button' class ='collapse'>Hide</button> <div class ='img-block'> <a href=$imageURL> <img src='Icons/PDF.jpg' alt='' /> </a> </div> <div class='bodytextThread'> <p>{$row['ThreadBody']}</p> </div> </div> \n"; } else{ echo " <div class ='Thread-grid-item'> <div class='ThreadNumber'> Post {$row['id']}<br> </div> <div class='UserOnThread'>{$row['Users']} </div> <h2>{$row['Title']} </h2> <button type='button' class ='collapse'>Hide</button> <div class ='img-block'> <img src=$imageURL alt='' /> </div> <div class='bodytextThread'> <p>{$row['ThreadBody']}</p> </div> </div> \n"; } }?> <div class="comment-upload-box"> <form action="CommentUpload.php" method="post" enctype="multipart/form-data"> <table> <tr> <td></td> </tr> <tr> <td>Comment: </td> <td> <textarea name="CommentText" cols="100" rows="10" > Enter your posts... </textarea> </td> <td></td> </tr> <tr> <td></td> <td><input type="submit" name='submit' value="Submit"/></td> <td></td> </tr> </table> </form> </div> <div class='divTableForComments'> <div class='divTableBody'> <?php include 'dbconnect.php'; //Output Comments onto page //Create a variable for the Comment boxes so when clicking reply a text area shows $ChildCommentBoxes = "<div class='child-comment-upload-box' style='margin-left: 48px'> <form action='ChildCommentUpload.php' method='post' enctype'multipart/form-data'> <table> <tr> <td></td> </tr> <tr> <td>Comment: </td> <td> <textarea name='ChildCommentText' cols='100' rows='10' > Enter your posts... </textarea> </td> <td></td> </tr> <tr> <td></td> <td><input type='submit' name='submit' value='Submit'/></td> <td></td> </tr> </table> </form>"; $query = mysqli_query($conn, "SELECT * FROM Posts where IDOfThread=$number") or die (mysqli_error($conn)); $tree=[]; $map=[]; foreach ($queryResults as &$row){ if ($row['ParentId']){ $map[$row['ParentId']]['children'][] = &$row; } else { $row['children']=[]; $tree[] = &$row; } $map[$row['id']] = &$row; } function outputPostTree(array $tree){ echo '<ul>'; foreach ($tree as $post){ echo '<li>'.$post['CommentText']; if ($post['children']){ outputPostTree($post['children']); } echo '</li>'; } echo '</ul>'; } ?> <div class ="sidebar"> </div> </body> </html> <script> var coll = document.getElementsByClassName("collapse"); var i; for (i = 0; i < coll.length; i++) { coll[i].addEventListener("click", function() { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.display === "block") { content.style.display = "none"; } else { content.style.display = "block"; } }); } </script> <script> var coll2 = document.getElementsByClassName("CommentChildButton"); var i; for (i = 0; i < coll2.length; i++) { coll2[i].addEventListener("click", function() { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.display === "block ") { content.style.display = "none"; } else { content.style.display = "block"; } }); } </script> <script> document.getElementById("upvote").onclick = function(){ onmouseover = document.body.style.cursor = "pointer"; document.getElementById("upvote").style.color = 'orange'; } </script>
  15. So I wanted to create stickers on my forum where people type in say ":Blobby-Tired" and then instead of the comment showing ":Blobby-Tired" it shows an html image tag displaying a picture of Blobby in the comment box So I created the following page CommentUpload.php However my sql fails to insert it despite the fact when I "echo $new" it shows the image on the page correctly And it can't be my sql insert code as if I change $new variable for "$BodyText" int he SQL query it it inserts ":Blobby-Tired" OK? <?php include 'dbconnect.php'; session_start(); if(isset($_POST["submit"]) && !empty($_POST["CommentText"])){ $id = intval($_SESSION['id']); echo $_SESSION['id'] . '<p> </p>' ; $BodyText = $conn -> real_escape_string($_POST['CommentText']) ; $User = $_SESSION['username']; //Replace flairs with <img> tags /*not working currently) */ $new = str_replace(":Blobby-Tired","<img src='flairs/Blobby-Tired.jpg'> </img>","'$BodyText'"); echo "$new"; /************************/ $sql = "INSERT INTO Posts (User, CommentText, IdOfThread) VALUES ('$User','$new','$id')"; if (mysqli_query($conn, $sql)) { echo "New record has been added successfully !"; } else { echo "Error: " . $sql . ":-" . mysqli_error($conn); } mysqli_close($conn); } ?>
  16. So I did implement this but it doesn't output anything. The page does load but the comments don't get spat out. when running at the command line "php viewthread2.php" I get this back however? PHP Warning: Undefined variable $tree in /var/www/html/Backup16042020/viewthread2.php on line 129 PHP Fatal error: Uncaught TypeError: outputPostTree(): Argument #1 ($tree) must be of type array, null given, called in /var/www/html/Backup16042020/viewthread2.php on line 129 and defined in /var/www/html/Backup16042020/viewthread2.php:132 Stack trace: #0 /var/www/html/Backup16042020/viewthread2.php(129): outputPostTree() #1 {main} thrown in /var/www/html/Backup16042020/viewthread2.php on line 132 with line 132 being the function declaration function outputPostTree(array $tree){ <!DOCTYPE html> <html> <header> <link href="styles.css" rel="stylesheet" type="text/css" media="all"> <title> Image Board</title> <div class="header"> <a href="index.php" class="logo"> ARMY ONLINE</a> <div class="header-right"> <a class="active" href="#home">Home</a> <a href="#news">News</a> <a href="#contact">Education</a> <a href="#about">Tech</a> </div> </div> </header> <body> <!-- <a href="CreateThread.php"> <h1>Create Thread</h1> </a> --> <div class ='Thread-grid-container'> <?php include 'dbconnect.php'; $number = intval($_GET['id']) ; session_start(); $_SESSION['id'] = $number ; $query = mysqli_query($conn, "SELECT * FROM Threads where id=$number") or die (mysqli_error($conn)); //Output Grid layout for a Thread post while ($row = mysqli_fetch_array($query)) { //output picture from upload folder $imageURL = 'upload/'.rawurlencode($row["filename"]); echo " <div class ='Thread-grid-item'> <div class='ThreadNumber'> Post {$row['id']}<br> </div> <div class='UserOnThread'>{$row['Users']} </div> <h2>{$row['Title']} </h2> <button type='button' class ='collapse'>Hide</button> <div class ='img-block'> <img src={$row['$imageURL']}$imageURL alt='' /> </div> <div class='bodytextThread'> <p>{$row['ThreadBody']}</p> </div> </div> \n"; }?> <div class="comment-upload-box"> <form action="CommentUpload.php" method="post" enctype="multipart/form-data"> <table> <tr> <td></td> </tr> <tr> <td>Comment: </td> <td> <textarea name="CommentText" cols="100" rows="10" > Enter your posts... </textarea> </td> <td></td> </tr> <tr> <td></td> <td><input type="submit" name='submit' value="Submit"/></td> <td></td> </tr> </table> </form> </div> <div class='divTableForComments'> <div class='divTableBody'> <?php include 'dbconnect.php'; //Output Comments onto page //Create a variable for the Comment boxes so when clicking reply a text area shows $ChildCommentBoxes = "<div class='child-comment-upload-box' style='margin-left: 48px'> <form action='ChildCommentUpload.php' method='post' enctype'multipart/form-data'> <table> <tr> <td></td> </tr> <tr> <td>Comment: </td> <td> <textarea name='ChildCommentText' cols='100' rows='10' > Enter your posts... </textarea> </td> <td></td> </tr> <tr> <td></td> <td><input type='submit' name='submit' value='Submit'/></td> <td></td> </tr> </table> </form>"; $query = mysqli_query($conn, "SELECT * FROM Posts where IDOfThread=$number") or die (mysqli_error($conn)); while ($row = mysqli_fetch_array($query)) { //May need this later to output pictures // $imageURL = 'upload/'.rawurlencode($row["filename"]); $CommentText = nl2br($row['CommentText']) ; $tree=[]; $map=[]; foreach ($query as &$row){ if ($row['ParentId']){ $map[$row['ParentId']]['children'][] = &$row; } else { $row['children']=[]; $tree[] = &$row; } $map[$row['id']] = &$row; } } echo outputPostTree($tree) ; function outputPostTree(array $tree){ echo '<ul>'; foreach ($tree as $post){ echo '<li>'.$post['CommentText']; if ($post['children']){ outputPostTree($post['children']); } echo '</li>'; } echo '</ul>'; } ?> <div class ="sidebar"> </div> </body> </html> <script> var coll = document.getElementsByClassName("collapse"); var i; for (i = 0; i < coll.length; i++) { coll[i].addEventListener("click", function() { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.display === "block") { content.style.display = "none"; } else { content.style.display = "block"; } }); } </script> <script> var coll2 = document.getElementsByClassName("CommentChildButton"); var i; for (i = 0; i < coll2.length; i++) { coll2[i].addEventListener("click", function() { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.display === "block ") { content.style.display = "none"; } else { content.style.display = "block"; } }); } </script> <script> document.getElementById("upvote").onclick = function(){ onmouseover = document.body.style.cursor = "pointer"; document.getElementById("upvote").style.color = 'orange'; } </script>
  17. That is a really nice solution I tried implementing it however and am not sure if I'm doing it correctly Also do I need to declare "children" as something? <!DOCTYPE html> <html> <header> <link href="styles.css" rel="stylesheet" type="text/css" media="all"> <title>Image Board</title> <div class="header"> <a href="index.php" class="logo">forum ONLINE</a> <div class="header-right"> <a class="active" href="#home">Home</a> <a href="#news">News</a> <a href="#contact">Education</a> <a href="#about">Tech</a> </div> </div> </header> <body> <!-- <a href="CreateThread.php"> <h1>Create Thread</h1> </a> --> <div class ='Thread-grid-container'> <?php include 'dbconnect.php'; $number = intval($_GET['id']) ; session_start(); $_SESSION['id'] = $number ; $query = mysqli_query($conn, "SELECT * FROM Threads where id=$number") or die (mysqli_error($conn)); //Output Grid layout for a Thread post while ($row = mysqli_fetch_array($query)) { //output picture from upload folder $imageURL = 'upload/'.rawurlencode($row["filename"]); echo " <div class ='Thread-grid-item'> <div class='ThreadNumber'> Post {$row['id']}<br> </div> <div class='UserOnThread'>{$row['Users']} </div> <h2>{$row['Title']} </h2> <button type='button' class ='collapse'>Hide</button> <div class ='img-block'> <img src={$row['$imageURL']}$imageURL alt='' /> </div> <div class='bodytextThread'> <p>{$row['ThreadBody']}</p> </div> </div> \n"; }?> <div class="comment-upload-box"> <form action="CommentUpload.php" method="post" enctype="multipart/form-data"> <table> <tr> <td></td> </tr> <tr> <td>Comment: </td> <td> <textarea name="CommentText" cols="100" rows="10" > Enter your posts... </textarea> </td> <td></td> </tr> <tr> <td></td> <td><input type="submit" name='submit' value="Submit"/></td> <td></td> </tr> </table> </form> </div> <div class='divTableForComments'> <div class='divTableBody'> <?php include 'dbconnect.php'; //Output Comments onto page //Create a variable for the Comment boxes so when clicking reply a text area shows $ChildCommentBoxes = "<div class='child-comment-upload-box' style='margin-left: 48px'> <form action='ChildCommentUpload.php' method='post' enctype'multipart/form-data'> <table> <tr> <td></td> </tr> <tr> <td>Comment: </td> <td> <textarea name='ChildCommentText' cols='100' rows='10' > Enter your posts... </textarea> </td> <td></td> </tr> <tr> <td></td> <td><input type='submit' name='submit' value='Submit'/></td> <td></td> </tr> </table> </form>"; $query = mysqli_query($conn, "SELECT * FROM Posts where IDOfThread=$number") or die (mysqli_error($conn)); while ($row = mysqli_fetch_array($query)) { //May need this later to output pictures // $imageURL = 'upload/'.rawurlencode($row["filename"]); $CommentText = nl2br($row['CommentText']) ; $tree=[]; $map=[]; foreach ($queryResults as &$row){ if ($row['ParentId']){ $map[$row['ParentId']]['children'][] = &$row; } else { $row['children']=[]; $tree[] = &$row; } $map[$row['id']] = &row; } $ParentComment = "" ; $replies = "" ; if (empty($row['ParentId'])) { $ParentComment .= " <div class='divTableRow'> <div class='divTableCell'>{$row['User']} <div class='pointsincommentbox'> {$row['Upvotes']}points</div> <div class='divTableComment'> $CommentText <br> <div class='divCommentLinks'> <div class='upvotes'> ⬆</div> <div class='upvotes'> ⬇</div> <div> view comment </div> <div>report </div> <div>permalink</div> <button type='button' class ='CommentChildButton'>reply</button> <div class ='OpenChildCommentBox'> $ChildCommentBoxes </div> </div> </div> </div> </div> \n"; $ParentComment .= outputPostTree($tree); } echo "$ParentComment" ; } function outputPostTree(array $tree){ echo '<ul>'; foreach ($tree as $post){ echo '<li>'.$post['CommentText']; if ($post['children']){ outputPostTree($post['children']); } echo '</li>'; } echo '</ul>'; } ?> <div class ="sidebar"> </div> </body> </html> <script> var coll = document.getElementsByClassName("collapse"); var i; for (i = 0; i < coll.length; i++) { coll[i].addEventListener("click", function() { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.display === "block") { content.style.display = "none"; } else { content.style.display = "block"; } }); } </script> <script> var coll2 = document.getElementsByClassName("CommentChildButton"); var i; for (i = 0; i < coll2.length; i++) { coll2[i].addEventListener("click", function() { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.display === "block ") { content.style.display = "none"; } else { content.style.display = "block"; } }); } </script>
  18. Hi I'm wondering how I can output nested comments. I have written a viewthread.php file that works nicely so far. From index.php it gets the IDOfThread and passes this to a $number then outputs all the comments assigned to the Thread ID However I'd like to be able to respond to each comment to create nested comments This is my viewthread.php so far <!DOCTYPE html> <html> <header> <link href="styles.css" rel="stylesheet" type="text/css" media="all"> <title>test Image Board</title> <div class="header"> <a href="index.php" class="logo">test forum online</a> <div class="header-right"> <a class="active" href="#home">Home</a> <a href="#news">News</a> <a href="#contact">Education</a> <a href="#about">Tech</a> </div> </div> </header> <body> <!-- <a href="CreateThread.php"> <h1>Create Thread</h1> </a> --> <div class ='Thread-grid-container'> <?php include 'dbconnect.php'; $number = intval($_GET['id']) ; session_start(); $_SESSION['id'] = $number ; $query = mysqli_query($conn, "SELECT * FROM Threads where id=$number") or die (mysqli_error($conn)); //Output Grid layout for a Thread post while ($row = mysqli_fetch_array($query)) { //output picture from upload folder $imageURL = 'upload/'.rawurlencode($row["filename"]); echo " <div class ='Thread-grid-item'> <div class='ThreadNumber'> Post {$row['id']}<br> </div> <div class='UserOnThread'>{$row['Users']} </div> <h2>{$row['Title']} </h2> <button type='button' class ='collapse'>Hide</button> <div class ='img-block'> <img src={$row['$imageURL']}$imageURL alt='' /> </div> <div class='bodytextThread'> <p>{$row['ThreadBody']}</p> </div> </div> \n"; }?> <div class="comment-upload-box"> <form action="CommentUpload.php" method="post" enctype="multipart/form-data"> <table> <tr> <td></td> </tr> <tr> <td>Comment: </td> <td> <textarea name="CommentText" cols="100" rows="10" > Enter your posts... </textarea> </td> <td></td> </tr> <tr> <td></td> <td><input type="submit" name='submit' value="Submit"/></td> <td></td> </tr> </table> </form> </div> <div class='divTableForComments'> <div class='divTableBody'> <?php include 'dbconnect.php'; //Output Comments onto page //Create a variable for the Comment boxes so when clicking reply a text area shows $ChildCommentBoxes = "<div class='child-comment-upload-box' style='margin-left: 48px'> <form action='ChildCommentUpload.php' method='post' enctype'multipart/form-data'> <table> <tr> <td></td> </tr> <tr> <td>Comment: </td> <td> <textarea name='ChildCommentText' cols='100' rows='10' > Enter your posts... </textarea> </td> <td></td> </tr> <tr> <td></td> <td><input type='submit' name='submit' value='Submit'/></td> <td></td> </tr> </table> </form>"; $query = mysqli_query($conn, "SELECT * FROM Posts where IDOfThread=$number") or die (mysqli_error($conn)); while ($row = mysqli_fetch_array($query)) { //May need this later to output pictures // $imageURL = 'upload/'.rawurlencode($row["filename"]); $CommentText = nl2br($row['CommentText']) ; $ParentComment = "" ; $replies = "" ; if (empty($row['ParentId'])) { $ParentComment .= " <div class='divTableRow'> <div class='divTableCell'>{$row['User']} <div class='pointsincommentbox'> {$row['Upvotes']}points</div> <div class='divTableComment'> $CommentText <br> <div class='divCommentLinks'> <div class='upvotes'> ⬆</div> <div class='upvotes'> ⬇</div> <div> view comment </div> <div>report </div> <div>permalink</div> <button type='button' class ='CommentChildButton'>reply</button> <div class ='OpenChildCommentBox'> $ChildCommentBoxes </div> </div> </div> </div> </div> \n"; } echo "$ParentComment "; } ?> <div class ="sidebar"> </div> </body> </html> <script> var coll = document.getElementsByClassName("collapse"); var i; for (i = 0; i < coll.length; i++) { coll[i].addEventListener("click", function() { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.display === "block") { content.style.display = "none"; } else { content.style.display = "block"; } }); } </script> <script> var coll2 = document.getElementsByClassName("CommentChildButton"); var i; for (i = 0; i < coll2.length; i++) { coll2[i].addEventListener("click", function() { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.display === "block ") { content.style.display = "none"; } else { content.style.display = "block"; } }); } </script> And this is what it looks like I think I would probably change the margin of the responses to jut them in a bit and am thinking the best way would be to create a function that cycles through and where it finds a ParentId of a comment matching the Posts.id it would then put this beneath it? My comments are stored in a table titled Posts and Posts looks like MariaDB [test]> describe Posts ; +---------------+-----------------+------+-----+---------------------+-------------------------------+ | Field | Type | Null | Key | Default | Extra | +---------------+-----------------+------+-----+---------------------+-------------------------------+ | id | int(6) unsigned | NO | PRI | NULL | auto_increment | | User | varchar(30) | NO | | NULL | | | PostTimeStamp | timestamp | NO | | current_timestamp() | on update current_timestamp() | | CommentText | varchar(8000) | YES | | NULL | | | IDOfThread | int(11) | YES | | NULL | | | Upvotes | int(11) | NO | | 0 | | | ParentId | int(11) | YES | | NULL | | +---------------+-----------------+------+-----+---------------------+-------------------------------+ 7 rows in set (0.002 sec)
  19. Doh... Answered my own question as I just input session_start() into my index.php and it now works as expected... I'm wondering why when login.php runs which looks like the below doesn't start the session though?! Login.php is as follows <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Login</title> <link rel="stylesheet" href="style.css"/> </head> <body> <?php require('dbconnect.php'); session_start(); // When form submitted, check and create user session. if (isset($_POST['username'])) { $username = stripslashes($_REQUEST['username']); // removes backslashes $username = mysqli_real_escape_string($conn, $username); $password = stripslashes($_REQUEST['password']); $password = mysqli_real_escape_string($conn, $password); // Check user is exist in the database $query = "SELECT * FROM `Users` WHERE User='$username' AND password='" . md5($password) . "'"; $result = mysqli_query($conn, $query) or die(mysql_error()); $rows = mysqli_num_rows($result); if ($rows == 1) { $_SESSION['username'] = $username; // Redirect to user dashboard page header("Location: index.php"); } else { echo "<div class='form'> <h3>Incorrect Username/password.</h3><br/> <p class='link'>Click here to <a href='login.php'>Login</a> again.</p> </div>"; } } else { ?> <form class="form" method="post" name="login"> <h1 class="login-title">Login</h1> <input type="text" class="login-input" name="username" placeholder="Username" autofocus="true"/> <input type="password" class="login-input" name="password" placeholder="Password"/> <input type="submit" value="Login" name="submit" class="login-button"/> <p class="link"><a href="register.php">New Registration</a></p> </form> <?php } ?> </body> </html>
  20. Hi thanks for the responses they are very informative However I am calling start_session() in login.php (login.php is run when they login) which is my question as to why the divs are not changing when I do an if(isset($_SESSION['username'])) in the index.php (main page) <?php require('dbconnect.php'); session_start(); // When form submitted, check and create user session. if (isset($_POST['username'])) { $username = stripslashes($_REQUEST['username']); // removes backslashes $username = mysqli_real_escape_string($conn, $username); $password = stripslashes($_REQUEST['password']); $password = mysqli_real_escape_string($conn, $password); // Check user is exist in the database $query = "SELECT * FROM `Users` WHERE User='$username' AND password='" . md5($password) . "'"; $result = mysqli_query($conn, $query) or die(mysql_error()); $rows = mysqli_num_rows($result); if ($rows == 1) { $_SESSION['username'] = $username; // Redirect to user dashboard page header("Location: index.php"); } else { echo "<div class='form'> <h3>Incorrect Username/password.</h3><br/> <p class='link'>Click here to <a href='login.php'>Login</a> again.</p> </div>"; } } else { however when I include the auth_session.php which is the below it DOES change the divs <?php session_start(); if(!isset($_SESSION["username"])) { header("Location: login.php"); exit(); } else { } ?> So essentially I'm trying to figure out why after I've logged in when I DO NOT include the auth_session.php the divs for Login/Register do not change to Profile? As I run the start_Session() in the index.php
  21. Back with more noob questions so I was following a page in setting up a login system and so far it works how I want except for one minor thing So I want when a user is logged into the system to see Profile div instead of Login and Register and I do that in my index.php with the following <?php if(isset($_SESSION['username'])){ echo "<div class='profile'> <a href='logout.php'>Logout</a> </div> "; } else{ echo "<div class='loginregister'> <a href='login.php'>Login</a> <a href='register.php'>Register</a> </div> "; } ?> So when a user logs in it hits the login.php which looks like this <?php require('dbconnect.php'); session_start(); // When form submitted, check and create user session. if (isset($_POST['username'])) { $username = stripslashes($_REQUEST['username']); // removes backslashes $username = mysqli_real_escape_string($conn, $username); $password = stripslashes($_REQUEST['password']); $password = mysqli_real_escape_string($conn, $password); // Check user is exist in the database $query = "SELECT * FROM `Users` WHERE User='$username' AND password='" . md5($password) . "'"; $result = mysqli_query($conn, $query) or die(mysql_error()); $rows = mysqli_num_rows($result); if ($rows == 1) { $_SESSION['username'] = $username; // Redirect to user dashboard page header("Location: index.php"); } else { echo "<div class='form'> <h3>Incorrect Username/password.</h3><br/> <p class='link'>Click here to <a href='login.php'>Login</a> again.</p> </div>"; } } else { and it starts the session_start() function whilst also allocating $_SESSION['username'] = $username so in theory when index.php loads if SHOULD (?) hit the correct if statement in the index.php file now outputting the Profile div instead of the Login and Register div. Except it doesn't. However when I include the auth_session.php at the top of my index.php file like (currently uncommented to test) //<?php //include auth_session.php file on all user panel pages //include("auth_session.php"); //?> with the Auth_session file looking like <?php session_start(); if(!isset($_SESSION["username"])) { header("Location: login.php"); exit(); } else { } ?> It does show the correct Profile div instead of the Login and Register div. So I'm trying to understand what is happening here as from the look of it the $_SESSION['username'] is allocated within login.php and the session_start() function is also started in login.php So why would I need auth_session.php to be ran in order for the correct divs to show (I've not included auth_session.php as I want people to be able to see the site that aren't logged in) Warm regards
  22. I input the error function here to see what error it's returning //Update SQL db by setting the thumbnail column to equal $Thumbnail $update = $conn->query("update Threads set thumbnail = '$Thumbnail' where filename = '$fileName'"); if($update){ $statusMsg = "Updated the thumbnail to sql correctly."; echo $statusMsg . "<br> </br>"; echo "Error : " . $_FILES['file']['error'] . "<br>"; } and the output I get is Updated the thumbnail to sql correctly. Error : Updated the thumbnail to sql correctly. Which is weird as it definitely has not updated sql correctly or uploaded the thumbnail
  23. So far I have managed to create an upload process which uploads a picture, updates the database on file location and then tries to upload the db a 2nd time to update the Thumbnails file location (i tried updating the thumbnails location in one go and for some reason this causes failure) But the main problem is that it doesn't upload some files Here is my upload.php <?php include 'dbconnect.php'; $statusMsg = ''; $Title = $conn -> real_escape_string($_POST['Title']) ; $BodyText = $conn -> real_escape_string($_POST['ThreadBody']) ; // File upload path $targetDir = "upload/"; $fileName = basename($_FILES["file"]["name"]); $targetFilePath = $targetDir . $fileName; $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION); $Thumbnail = "upload/Thumbnails/'$fileName'"; if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){ // Allow certain file formats $allowTypes = array('jpg','png','jpeg','gif','pdf', "webm", "mp4"); if(in_array($fileType, $allowTypes)){ // Upload file to server if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){ // Insert image file name into database $insert = $conn->query("INSERT into Threads (Title, ThreadBody, filename) VALUES ('$Title', '$BodyText', '$fileName')"); if($insert){ $statusMsg = "The file ".$fileName. " has been uploaded successfully."; $targetFilePathArg = escapeshellarg($targetFilePath); $output=null; $retval=null; //exec("convert $targetFilePathArg -resize 300x200 ./upload/Thumbnails/'$fileName'", $output, $retval); exec("convert $targetFilePathArg -resize 200x200 $Thumbnail", $output, $retval); echo "REturned with status $retval and output:\n" ; if ($retval == null) { echo "Retval is null\n" ; echo "Thumbnail equals $Thumbnail\n" ; } }else{ $statusMsg = "File upload failed, please try again."; } }else{ $statusMsg = "Sorry, there was an error uploading your file."; } }else{ $statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, mp4, webm & PDF files are allowed to upload.'; } }else{ $statusMsg = 'Please select a file to upload.'; } //Update SQL db by setting the thumbnail column to equal $Thumbnail $update = $conn->query("update Threads set thumbnail = '$Thumbnail' where filename = '$fileName'"); if($update){ $statusMsg = "Updated the thumbnail to sql correctly."; echo $statusMsg ; } else { echo "\n Failed to update Thumbnail. Thumbnail equals $Thumbnail" ; } // Display status message echo $statusMsg; ?> And this does work on most files however it is not working on a 9.9mb png file which is named "test.png" I tested on another 3.3 mb gif file and that failed too? For some reason it returns the following Updated the thumbnail to sql correctly.Updated the thumbnail to sql correctly. Whereas on the files it works on it returns REturned with status 0 and output: Retval is null Thumbnail equals upload/Thumbnails/'rainbow-trh-stache.gif' Failed to update Thumbnail. Thumbnail equals upload/Thumbnails/'rainbow-trh-stache.gif'The file rainbow-trh-stache.gif has been uploaded successfully. Any idea on why this is?
  24. That's great thanks, I'll have to study how this join in sql works
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.