Jump to content

Strider64

Members
  • Posts

    473
  • Joined

  • Last visited

  • Days Won

    12

Everything posted by Strider64

  1. Well Davey K beat me to the punch, but I came up with the first one he did: <?php $places = array( array("name" => "Cabot Cove", "area" => "12", "lat" => "-11.003", "lon" => "-151.2285", "pop" => "17"), array("name" => "Smallville", "area" => "32;", "lat" => "-19.910", "lon" => "-50.205", "pop" => "18"), array("name" => "Gotham City", "area" => "85", "lat" => "-39.9294", "lon" => "-40.199", "pop" => "14"), array("name" => "Springfield", "area" => "21.6", "lat" => "-43.9534", "lon" => "-24.2118", "pop" => "18"), ); foreach($places as $place) { if ($place['name'] == "Gotham City") { echo 'The latitude and longitude for ' , $place['name'] , ' is ' , 'lat: ' , $place['lat'] , ' lon: ' , $place['lon'] , '<br>'; } }
  2. I find it easier to find out what privileges a user has then doesn't have and having a User/Member class simplifies that for all one has to do is something like: // Method returns a Boolean if the user is an administrator: public function isAdmin() { return ($this->userType == 'admin'); }
  3. <?php $name_array_original = array ( 0 => array('animal' => 'dog'), 1 => array('animal' => 'cat'), 2 => array('animal' => 'tiger') ); $name_array = array ( 0 => array('animal' => 'dog' , 'name' => 'Snoopy'), 1 => array('animal' => 'cat', 'name' => 'Garfield'), 2 => array('animal' => 'tiger', 'name' => 'Tony') ); // Name sorting function: function name_sort($x, $y) { return strcasecmp($x['name'], $y['name']); } echo '<h2>Original Array</h2><pre>' . print_r($name_array_original, 1) . '</pre>'; uasort($name_array, 'name_sort'); echo '<h2>Array Sorted By Name</h2><pre>' . print_r($name_array, 1) . '</pre>'; foreach ($name_array_original as $original) { foreach ($original as $key => $value) { echo '<p>Key = ' . $key . '<br>Value = ' . $value . '</p>'; } }
  4. It took me a while to understand OOP and I'm always learning something new. Just remember all you attributes have to correspond to the database table columns: Fore example a User class attributes might look something like: protected $id = null; protected $userType = null; protected $username = null; protected $email = null; protected $pass = null; protected $dateAdded = null; You can even have specialized methods(functions) // Method returns a Boolean if the users is an administrator: function isAdmin() { return ($this->userType == 'admin'); } And I think the following will really clear this up (This is part of my login.php file): // Check against the database: $query = 'SELECT id, userType, username, email FROM users WHERE email=:email AND pass=SHA1(:pass)'; $stmt = $pdo->prepare($query); $result = $stmt->execute(array(':email' => $email->getValue(), ':pass' => $password->getValue())); // Try to fetch the results: if ($result) { $stmt->setFetchMode(PDO::FETCH_CLASS, 'User'); $user = $stmt->fetch(); }
  5. <?php echo (isset($array['key'])) ? "Array key exists." : "Array key does not exist.";
  6. I have it where I check the username (name) against the names in the database during the registration process and in my opinion there isn't to much code: $query = " SELECT 1 FROM users WHERE username = :username1 "; $query_params = array( ':username1' => htmlspecialchars($_POST['username1']) ); $stmt = $db->prepare($query); $result = $stmt->execute($query_params); $row = $stmt->fetch(); // If a row was returned, then we know a matching username was found in // the database already and we should not allow the user to continue. if($row) { error_log("This username is already registered", 3, "../logs/my-errors.log"); $announce->errorHandler("user_taken"); $user_input = $announce->error_return(); $error_msg = true; } I stop the registration process before it is even entered into the table, thus no need in cleaning it up. To prevent bots I employe a Captcha scheme, don't like doing it...however, it's a necessary evil . Though over time I have a utility to purge the really really old accounts that are inactive.
  7. Null wipes the array, giving it a clean slate. Where as unset you can be selective in what you clear from the array. For Example: unset($row['salt']); unset($row['password']);
  8. It feels so good to solve the problem on your own.... Here's the solution if anyone cares (this is only part of the file): // Creat a new QuickForm2 form: // set_include_path(get_include_path() . PATH_SEPARATOR . '/usr/local/pear/share/pear/'); require('HTML/QuickForm2.php'); //$form = new HTML_QuickForm2('editPageForm' ); // Set defaults for the form elements $form = new HTML_QuickForm2('editPageForm', 'post', array( 'action' => $_SERVER['PHP_SELF'] . '?id=' . $_GET['id'] )); // Add the title field: $title = $form->addElement('text', 'title'); // Add Data to text box, only if the submit button isn't click! if (!($form->validate())) { $title->setValue(strip_tags($page->getTitle())); } $title->setLabel('Page Title'); $title->addFilter('strip_tags'); $title->addRule('required', 'Please enter a page title'); // Add the content field: $content = $form->addElement('textarea', 'content'); // Add Data to textarea, only if the submit button isn't click! if (!($form->validate())) { $content->setValue(strip_tags($page->getContent())); } $content->setLabel('Page Content'); $content->addFilter('strip_tags'); $content->addFilter('nl2br'); $content->addFilter('trim'); $content->addRule('required', 'Please enter the page content'); // Add the submit button: $submit = $form->addElement('submit', 'submit', array('value' => 'Edit This Page')); $form->addRecursiveFilter('trim'); // Validate the form data: if ($form->validate()) { // Update the edited text: $query = 'UPDATE pages SET creatorId=:creatorId, title=:title, content=:content, dateUpdated=NOW() WHERE id=:id'; $stmt = $pdo->prepare($query); $result = $stmt->execute(array(':creatorId' => $user->getId(), ':title' => $title->getValue(), ':content' => $content->getValue(), ':id' => $page->getId())); // Freeze the form upon success: if ($result) { $form->toggleFrozen(true); $form->removeChild($submit); } }
  9. I've been trying to improve my php skills by reading and going through the examples (step by step in order) from the book "PHP Advanced and Object-Oriented Programming". I'll try to explain it the best that I can the problem I have followed with some code. I think I'll will start with code: I have to grab the data for after all it's an edit page: <?php # edit_page // This page both displays and handles the "edit the page" form. // Need the utilities file: require('includes/utilities.inc.php'); try { // Validate the page ID: if (!isset($_GET['id']) || !filter_var($_GET['id'], FILTER_VALIDATE_INT, array('min_range' => 1))) { throw new Exception('An invalid page ID was provided to this page.'); } // Fetch the page from the database: $query = 'SELECT id, title, content, DATE_FORMAT(dateUpdated, "%e %M %Y") as dateUpdated FROM pages WHERE id=:id'; $stmt = $pdo->prepare($query); $result = $stmt->execute(array(':id' => $_GET['id'])); // If the query ran OK, fetch the record into an object: if($result) { $stmt->setFetchMode(PDO::FETCH_CLASS, 'Page'); $page = $stmt->fetch(); } else { throw new Exception('An invalid page ID was provided to this page'); } } catch(Exception $e) { // catch generic Exceptions $pageTitle = 'Error!'; include('includes/header.inc.php'); include('views/error.html'); } Then I have to setup my Quickform2 form // Creat a new QuickForm2 form: // set_include_path(get_include_path() . PATH_SEPARATOR . '/usr/local/pear/share/pear/'); require('HTML/QuickForm2.php'); $form = new HTML_QuickForm2('editPageForm' ); // Add the title field: $title = $form->addElement('text', 'title'); $title->setLabel('Page Title'); $title->addFilter('strip_tags'); //$title->addRule('required', 'Please enter a page title'); // Add the content field: $content = $form->addElement('textarea', 'content'); $content->setLabel('Page Content'); $content->addFilter('strip_tags'); $content->addFilter('trim'); //$content->addRule('required', 'Please enter the page content'); // Set defaults for the form elements $form->addDataSource(new HTML_QuickForm2_DataSource_Array(array( 'title' => $page->getTitle(), 'content' => $page->getContent() ))); // Add the submit button: $submit = $form->addElement('submit', 'submit', array('value' => 'Edit This Page')); and then I have to validate and submit the edited data to the database (This is where I run into problems) // Check for a form submission: if (!isset($_SERVER) && $_SERVER['REQUEST_METHOD'] == 'POST') { // Handle the form submission // Validate the form data: if ($form->validate()) { $query = 'UPDATE pages SET creatorId=:creatorId, title=:title, content=:content, dateUpdated=NOW() WHERE id=:id'; // Insert into the database: //$query = 'INSERT INTO pages (creatorId, title, content, dateAdded) VALUES (:creatorId, :title, :content, NOW())'; $stmt = $pdo->prepare($query); $result = $stmt->execute(array(':creatorId' => $user->getId(), ':title' => $title->getValue(), ':content' => $content->getValue(), ':id' => $page->getId())); // Freeze the form upon success: if ($result) { $form->toggleFrozen(true); $form->removeChild($submit); } } // End of form validation IF. } // End of form submission IF. This is the error it gives: Details (not for public consumption): An invalid page ID was provided to this page. Notice: Undefined variable: page in C:\xampp\htdocs\php_test\chapter-09-CMS-with-OOP\edit_page.php on line 56 Fatal error: Call to a member function getTitle() on a non-object in C:\xampp\htdocs\php_test\chapter-09-CMS-with-OOP\edit_page.php on line 56 I think it might have something to do with the url being different (edit_page.php?id=5) vs (edit_page.php) when it kicks out the error. I don't know if I have my query right or the POST right or what have you. This is the first time I really have been using PDO for previously I've been using mysqli to go back and forth to the MySQL database. I believe I have it right? Anyways, I apologize if I didn't make myself clear and I can always reply with more information if needed. I have gone to the author's forums, check the Quckform2 documentation, php.net manual and have done a bunch of Google searches to no avail to fix the problem. Well at least I know now how to catch an error, but now the thing is how to fix them. Thanks, John
  10. You (or you visitors) via code have to tell it what timezone you are in ---- for example: date_default_timezone_set("America/New_York");
  11. How's this? (Didn't see the part where you want it click, but I'm tired this morning. Maybe you can figure it out on your own or someone else can help you?) <?php $total_unread_private_messages = 14; if ($total_unread_private_messages) { echo "The Detroit Tigers are No. 1 and you have " , $total_unread_private_messages; } else { echo 'The Detroit Tigers are not playing today and you have ', $total_unread_private_messages; } echo '<br>'; $total_unread_private_messages = 0; if ($total_unread_private_messages) { echo "The Detroit Tigers are No. 1 and you have " , $total_unread_private_messages; } else { echo 'The Detroit Tigers are not playing today and you have ', $total_unread_private_messages; }
  12. should <form id="form2" name="form2" method="post" action=""> it be this <form id="form2" name="form2" method="post" action="report.php">?
  13. This is what I do, but I'm sure a guru here will have a better way of doing this. Though it works for me. I have a file for my database constant variables called common.php <?php define('DB_HOST', 'localhost'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', '****'); define('DB_NAME', 'cart_db'); my connection class: class DatabaseConnection { protected static function connect() { $database = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD, DB_NAME); return $database; } } Where I grab my data class class DatabaseData extends DatabaseConnection { public $products = array(); public function shopping_cart_data() { $database = parent::connect(); //Connects to the mysqli Database $query = "SELECT CONCAT('A00', id) AS id, description, cost, qty_on_hand FROM shopping_cart ORDER by id ASC"; $result = $database->query($query); while ($page = $result->fetch_array(MYSQLI_ASSOC)) { $this->products[] = new Item($page['id'], $page['description'], $page['cost'], $page['qty_on_hand']); } /* free result set */ $result->free(); $databaseClose = parent::close_connection(); return $this->products; } }
  14. To me you would be better off pulling the content off the database by having a dynamic menu, an example: Forgive the code, for it's old code that I have laying around and isn't the greatest. function php_navigation($nav_page, $page_set) { // Format for php_navigation // <ul> // <li><a href="{link}">Name of Link</a></li> // </ul> $query = "SELECT id, category FROM pages ORDER BY new_blog_date ASC LIMIT 25"; $output = "<ul>"; if ($result = mysqli_query($db, $query)) { while ($page = mysqli_fetch_array($result)) { $output .= "<li><a href=\"" . $nav_page . "?page=" . urlencode($page["id"]) . "\">"; if ($page_set == $page['id']) { $output .= "<span class=\"selected\" >{$page["category"]}</span>"; } else { $output .= "{$page["category"]}"; } $output .= "</a></li>"; } /* free result set */ mysqli_free_result($result); } $output .= "</ul>"; return $output; } This way the visitor could just click on a link and then by writing code (Hint a single if statement and a get statement (of course sanitized ) could pass the content to be displayed. This is what I would do instead of writing all that code, but I'm lazing and want to write as little code as possible.
  15. I don't want to hijack this thread, so I'll keep my question simple. Isn't Mapper Classes a PEAR package?
  16. I just have to say I think I finally getting the hang of OOP and the power is has, I am truly amazed For example public function commentPostRecords() { $database = parent::connect(); //Connects to the mysqli Database $query = "SELECT id, username, pages_id, content, post_date FROM comments ORDER by id"; $result = $database->query($query); while ($page = $result->fetch_array(MYSQLI_ASSOC)) { $this->send_comments[] = new BlogPosts($page); // Assign new object BlogPosts to an array } /* free result set */ $result->free(); return $this->send_comments; } and this <?php class BlogPosts extends BlogPost { public function __construct($page) { foreach ($page as $key => $value) { $pos = strpos($key, 'date'); // Find the word date in array if ( $pos !== false ) $value = date('F j, Y g:i A', strtotime( $value )); // Format MySQL date to proper format $this->$key = $value; // Assign value to variable in object. } } } Would had taken me way more lines doing it the procedural way and the nice feature is that I can use the constructor for multiple tables. I have to say Thanks once again to ignace and trq, plus php.net manual, it truly helps visiting that site to read up on arrays, objects, etc....
  17. I'm guessing you don't have method="post" (print_r to check) <form class="login-style" action="" method="post">
  18. Thanks for replying and I definitely saving this for my notes so I can refer to it from time to time.
  19. It was kind of late when I wrote for I meant by number is making the index of the array be associative instead of numeric. However, after reading these replies that doesn't make sense now to me either. , I think I now understand it is more important to understand what I want the class/methods to do in OOP and take one step at a time. I thought in order for MemberTopic class to have access to the mysqli it would have to extend ConnectMySQL Class, and after researching what you mean I found out that it was sloppy code on my part for I have a separate file with the extend ConnectMySQLClass and I should had never had require_once ("Connect.DB.Class.php"); in the other file. Thanks for Replying <?php require_once ('common.php'); abstract class ConnectMySQLClass { protected static function connect() { $database = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD, DB_NAME); return $database; } }
  20. I think I'm starting to wrap my mind around how to work with OOP - Objects and Arrays I have starting a small test php file that I'm doing testing on. Here's my main file <?php require('includes/Connect.MySQL.Class.php'); ?> <?php require('includes/TopicFileClass.php'); ?> <?php $data = array(); // New instance/modifier of class MemberTopic $topic = new MemberTopic($data); // Retrieve topics from mysqli database $topic = $topic->retrieve_record(); //print_r($topic); ?> <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Object Oriented Programming</title> </head> <?php ?> <body> <?php foreach ($topic as $key=>$record) { // Loop through the Array to pull out the objects(records)?> <h1><?php echo $record->blog_name; // Display the Title of the Blog ?></h1> <p><?php echo $record->content; // Display the Content of the Blog ?></p> <?php } // Closes the foreach loop ?> </body> </html> An here is where I retrieve my data <?php require_once ("Connect.MySQL.Class.php"); class MemberTopic extends ConnectMySQLClass { protected $threads = array(); protected function main_record() { $database = parent::connect(); //Connects to the mysqli Database $query = "SELECT * FROM pages ORDER by id"; $result = $database->query($query); while ($page = $result->fetch_array(MYSQLI_ASSOC)) { $this->threads[] = (object) $page; } /* free result set */ $result->free(); //print_r($this->threads); return $this->threads; } public function retrieve_record() { //return $records = $this->assign_topic_record(); return $this->main_record(); } } My questions is there a way to make it so I have each object tied to a user name instead of a number? I tried doing $this->threads[$page['username']] = (object) $page; which only worked partially for it skip a few records(objects). If there isn't a way of doing it, it's no big deal for this has simplified my code a lot and makes it so much easier following what the code is doing. Thanks John
  21. You need to check it to see if the variable is set. There are many ways you can do this, the following uses a Ternary Operator, but you could use an if statement to accomplish the same thing. <p>thank you, <?php echo (isset($_POST['firstName'])) ? $_POST['firstName'] : 'To Whom It May Concern'; ?>, for filling out my form </p>
  22. <?php function get_stores() { $stores = array( "First Name" => "Kevin", "Last Name" => "Smith", "Occupation" => "Director" ); foreach ($stores as $key => $value) { echo "key = " . $key . " value = " . $value . "<br />"; } return $stores; } // use print_r instead to see how the array is setup $my_array = get_stores(); print_r($my_array); ?>
  23. Well, after thinking about this and doing some research on the web I solved this myself (btw going to php.net documentation does help a lot), in case anyone runs into a similar problem here's the solution: public function login_user( $user, $user_pwd, $login_ok) { /* create a prepared statement */ if ($stmt = $this->database->prepare("SELECT id, username, password, salt, email, confirmed FROM users WHERE username=?")) { /* bind parameters for markers */ $stmt->bind_param("s", $user); /* execute query */ $stmt->execute(); /* bind result variables */ $stmt->bind_result($row['id'], $row['username'], $row['password'], $row['salt'], $row['email'], $row['confirmed']); /* fetch value */ $stmt->fetch(); /* close statement */ $stmt->close(); } // The Above checks to see if the username is in the databese // The Belows checks the password. if($row) {
  24. What I do is have a common.php at the top of my page before my header info like this: <?php require_once("includes/common.php"); ?> <?php require("includes/Thread.Reply.Class.php"); ?> <?php $dynamic_menu = new ThreadReplayClass; // Instances for Displays Threads and Replies $threads = $dynamic_menu->display_topic(); $user_comments = $dynamic_menu->display_replies(); ?> <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> Then in my common.php file I do this <?php define('DB_HOST', 'localhost'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', '*******'); define('DB_NAME', 'your_database'); header('Content-Type: text/html; charset=utf-8'); session_start(); This prevents a lot of those errors from happening in the first place, but you still have to be careful on a few other gotchas.
  25. While the below works, I want to improve it by using bind parameters. I know the $query string should have WHERE username=? at the end of the string. What I am stuck on is the prepare statement (Which should be the converted $query statement?) and the $stmt->bind_param('s', $user); portion of it. $query = "SELECT id, username, password, salt, email, confirmed FROM users WHERE username='$user'"; $result = $this->database->query($query); /* fetch values */ $row = $result->fetch_array(MYSQLI_ASSOC); $result->free(); /* close connection */ $this->database->close(); // The Above checks to see if the username is in the databese // The Belows checks the password. if($row) { I'm slowly grasping php and mysqli, but trying to convert this has me stumped. I must be having a brain fart. Any help would be greatly appreciated. Thanks John
×
×
  • 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.