-
Posts
480 -
Joined
-
Last visited
-
Days Won
13
Everything posted by Strider64
-
Question about using a database connection class
Strider64 replied to kenoli's topic in PHP Coding Help
This is how I do it: My Database Class: <?php namespace Miniature; use PDO; class Database { private $_connection; // Store the single instance. private static $_instance; // Get an instance of the Database. // @return Database: protected static function getInstance(): Database { if (!self::$_instance) { self::$_instance = new self(); } return self::$_instance; } public static function pdo(): PDO { $db = static::getInstance(); return $db->getConnection(); } // Constructor - Build the PDO Connection: public function __construct() { $db_options = array( /* important! use actual prepared statements (default: emulate prepared statements) */ PDO::ATTR_EMULATE_PREPARES => false /* throw exceptions on errors (default: stay silent) */ , PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION /* fetch associative arrays (default: mixed arrays) */ , PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ); $this->_connection = new PDO('mysql:host=' . DATABASE_HOST . ';dbname=' . DATABASE_NAME . ';charset=utf8', DATABASE_USERNAME, DATABASE_PASSWORD, $db_options); } // Empty clone magic method to prevent duplication: private function __clone() { } // Get the PDO connection: public function getConnection(): PDO { return $this->_connection; } } Then I simple do this is my other classes (a small snippet) -> public function update(): void { /* Initialize an array */ $attribute_pairs = []; /* Create the prepared statement string */ foreach (static::$params as $key => $value) { if($key === 'id') { continue; } // Don't include the id: $attribute_pairs[] = "{$key}=:{$key}"; // Assign it to an array: } /* * The query/sql implodes the prepared statement array in the proper format * and I also hard code the date_updated column as I practically use that for * all my database table. Though I think you could override that in the child * class if you needed too. */ $sql = 'UPDATE ' . static::$table . ' SET '; $sql .= implode(", ", $attribute_pairs) . ', date_updated=NOW() WHERE id =:id'; /* Normally in two lines, but you can daisy chain pdo method calls */ Database::pdo()->prepare($sql)->execute(static::$params); } Though looking at the Database class the code possibly could be tighten up just a tad, but I have been refining it over the years. -
I will chime in with my thoughts. I bet most of your website could be fixed to look good on mobile devices by doing some CSS tweaks. It doesn't have to look the greatest as all it needs to look good. Here's what I do, first for all browsers including mobile: /*-------------------------------------------------------------- Basic responsive layout for all browsers: --------------------------------------------------------------*/ .site { background-color: #fff; max-width: 75em; margin: 0 auto; } Then inside a media query for modern browsers (Firefox, Chrome for PCs) .site { max-width: none; display: grid; grid-template-columns: 1fr auto 1fr; grid-template-rows: auto; grid-gap: 0; } Sure it isn't going to look as polished as some of the major sites that you see, but people will be able to see comments and other thing information in a nice pleasing style that goes from edge to edge that is one right after another down the screen when they scroll. You and always go back to the restyling for mobile if you so decided to. BTW the .site class is in the HTML <body> tag.
-
My opinion using grid and flex together would do the trick. Though you could even even accomplish with just flex, but it gets a little tricky if you have to change the number of columns. Though you can fix that problem using JavaScript.
-
Well, I find syntax bugs to be a pain when you have logic errors on top of them. You fix all the syntax bugs and you code doesn't work the way you expect it to then you feel like you just wasted a couple hours of work, plus you feel like banging you head against the desk. The best way to learn PHP in my opinion is to learn the code syntax properly by going to php.net and following tutorials. An IDE is just away to debug syntax errors more quickly in order for you to concentrate on the logical errors. That's my opinon.
-
I don't know if I'm on the right track and I use DateTime(), but I'm sure it can be done with date as well. <?php $firstMonday = new DateTime("January 1, 2021", new DateTimeZone("America/Detroit")); if ($firstMonday->format("l") === "Sunday") { $firstMonday->modify("last Monday"); echo $firstMonday->format("F j, Y -l") . "<br>"; } else { $firstMonday->modify("Monday"); echo $firstMonday->format("F j, Y -l"); }
-
How Can I Teach My Child JavaScript Programming?
Strider64 replied to annetrose's topic in Javascript Help
I agree learning a basic programming language services is a great foundation in learning other programming languages. I'm 56 years and when I first was learning programming I was had a class in Pascal (I think that was the language) that set the tone for other languages. After learning the first language I would suggest learning C+ as that programming language is very similar to a lot of languages that will make you say I seen that before and then realize it was C+. It doesn't have to be that in-depth learning C+ as getting the basics would be enough in my opinion. -
Display single blog post from db in php mvc
Strider64 replied to sidekick's topic in PHP Coding Help
Personally I just redirect to another php file if a certain about of text should only be displayed. I do it like the following: public function getIntro($content = "", $count = 200, $pageId = 0) {; $this->content = (string) $content; return substr($this->content, 0, (int)$count) . '<a class="moreBtn" href="mainArticle.php?page=' . (int)$pageId . '"> ...more</a>'; } If I want to have is stay on the same page I simply would just introduce vanilla javascript. (Which I might after I get done overhauling my website) I just simply display a page like this public function page($id) { $this->query = 'SELECT id, user_id, author, page, post, page, thumb_path, path, Model, ExposureTime, Aperture, ISO, FocalLength, heading, content, DATE_FORMAT(date_added, "%W, %M %e, %Y") as date_added, date_added as myDate FROM cms WHERE id=:id'; $this->stmt = static::pdo()->prepare($this->query); $this->stmt->execute([':id' => $id]); $this->result = $this->stmt->fetch(PDO::FETCH_OBJ); return $this->result; } It doesn't matter what page the class is on, just as long as it has the id (page id) of the database table record. I use pagination for control multiple records that I want to display on a website page. Which is relatively easy to do/setup and something that you might look into if you are develop a blog. I used to try to setup a MVC, but found it more of a hassle than what it was worth when developing a simple CMS/Blog page. -
Personally I wouldn't start off learning PDO by doing try-catch statements as in my opinion will cause more confusion than it is worth. Simply have error reporting turned on to catch the errors. I personally don't like writing foreach statements that way, I would write it something like the following: <?php foreach ($result as $text) { echo '<blockquote>'; echo '<p>' . htmlspecialchars($text['joketext']) . '</p>'; echo '</blockquote>'; } ?> as for the pdo I would do something like the following: $db_options = array( /* important! use actual prepared statements (default: emulate prepared statements) */ PDO::ATTR_EMULATE_PREPARES => false /* throw exceptions on errors (default: stay silent) */ , PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION /* fetch associative arrays (default: mixed arrays) */ , PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ); $pdo = new PDO('mysql:host=' . DATABASE_HOST . ';dbname=' . DATABASE_NAME . ';charset=utf8', DATABASE_USERNAME, DATABASE_PASSWORD, $db_options); $stmt = $pdo->query('SELECT joketext FROM joke'); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); I haven't tested the above out, so I don't know how correct it is. I would look at this link -> https://phpdelusions.net/pdo as it explains it pretty good in my opinion and I still refer to it from time to time myself.
-
I know it would mean basically starting over, but something like this is screaming pagination. Here's a small cms example using pagination for my website: /* * Pagination Code */ $current_page = htmlspecialchars($_GET['page'] ?? 1); // Current Page Location: $per_page = 3; // Total articles per page $total_count = $journal::countAll(); // Totoal articles in database table: $pagination = new Pagination($current_page, $per_page, $total_count); Here's the Pagination Class: <?php namespace Miniature; use PDO; use Miniature\Database as DB; class Pagination extends Journal { public $currentPage; public $perPage; public $totalCount; public $result = \NULL; protected $query = \NULL; protected $stmt = \NULL; public function __construct($currentPage = 1, $perPage = 20, $totalCount = 0) { $this->currentPage = (int) $currentPage; $this->perPage = (int) $perPage; $this->totalCount = (int) $totalCount; } public function offset() { return $this->perPage * ($this->currentPage - 1); } public function totalPages() { return ceil($this->totalCount / $this->perPage); } public function previousPage() { $prev = $this->currentPage - 1; return ($prev > 0) ? $prev : false; } public function nextPage() { $next = $this->currentPage + 1; return ($next <= $this->totalPages()) ? $next : false; } public function previousLink($url = "") { $link = ""; if ($this->previousPage() != false) { $link .= "<a class=\"menuExit\" href=\"{$url}?page={$this->previousPage()}\">"; $link .= "« Previous</a>"; } return $link; } public function nextLink($url = "") { $link = ""; if ($this->nextPage() != false) { $link .= "<a class=\"menuExit\" href=\"{$url}?page={$this->nextPage()}\">"; $link .= "Next »</a>"; } return $link; } public function numberLinks($url = "") { $output = ""; for ($i = 1; $i <= $this->totalPages(); $i++) { if ($i == $this->currentPage) { $output .= "<span class=\"selected\">{$i}</span>"; } else { $output .= "<a class=\"menuExit\" href=\"{$url}?page={$i}\">{$i}</a>"; } } return $output; } public function pageLinks($url) { $output = ""; if ($this->totalPages() > 1) { $output .= "<div class=\"pagination\">"; $output .= $this->previousLink($url); $output .= $this->numberLinks($url); $output .= $this->nextLink($url); $output .= "</div>"; } return $output; } public function readPage() { $this->query = 'SELECT id, user_id, author, page, thumb_path, path, post, page, Model, ExposureTime, Aperture, ISO, FocalLength, heading, content, DATE_FORMAT(date_added, "%M %e, %Y") as date_added, date_added as myDate FROM cms ORDER BY myDate DESC LIMIT :perPage OFFSET :blogOffset'; $this->stmt = static::pdo()->prepare($this->query); // Prepare the query: $this->stmt->execute([':perPage' => $this->perPage, ':blogOffset' => $this->offset()]); // Execute the query with the supplied data: $this->result = $this->stmt->fetchAll(PDO::FETCH_OBJ); return $this->result; } } Just some food for thought or maybe some ideas on how to fix the code?
-
Throw that in file 13 and look for a safe secure login using PDO (My Suggestion) or mysqli. I did a Google search and found this https://levelup.gitconnected.com/how-to-build-a-secure-login-page-in-php-954f51d08701 and I am sure there are many others out there.
-
Checkout https://www.php.net/manual/en/datetime.format.php it should get you on the right track.
-
This can also be achieved by simply using HTML and CSS. I have done it plenty of times and you don't even need javascript though using javascript you could give some flare to it.
-
What's the purpose of having a form if there's no submit button?
-
Another nice 3rd Party email is Swiftmailer Swiftmailer I personally found it easier to setup though PHPMailer is just a good.
-
How does csrf token add security for form submission?
Strider64 replied to colap's topic in PHP Coding Help
Well, when the user first visit a website the token is generated and stored in sessions then when he/she submits his information in a form the token is sent along with the info. That way it has to be her/him that enter the data from that browser and the only way it can theoretically happen to be another user would be that user would have to use the same browser on that computer. For more info check out -> https://owasp.org/www-community/attacks/csrf -
You're still trying to paddle upstream without a paddle. My suggestion would to be look at a CURRENT tutorial on adding, updating, and deleting data to a database table. I would also suggest PDO instead of mysqli as I feel it's more robust, but that is a personal preference. I like this PDO tutorial as they do a nice job explaining how PDO works : https://phpdelusions.net/pdo
-
How do I get average user count based on each day?
Strider64 replied to imgrooot's topic in PHP Coding Help
I probably should had explain better. I would just take a range of dates (for example of week in an array) and loop through the dates. Unless it's important to save the data (which I personally don't there would be) then just store that data in another database table. -
How do I get average user count based on each day?
Strider64 replied to imgrooot's topic in PHP Coding Help
If I was tackling the problem I would do something like this: $stmt = static::pdo()->prepare("SELECT count(user_id) FROM users WHERE joined_date = ?"); $stmt->execute(['joined_date']); $result = $stmt->fetchColumn(); return $result; then I would either cycle through the database table with some kind of loop or set up a daily maintenance routine where I store the results. Of course you can do averages or what have you as it's just simple math in either case. The first option is what I would do as I wouldn't have to go about storing and setting up additional stuff. -
I find sending NON-HTML emails have a better chance of getting through spam filters than HTML emails. Sure they don't look as flashy, but it's the content that matters. 😉
-
I personally would make the flow a little easier to follow: here's my example: /* * Database Connection * I would have the PDO database connection in a separate file (Something like inc.pdoConnect.php) * and then call it something like require_once "includes/inc.pdoConnect.php"; */ $db_options = [ /* important! use actual prepared statements (default: emulate prepared statements) */ PDO::ATTR_EMULATE_PREPARES => false /* throw exceptions on errors (default: stay silent) */ , PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION /* fetch associative arrays (default: mixed arrays) */ , PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ]; $pdo = new PDO('mysql:host=' . DATABASE_HOST . ';dbname=' . DATABASE_NAME . ';charset=utf8', DATABASE_USERNAME, DATABASE_PASSWORD, $db_options); /* End of Connection String */ /* I would personally only be pulling out table column names instead of the wildcard * */ $query = "SELECT * FROM convoy_part WHERE us_convoy=:get_id"; $stmt = $pdo->prepare($query); $stmt->execute([':get_id' => $_GET['id']); // I personally would have something like uniform :convoy_id / $_GET['convoy_id] $result = $stmt->fetchALL(PDO::FETCH_ASSOC); echo "<pre>" . print_r($result, 1) . "</pre>"; // Great way to debug and see what is going on: /* I personally like using the fetch statement over the while statement */ foreach ($result as $results) { $convoy_name = $results['convoy_name']; $convoy_veranstalter = $results['convoy_veranstalter']; $convoy_server = $results['convoy_server']; $convoy_date = $results['convoy_date']; $convoy_adddate = $results['convoy_adddate']; $convoy_language = $results['convoy_language']; $convoy_participants = $results['convoy_participants']; } Make sure you have error reporting turned on ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); It will help you debug your code easier.
-
Make sure you have error reporting on - ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); If that isn't working then your local server isn't set up right. To test if you local server is working properly create a php info file. <?php // Show all information, defaults to INFO_ALL phpinfo();
-
I use SwiftMailer, but I don't bother to send the email and going through all the hassle of sending the email until I verify the user with Google's recaptcha. /* The Following to get response back from Google recaptcha */ $url = "https://www.google.com/recaptcha/api/siteverify"; $remoteServer = filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_SANITIZE_URL); $response = file_get_contents($url . "?secret=" . PRIVATE_KEY . "&response=" . \htmlspecialchars($_POST['g-recaptcha-response']) . "&remoteip=" . $remoteServer); $recaptcha_data = json_decode($response); /* The actual check of the recaptcha */ if (isset($recaptcha_data->success) && $recaptcha_data->success === TRUE) { $success = "Mail was sent!"; $data['name'] = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_FULL_SPECIAL_CHARS); $data['email'] = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL); $data['phone'] = filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_FULL_SPECIAL_CHARS); $data['website'] = filter_input(INPUT_POST, 'website', FILTER_SANITIZE_FULL_SPECIAL_CHARS); $data['reason'] = filter_input(INPUT_POST, 'reason', FILTER_SANITIZE_FULL_SPECIAL_CHARS); $data['comments'] = filter_input(INPUT_POST, 'comments', FILTER_SANITIZE_FULL_SPECIAL_CHARS); $send = new Email($data); } else { $success = "You're not a human!"; // Not of a production server: }
-
Personally I would just populate the table and if you want people to edit the comments use a HTML anchor tag: You can then either redirect the edit to another HTML page and/or use some form of Javascript/Ajax on the anchor tag. That's what I did with my small blog that I wrote for my website: <?php foreach ($journal as $cms) { ?> <div class="article"> <h2><?= $cms->heading; ?> <span class="subheading">by <?= $cms->author ?> on <?= $cms->date_added ?></span></h2> <a class="myLightBox" href="<?= $cms->image_path; ?>" title="Picture Gallery" data-picture="<?= $counter ?>" data-exif="<?php if (!is_null($cms->Model)) { echo $cms->Model . " --- " . $cms->FocalLength . " --- " . $cms->Aperture . " --- " . $cms->ISO . " --- " . $cms->ExposureTime; } ?>"><img class="editPic" src="<?= $cms->thumb_path; ?>" alt="Picture for Journal Entry"></a> <hr> <p><?php echo nl2br($cms->content); ?></p> <a class="btn3" href="edit.php?article_id=><?= $cms->id; ?>">Edit</a> <a class="btn3" href="delete_entry.php?id=<?= $cms->id; ?>" data-confirm="Do you really want to delete this item?">Delete</a> <hr> </div> <?php $counter += 1; } ?> I just find it cleaner and easier to understand.
-
I personally switched back to vanilla javascript as it really isn't all that much harder to write and it doesn't use a library. Nothing wrong in with jQuery, but I was always wondering about the javascript equivalent when it came to certain coding. Now I don't have to wonder. I do say people who are just learning javascript should learn vanilla javascript before tackling jQuery as it will make life much simpler if you ever need just to use vanilla javascript. That was my problem as I really didn't learn vanilla js before I tackled jQuery.