Jump to content

TechnoDiver

Members
  • Posts

    203
  • Joined

  • Last visited

Everything posted by TechnoDiver

  1. So, I've thought about this, I really really hope to receive some input. This is my cleaned up config.php -> <?php class Database { private $dbhost = "localhost"; private $dbuser = "root"; private $dbpassword = ""; private $dbname = "qcic"; public $conn; public function __construct() { try { $dsn = "mysql:host=" . $this->dbhost . ";dbname=" . $this->dbname; $this->conn = new PDO($dsn, $this->dbuser, $this->dbpassword); } catch(PDOException $exception) { die("DB connection failed: " . $exception->getMessage()); } // $conn = $this->conn; return $this->conn; } } ob_start(); session_start(); $timezone = date_default_timezone_set("America/Cancun"); $whitelist = array('username', 'email', 'email2', 'password', 'password2'); $table = 'users'; $conn = new Database(); ob_end_flush(); I'm still getting that $conn is unassigned from my other classes. Could this be because the db queries in those classes are in mysql and the connection was made in PDO?
  2. Yea, I've tried that and don't get the type error either, but with that amended code returning $conn now the other classes aren't picking up the $conn anymore. But like I said, the commented out code in my first OP works, and I haven't changed the location of anything, just commented out one section and wrote another. That's why I'm sure it's correct. Unless I'm overlooking something. the path to config.php is /opt/lampp/config/config.php and the path to load.php is /opt/lampp/htdocs/site/load.php. I didn't just make this file today, I've been using it for months on that path name But something is beyond my understanding because returning $conn isn't connecting to the other classes. I don't know why putting pretty much the same code into a class has caused so much chaos
  3. I caught that while messing around with it earlier I've modified it to this -> class Database { private $dbhost = "localhost"; private $dbuser = "root"; private $dbpassword = ""; private $dbname = "qcic"; public $conn; public function __construct() { try { $dsn = "mysql:host=" . $this->dbhost . ";dbname=" . $this->dbname; $this->conn = new PDO($dsn, $this->dbuser, $this->dbpassword); } catch(PDOException $exception) { die("DB connection failed: " . $exception->getMessage()); } $conn = $this->conn; return $conn; } } but it still doesn't work, any idea why??
  4. As it's been recommended numerous times I've started using/learning PDO. So starting from the beginning I've decided to start refactoring my project using it. Attempting to write a database class has got me stuck and I don't know why. In the following code I'm going to leave in my former, commented out code as well. This is the change I've made to my config file which is located (I'm using XAMPP) in /opt/lampp. Outside my root directory. The commented out code works fine, so this isn't an issue of an improper path name <?php // ob_start(); // session_start(); // $timezone = date_default_timezone_set("America/Cancun"); // $whitelist = array('username', 'email', 'email2', 'password', 'password2'); // $table = 'users'; // $conn = mysqli_connect('localhost', 'root', '', 'qcic'); // if($conn->connect_errno) { // printf("Connect Failed: %s\n", $conn->connect_error); // exit(); // } // ob_end_flush(); class Database { private $dbhost = "localhost"; private $dbuser = "root"; private $dbpassword = ""; private $dbname = "qcic"; private $conn; public function __construct() { try { $dsn = "mysql:host=" . $this->dbhost . ";dbname=" . $this->dbname; $this->conn = new PDO($dsn, $this->dbuser, $this->dbpassword); } catch(PDOException $exception) { die("DB connection failed: " . $exception->getMessage()); } } } I call the Database class here, in a file named load.php -> <?php require_once($_SERVER['DOCUMENT_ROOT'] . '/../config/config.php'); $db_obj = new Database(); The issue is that Database is coming back as "undefined type 'Database'". The require_once path is definitely the right path. Can someone tell me what the issue is, please?
  5. Thank you, I didn't even think about it being part of a string. Makes complete sense and it resolved the issue, thanks again
  6. I am only using them for table names between the classes, but thank you Your solution worked. Could you explain to me why it works and the other way doesn't? thanks
  7. I wish I could have edited this comment so apologies for back to backs. I decided to make an instance variable to use in the methods of the class itself and keep the static for other classes that need that table. And see if that would work. -> <?php class Post { private $conn; private $user_obj; public static $table = "posts"; public function __construct($conn, $username) { $this->conn = $conn; $this->user_obj = new User($conn, $username); $this->table = self::$table; //$this->table = "posts"; } And I thought this was a great idea; but I'm getting Notices that of trying to access a static property as non static. I'm using public function getBreakingNews() { $query = mysqli_query($this->conn, "SELECT * FROM $this->table WHERE type='breaking' ORDER BY RAND()"); It's confusing to me why it says that. It means (to me) that '$this->table' and 'self::$table' aren't separated entities. My understanding was that $this referred to the instance and 'self' referred to the class. So why are places that I've instantiated it at giving me this message? I don't understand it and it's nothing an answer you can readily resolve on search engines. Hoping someone can break this down for me
  8. Good morning Freaks, I hope you're all having a productive week. I've a question about an issue I'm having accessing static properties. I've been doing some reading on them but haven't yet deployed one successfully. I have a bunch of classes and I want to make the database query tables all static so they can be used cross-class, so to speak. Here's a sample attempt -> class Post { private $conn; private $user_obj; public static $table = "posts"; public function __construct($conn, $username) { $this->conn = $conn; $this->user_obj = new User($conn, $username); // $this->table = "posts"; } and accessing it here -> public function getBreakingNews() { $query = mysqli_query($this->conn, "SELECT * FROM self::$table WHERE type='breaking' ORDER BY RAND()"); This gets me an error that $table doesn't exist as does using Post::$table. When I assign $this->table = 'posts' (the commented out line in __construct) and access it by $this->table all works great. What am I doing wrong that it won't find that public static property? In the manual there's this example, which I feel like I've stayed true to -> class Foo { public static $my_static = 'foo'; public function staticValue() { return self::$my_static; } } ..... print Foo::$my_static . "\n"; The only difference I see is that they're printing the value and I'm trying to use it in a database query. Can anyone guide me through this mistake I'm apparently making and can't see? I've tried both self::$table and Post::$table, self::table and Post::table, every permutation I can think of but still the variable is saying it's unassigned. Share your knowledge please
  9. yea, I understand that, but I felt it wasn't about specific code and more about general advice. If it was in the wrong forum, I apologize.I feel I should only have required $user in specific methods as well. These are growing pains
  10. Hi Freaks, I'm looking for advice if someones willing to give it. Here's the situation -> I've been working on a project, I started to learn PHP specifically to complete this idea I had. My code has evolved a lot over time as I've started understanding more. Up until today I've been working on it with just the registration functionality, no login. I had my username hardcoded into the $user_obj instantiation. I decided I wanted to try to make category subscription functionality and doing that I realized I was better off finishing the login form first so as to get a users subscriptions into a session variable at login. This has brought about the issue of getting an unassigned variable warning from the User class when not logged in. How I made all my other classes was putting a $user in the __construct parameter for each class. I now feel this may have been a rookie error since I'm having problems with error messages especially undefined array keys and variables when there isn't a session started. It's become a bit of a mess. So the advice I'm looking for and hoping to find here is how you folks handle non $_SESSION sessions, when a user is just scrolling the site not logged in. Did I make a mistake requiring $user for each class __construct? should I move the $user parameter to only the methods that require them? Is there a simpler solution that my inexperience causes to elude me? What would you folks do in this situation?
  11. I was just researching how to make a proper logout form, seems easy enough. I noticed that a lot of the examples started with session_start(). Are they saying to start it again before destroying it? I don't understand those examples, also a few examples didn't even destroy it but just unset() everything. I also moved my session_start() from config.php to my login handler, it seemed more logical to me. So 2 questions: What IS the proper way to handle a logout - a) start session again to destroy it right away b) just destroy it c) simply unset everything? My heart chooses b) but I've been wrong many times with things that I thought made sense. Also, the session_start() - config.php or login.php? Is there a performance or security difference I should be considering? Good weekend to you all. TIA for responses.
  12. I tried this with bootstrap cols actually and didn't work. It's from a template and I wasn't familiar with flex. I'm reading about it now, thanks
  13. CSS in one of my nightmares, it is the one thing that causes me the most frustration. I have a question for those who are a bit more graceful with it than I am - I have a comment area in a practice project, it looks like this -> <div class="comment-content d-flex"> <div class="comment-author"> <img src="img.jpg" alt="author"> </div> <div class="comment-meta"> <a href="#" class="post-author">Commenter Name</a> <a href="#" class="post-date">Comment date</a> <p>Donec turpis erat, scelerisque id euismod sit amet, fermentum vel dolor. Nulla facilisi. Sed pellen tesque lectus et</p> </div> <!-- I added this area myself <div class='d-flex align-items-center'> <a href='#' class='comment-like'><span><i class="fa fa-thumbs-up"></i> like</span></a>&nbsp;&nbsp; <a href='#' class='comment-respond'><span><i class="fa fa-comment"></i> respond</span></a> </div> --> </div> in the area that I commented that I added myself .comment-like and .comment-respond are not yet defined. At the moment it flows to the right of the comment area and I want them below it. Easy enough to do with positioning except that I need it to be positioned relative to the content of the comment that it belongs to. This whole block will eventually be echoed from a PHP class but I like to get the styling and html correct on the page it will display on first (probably like most people). Can I get some advice on the best way to resolve this issue from you folks please. TIA
  14. Yea, that all makes sense. And yea sometimes things don't stick the first time depending on my state of mind when hearing it and learning a lot at once. I often have to come back here to look into old questions I asked that I only have a vague memory of asking about the first time. Thank you, all Would any of you fine freaks have suggestions or some good links where I can start researching how to allow users to use markup and/or HTML in their submissions and how to handle all that going to and from the database?
  15. Not done yet, but aware that it needs to be. I'm still in that linear way of thinking that pieces together as I go and trying to get to a broader cyclical way of seeing an app. Thanks for commenting. I must have misunderstood my read-up on nl2br(). I also did not know that about mysqli_real_escape_string(). What are normally the proper 'sanitizing' functions to use before sending text data TO a database?
  16. I"ve resolved this. The solution was changing if($statement) { $statement->execute(); } to if($statement) { $statement->execute(); return true; } So the issue has been resolved but I don't quite understand why the top statement doesn't return true by default EDIT: Thanks Kicken, I saw the notification for you comment as I was typing my resolution. I appreciate your effort anyways You also helped me understand why the 'return true;' line isn't redundant like it seemed.
  17. yea yea, it sends all data to the database. It's only this one part that's not working. If you tell me that it can send the date to the database and still return false I'll have to reevaluate everything I thought I understood about PHP lol Here's the addComment method if it helps public function addComment($id, $name, $email, $body) { if(!empty($body) && !empty($email)){ $name = strip_tags(mysqli_real_escape_string($this->conn, $name)); $email = strip_tags(mysqli_real_escape_string($this->conn, $email)); $body = nl2br(mysqli_real_escape_string($this->conn, $body)); $statement = $this->conn->prepare("INSERT INTO comments ( post_id, username, email, body ) VALUES (?,?,?,?)"); $statement->bind_param('isss', $id, $name, $email, $body); if($statement) { $statement->execute(); } }
  18. Hi again, Freaks, hope you've all been well. I have what I would have considered a simple problem if not for the trouble it's giving me. I have the following bit -> <?php if(!$message) : ?> <h4>Leave a comment</h4> <?php else : ?> <div class='success'> <p class='bg-success text-center'>We have your comment and it will be added after approval</p> </div> <?php endif; ?> this code is obviously in the body of the page. At the top I have this -> <?php require("assets/initializations.php"); $post_obj = new Post($conn, $user); //simply increase #views per page load if(isset($_GET['post_id']) && !empty($_GET['post_id'])) { $id = $_GET['post_id']; $query = mysqli_query($conn, "SELECT * FROM news WHERE id=$id"); $row = mysqli_fetch_array($query); $category = $row['post_category']; $views = $row['num_views']; $views ++; mysqli_query($conn, "UPDATE news SET num_views='$views', time_stamp=NOW() WHERE id=$id"); //comment to db $message = false; if(isset($_POST['submit'])) { mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT); $comment_obj = new Comment($conn); if($comment_obj->addComment($id, $_POST['name'], $_POST['email'], $_POST['comment'])) { $message = true; } } } ?> Everything works fine except I can't get the body if statement to show anything other "Leave a Comment". The comment gets to the database but the success message won't show. I've tried this various ways before using this format. I assigned the $message up top and tried echoing it in the body. I then tried ternary style. Then I remembered that I had to do the same thing months ago when I made the registration form. So I decided to try that style here. The code from the register.php is this -> <?php if(!empty($errors)) : ?> <div class="errors"> <p class="bg-danger text-center"><?php echo implode( '</p><p class="bg-danger text-center">', $errors ); ?></p> </div> <?php elseif($sent) : $js_switch = true; ?> <div class="success"> <p class="bg-success">You've been successfully registered. Login and enjoy the network.</p> </div> <?php endif; ?> This code works great and is why I decided to do the same on my current issue, but nothing that I do gets "Leave a Comment" to change to the success message. Is there some obscure rule of PHP I've overlooked? I really can't figure out why the bit I'm working on now isn't working correctly like that bit I copied it from. Thanks for all responses
  19. I'm pretty new to PHP too and I'm not sure if you've figured out some of you issues yet, but in the spirit of trying to contribute more I'll add my two cents. All those if(isset) statements should be filtered down to one if(isset) that refers to - think of the form element that submits data - and then try to assign your variables within. happy learning
  20. Yea, I thought about going down that road but I'm not sure it's the way that I want to go. There's already a login and registration form and I have users 'roles' saved in the database. I'm looking for some direction on users just logging in normally and having access dependent on their role (security clearance, so to speak). And I have that except for the URL vulnerability and was looking for a different way. Do you happen to have a different ideas I can look into??
  21. Hi Freaks, I have an admin area to a project I'm working on. No links show up for it anywhere on the site if the logged in user isn't an 'admin'. But I realized that it can still be accessed through the URL. Any guidance on the correct, most secure methods to disallow this? Thanks
  22. Yea, this is exactly what I'm trying. So here's one example method -> public function getBreakingNews() { $query = mysqli_query($this->conn, "SELECT * FROM news WHERE type='breaking' ORDER BY RAND()"); $str = ""; while($row = mysqli_fetch_array($query)) { $id = $row['id']; $title = $row['title']; if(strlen($title) > 25) { $title = substr($title, 0, 25) . "..."; } $content = $row['content']; // if(strlen($content) > 200) { // $content = substr($content, 0, 200) . "..."; // } $added_by = $row['add_by']; $category = ucwords($row['post_category']); $cat_id = $row['post_cat_id']; $image = $row['post_image']; $likes = $row['num_likes']; $comments = $row['num_comments']; $date_added = $row['date_added']; $current_datetime = date("Y-m-d H:i:s"); $start_count = new DateTime($date_added); $end_count = new DateTime($current_datetime); $interval = $start_count->diff($end_count); if($interval->h <= 8 && $interval->d < 1) { $str .= " <div class='single-blog-post small-featured-post d-flex'> <div class='post-thumb'> <a href='single_post.php?post_id=$id&related=$category'><img src='img/posts/$image' alt=''></a> </div> <div class='post-data'> <a href='category_posts.php?cat_id=$cat_id&cat_title=$category' class='post-category text-size-6'>$category</a> <div class='post-meta'> <a href='single_post.php?post_id=$id&related=$category' class='post-title'> <h6>$title</h6> </a> <p class='post-date'><span>$date_added</span></p> </div> </div> </div>"; } } It's ugly, I know, but it's first draft code from a first draft coder. It's also redundant. Initially all these methods are assigning properties from the db query $row array. Now I've made it so any data coming from the form is in Post __construct(). This was in response to reading about the double colon to use properties from other classes. What I'm working on now is just moving the HTML echo from $str into a Display class. You can see where there are the PHP variables with the HTML. When I copy this HTML over to the Display class it doesn't have immediate access to those variable definitions anymore, so they're all considered unassigned. Here's a portion of the Display class with the corresponding method for the HTML above.as I was working on it last night -> require("Post.php"); class Display { private $classname = "Post"; private $title = $classname::$title; private function __construct($loc_code) { $this->loc_code = $loc_code; } //loc_code #1 private function breakingDisplay() { $html = "<div class='single-blog-post small-featured-post d-flex'> <div class='post-thumb'> <a href='single_post.php?post_id=$id&related=$category'><img src='img/posts/$image' alt=''></a> </div> <div class='post-data'> <a href='category_posts.php?cat_id=$cat_id&cat_title=$category' class='post-category text-size-6'>$category</a> <div class='post-meta'> <a href='single_post.php?post_id=$id&related=$category' class='post-title'> <h6>$title</h6> </a> <p class='post-date'><span>$date_added</span></p> </div> </div> </div>"; echo $html; } The methods are private because there will be only one Public method in Display - the one that chooses which Private method to use depending on which $loc_code is passed. Here, I've only yet tried assigning the $title property. The line private $title = $classname::$title; tells me $title has been assigned but not used, but it's clearly used in the HTML. I imagine the same thing will happen with the rest so haven't spent time on them yet. This is what I'm working on now. My original question was slightly different. Originally I was asking if it was possible to 'escape' the HTML variables in Display until they needed to be used in Post. So that's my situation right now. I love advise and guidance and appreciate it all. What I really need is a good resource on moving data between objects and classes, this is something I don't yet have total comfort with, if anyone has any links/resources like that.
  23. Ok, thanks for that link interesting read I definitely see where I can make use of that. Let me ask you something though, and I think I can explain without posting too much code. I have a Post class. In it there are multiple methods for displaying different types of posts. Column names from the database are assigned to property variables and the each method loops through a while loop and echos the appropriate html with the variable/properties ($title, $content, $image etc) inserted in the HTML for where the post is located on the site. It was sloppy and dirty and I needed to clean it up so I've made a Display class whose methods each only echo the relevant html and nothing else. Now as I've moved the HTML from the Post class to the Display class those variables that are inserted in the HTML have become a problem. Not a problem but an issue I have to deal with. In the Display class they all have to red squiggly error lines because they're not defined in that class. The thing is that the Display class doesn't really use them, they're only ever actually used in the Post class because that's where they're initiated. So I don't know the best way to deal with them as defining them all again in Display seems really redundant and doesn't feel right. Is there a way to 'escape' them while they're in the Display class and only get defined once they've made it to the Post class?
  24. I'm looking for some insight on where/how to look something up. I have a Post class and it's really messy so I'm trying to clean it up. There's a method - createPost() - that takes in 8 parameters from a form, does what's needed to them to prepare them for database and creates 7 more properties, as well. For a total of 15 fields being sent to the database. I want to create a sendPost() method to handle this. In creating this method I realized that all these parameters look and feel burdensome and there's no real connection between the 2 methods other than sharing a class. I'd like to look into how to make sendPost take however many of parameters from whichever method it's called for without always having to pass the same amount. So for example if sendPost is being called with createPost than it has to handle 15 parameters, but, later, if I want to call sendPost on an editPost method, for example, it may only need to send 6 parameters back to the database meaning the other 9 would have to be redundantly passed again. I seem to recall from Python years ago there was a way to do this but I can't remember and I really don't know what to even search for to research it. Any direction or resources or advice that anyone could share would be really helpful and appreciated. Thanks
  25. yea, and I can't get rid of them. It's strange nothing is working in textareas I still get the \r\n and also all the break tags as well (<br />). This uses a function to pull the posts from the database and then echos an html string with the properties inserted. It works fine if I just $content = $row['content']; except it's riddled with /r/n. Neither one of the ways I've used (str_replace & preg_replace) works. I'm stumped, I feel this is exactly the type of thing these functions were made for and can't imagine why they wouldn't work.
×
×
  • 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.