Jump to content

Strider64

Members
  • Posts

    466
  • Joined

  • Last visited

  • Days Won

    12

Everything posted by Strider64

  1. You're not echoing out the content <h4><?php the_title(); ?> </h4> should be <h4><?php echo the_title(); ?> </h4> /* or this */ <h4><?= the_title() ?> </h4>
  2. e.preventDefault() will stop the HTML button from firing: submit.addEventListener('click', (e) => { e.preventDefault(); sendEmail.phone = phone.value; sendEmail.website = website.value; sendEmail.response = submit.getAttribute('data-response'); if (sendStatus.name && sendStatus.email && sendStatus.comments) { saveRequest(sendUrl, sendUISuccess, sendUIError); } else { notice.style.display = "block"; notice.textContent = "Name, Email, and Message Required!"; } }, false);
  3. If the code doesn't work, but the only solution is to use arrays then learning about arrays is probably only option? There's a reason why the code stopped working and that is you added extra conditions to the script. Instead of single images there are now multiple images? (I'm assuming and you know what they say about assuming. 😃) Learning arrays isn't that tough. It is one of the first things that is taught in any coding language.
  4. Well, it's not actually cropping, but resizing function that I wrote and I have been testing it out on my website. So far it's been working like I expect it to. Though I imagine you could modify the script to do cropping? <?php function imageResize($imageSrc, $imageWidth, $imageHeight, $newImageWidth, $newImageHeight): GdImage|bool { $newImageLayer = imagecreatetruecolor($newImageWidth, $newImageHeight); imagecopyresampled($newImageLayer, $imageSrc, 0, 0, 0, 0, $newImageWidth, $newImageHeight, $imageWidth, $imageHeight); return $newImageLayer; } function resize($file_temp, $new_file_name, $thumb = false): bool { $sourceProperties = getimagesize($file_temp); // Get image sizes: /* * Determine if it's a thumbnail or large image then * resize the images accordingly. */ $old_width = $sourceProperties[0]; $old_height = $sourceProperties[1]; $new_height = null; if ($thumb) { $new_width = 300; $newImageHeight = ($new_width * $old_height) / $old_width; $newImageWidth = $new_width; } else { $new_width = 1200; $newImageHeight = ($new_width * $old_height) / $old_width; $newImageWidth = $new_width; } $temp = '../' . $new_file_name; // folder is nested one down from root: $imageType = $sourceProperties[2];// Determine what type of image (png, jpg or gif): /* * Use Switch statement to resize the image and save it to the correct folders */ switch ($imageType) { case IMAGETYPE_PNG: $imageSrc = imagecreatefrompng($file_temp); $tmp = imageResize($imageSrc, $sourceProperties[0], $sourceProperties[1], $newImageWidth, $newImageHeight); imagepng($tmp, $temp); break; case IMAGETYPE_JPEG: $imageSrc = imagecreatefromjpeg($file_temp); $tmp = imageResize($imageSrc, $sourceProperties[0], $sourceProperties[1], $newImageWidth, $newImageHeight); imagejpeg($tmp, $temp); break; case IMAGETYPE_GIF: $imageSrc = imagecreatefromgif($file_temp); $tmp = imageResize($imageSrc, $sourceProperties[0], $sourceProperties[1], $newImageWidth, $newImageHeight); imagegif($tmp, $temp); break; default: echo "Invalid Image type."; exit; } return true; // Return true to signal that image was resized: }
  5. or you could simply have a small function of some kind to use a full name: function fullname($user) { return $user['firstname'] . " " . $user['lastname']; }
  6. If you are not using Fetch then you need to parse the data: var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj.name; } }; xmlhttp.open("GET", "json_demo.txt", true); xmlhttp.send();
  7. The methods/functions in the DbBox class to me is redundant unless you are going to override them, but like requinix stated "really, really, really vague question" to help with. I use the Active Record Design Pattern and those two classes would just be silly to me.
  8. Ooops read it wrong ..... please delete 😃
  9. 🤔 Hmm? Something tells me that isn't true. 🤥😔
  10. I have been updating my website to include the Active Response Design pattern using PHP pdo. I have most to the pdo done with a few minor refinements and improvements. If you want to get some ideas or inspiration check out my GitHub repository : https://github.com/Strider64/Miniature01282021 I know there's better out there, but it' not to bad for a person who is 56 that has only been programming in PHP the last 6-7 years (though I have previous coding experience in other languages).
  11. I would personally just do it silently with an unique constraint in MySQL and not advertising it too much to users. The more you broadcast it or let it be known that an username exists the more like they will attack your website. I'm not saying NOT to do it, but simply say "username can't be used at this time", "Choose a different username" or something more vague than that after the user attempts to registers. It's usually not that big of deal having to come up with a different username as you can save all the other registration info (except password) back on the HTML form as a convenience to the user. That's what I do.
  12. Exactly what the error says $data is a string not an array. You also have other errors.
  13. 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.
  14. 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.
  15. 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.
  16. 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.
  17. 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"); }
  18. 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.
  19. 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.
  20. 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.
  21. 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 .= "&laquo; Previous</a>"; } return $link; } public function nextLink($url = "") { $link = ""; if ($this->nextPage() != false) { $link .= "<a class=\"menuExit\" href=\"{$url}?page={$this->nextPage()}\">"; $link .= "Next &raquo;</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?
  22. 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.
  23. Checkout https://www.php.net/manual/en/datetime.format.php it should get you on the right track.
  24. 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.
  25. What's the purpose of having a form if there's no submit button?
×
×
  • 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.