Jump to content

VanityCrush

Members
  • Posts

    41
  • Joined

  • Last visited

Everything posted by VanityCrush

  1. Hiya, I have a database table which is storing articles posted by my users. I am using a function to dynamically display these on the webpage. I would like to implement a feature where other registered users can comment on them. I believe these comments should be also stored in the database and linked with the article ID as I want to generate them dynamically (and assign them to an article on the page). Each comment should be unique to the article it belongs, therefore a comment to one article won't relate in any way with the other existent articles. For this, I have created the following fields in my database: content_id, title, content, posted_by, date, comments, comment_by. I have tried the below solution but even for me, it seems very messy. I have around 20-25 days experience with PHP, so if anyone could point me in the right direction I would really appreciate it. First of all, I have written a function that is displaying the comments form: function generate_captcha_forms() { echo " <form method='post' action='' class='comments_form'> <input type='text' name='username' placeholder='your name... *' id='name'> <textarea name='comments' id='textarea' placeholder='your comment... *' cols='30' rows='6'></textarea>" . create_captcha() . " <input type='submit' name='submit' id='post' value='post'> </form> "; } I use the above function because I cannot figure any other way to display one comment form for each article in my database. So I figured I can loop them as per below: I am implementing the above function in the function that I use to list the articles from the database: function list_articles() { include('core/db/db_connection.php'); $sql = "SELECT * FROM blog ORDER BY id DESC"; $result = mysqli_query($dbCon, $sql); while ($row = mysqli_fetch_array($result)) { echo "<h5 class='posted_by'>Posted by " . $posted_by = $row['posted_by'] . " on " . $row['date'] . "</h5>" . "<h1 class='content_headers'>" . $title = $row['title'] . "</h1>" . "<article>" . $content = $row['content'] . "</article>" . "<hr class='artline'>"; if (logged_in() === true) { generate_captcha_forms(); validate_blog_forms($_POST['username'], $_POST['comments']); echo "<hr class='artline'>"; } } } I am also running the below function to validate the comment forms: function validate_blog_forms($username, $comments) { include('core/db/db_connection.php'); $username = mysqli_real_escape_string($dbCon, $_POST['username']); $comments = mysqli_real_escape_string($dbCon, $_POST['comments']); if (empty($_POST) === false) { if (strlen($username) > 17) { $errors[] = 'Your name must be less than 17 characters long'; } if (strlen($comments) < 17) { $errors[] = 'Your comment must be more than 17 characters long'; } if (empty($comments) || empty($username)) { $errors[] = 'Fields marked with an asterisk are required'; } if (empty($_POST['captcha_results']) === true) { $errors[] = 'Please enter captcha.'; } else if ($_POST['captcha_results'] != $_POST['num1'] + $_POST['num2']) { $errors[] = "Incorrect captcha."; } } if (empty($_POST) === false && empty($errors) === true) { insert_comments($comments, $username); } else if (empty($errors) === false) { echo "<div id='blog_comment_errors'>" . output_errors($errors) . "</div>"; } } The function that is inserting user comments in the database: function insert_comments($comment_by, $comments) { include('core/db/db_connection.php'); $comments = sanitize($comments); $comment_by = sanitize($comment_by); $sql = "INSERT INTO `blog` (`comments`, `comment_by`) VALUES ('$comments', '$comment_by')"; mysqli_query($dbCon, $sql); } The bugs I get in doing so: I have 4 articles. Whenever I try test the errors for one comment form, the errors are displaying to all the articles on the webpage. captcha will always return empty, and it never passes to the next step of validation where I'm checking to see if the number entered is correct. i have disabled the captcha to see if the comments would be stored properly. They are not. A comment for article 1 (for example) will be displayed for all the articles, however these are not even linked to the articles on the page, it just inserts 4 new fields in the database that act like articles. Not having much experience, even describing what I'm trying to do gave me a headache, so please let me know if you require further clarification and I'll try to be more clear.
  2. I see where you're coming from. thanks for the suggestions, really appreciate the feedback.
  3. Hello mac_gyver, thank you for your input. I am in fact displaying an error for each required field that was empty. The above was just a snippet of my code. include('core/init.php'); not_logged_in_redirect(); admin_protect(); if (empty($_POST) === false) { $required_fields = array('usernamne', 'password', 'password_again', 'first_name', 'active', 'email'); foreach ($_POST as $key => $value) { if (empty($value) && in_array($key, $required_fields) === true) { $errors[] = 'Fields marked with an asterisk are required'; break 1; // breaks to foreach (if 1 error is found, we can't do anything else so there's no point for checking further) } } // iterating through our post data - doing a check on each one if (empty($errors) === true) { if (user_exists($_POST['username']) === true) { $errors[] = 'Sorry, the username \'' . $_POST['username'] . '\' is already taken. Try ' . $_POST['username'] . rand(7, 77) . ' instead.'; } if (preg_match("/\\s/", $_POST['username']) == true) { // regexp checking for any amount of spaces within the username $errors[] = 'No spaces allowed.'; } if (!ctype_alnum($_POST['username'])) { $errors[] = 'No special characters allowed'; } if (strlen($_POST['password']) < 7) { $errors[] = 'Your password must be at least 7 characters long.'; } if ($_POST['password'] !== $_POST['password_again']) { $errors[] = 'Your passwords do not match.'; } if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) { $errors[] = 'The email address entered is not valid.'; } if (email_exists($_POST['email']) === true) { $errors[] = 'Sorry, the email \'' . $_POST['email'] . '\' is already in use.'; } if (empty($_POST['captcha_results']) === true) { $errors[] = 'Please enter captcha.'; } else if ($_POST['captcha_results'] != $_POST['num1'] + $_POST['num2']) { $errors[] = "Incorrect captcha."; } } } // print_r($errors); if(isset($_GET['success']) && empty($_GET['success'])) { echo '<body> <div id="body_wrap"> <nav id="nav"> <ul> <li><a href="recom.php">recommendations</a></li> <li><a href="blog.php">blog</a></li> <li><a href="includes/logout.php">log out</a></li> <li><a href="admin.php">admin page</a></li> <li><a href="../ro/login.php">ro</a></li> </ul> <div id="logo"><a href="index.php"><img src="img/provisory-logo.gif"></a></div> </nav>'; echo '<h3 class="reg_success">User added successfully!</h3>'; } else { if (empty($_POST) === false && empty($errors) === true) { $register_data = array( 'username' => $_POST['username'], 'password' => $_POST['password'], 'first_name' => $_POST['first_name'], 'email' => $_POST['email'], 'active' => isset($_POST['active']) ? 1 : 0, ); admin_add_user($register_data); header('Location: add_user.php?success'); exit(); } else if (empty($errors) === false) { echo output_errors($errors); } } Is this any better?
  4. The reason why I'm checking if $_POST is empty is because I want to display an error to the users that are trying to submit the form without inserting any data. Does that make sense ?
  5. Using the checkbox approach solved my issue and I have modified the code like this: Required fields: if (empty($_POST) === false) { $required_fields = array('usernamne', 'password', 'password_again', 'first_name', 'active', 'email'); foreach ($_POST as $key => $value) { if (empty($value) && in_array($key, $required_fields) === true) { $errors[] = 'Fields marked with * are mandatory'; break 1; } } The code that is adding the user to the database: if (empty($_POST) === false && empty($errors) === true) { $register_data = array( 'username' => $_POST['username'], 'password' => $_POST['password'], 'first_name' => $_POST['first_name'], 'last_name' => $_POST['last_name'], 'email' => $_POST['email'], 'active' => isset($_POST['active']) ? 1 : 0, ); admin_add_user($register_data); header('Location: add_user.php?success'); exit(); } else if (empty($errors) === false) { echo output_errors($errors); } Didn't even cross my mind that I could just simply use a checkbox, I guess I was too focused on my approach, haha. Thank you
  6. That's the way I tried it in the first place - || instead of && - but I was encouraged to use AND. Using OR it won't work at all. The form field I have is not a checkbox, but a regular text field. I guess this might be the problem and a checkbox would be more appropriate in this case, as you suggested. I'll try it out and let you know. Thanks
  7. I am trying to restrict the value entered for the form field 'active' to either 0 or 1, 0 being inactive and 1 being active The code that is inserting the user in the database: if ($_POST['active'] != '1' && $_POST['active'] != '0') { $errors[] = 'Active field can only take values of either 1 or 0'; } else { if (empty($_POST) === false && empty($errors) === true) { $register_data = array( 'username' => $_POST['username'], 'password' => $_POST['password'], 'first_name' => $_POST['first_name'], 'email' => $_POST['email'], 'active' => $_POST['active'], ); admin_add_user($register_data); header('Location: add_user.php?success'); exit(); } else if (empty($errors) === false) { echo output_errors($errors); } } The function: function admin_add_user($register_data) { include('core/db/db_connection.php'); array_walk($register_data, 'array_sanitize'); $register_data['password'] = md5($register_data['password']); $fields = '`' . implode('`, `', array_keys($register_data)) . '`'; $data = '\'' . implode('\', \'', $register_data) . '\''; $sql = "INSERT INTO `_users` ($fields) VALUES ($data)"; $query = mysqli_query($dbCon, $sql); } How can I restrict the values entered for the form field named 'active' to 1 or 0? I have tried 1 and 0 without the apostrophes but I still get the error associated with this if statement. Whenever I use 1 as a field value it works, however when using 0 it does not register it and the form field acts like it is blank. Any suggestions?
  8. After much testing, the solution I have found is adding the header redirect into the function and removing it from the calling code: function email_users($subject, $body) { include('core/db/db_connection.php'); $sql = "SELECT email, first_name FROM `_users` WHERE allow_email = 1"; $query = mysqli_query($dbCon, $sql); while (($row = mysqli_fetch_assoc($query)) !== false) { $body = "Hello ". $row['first_name'] . ", <br><br>" . $body; email($row['email'], $subject, $body); header('Location: email_users.php?success'); } } Your suggestion is correct, requinix. require_once is needed in order for this to work, otherwise it will send an email only to the first account found in the database. Without redirecting to the email_users.php?success, this will cause an infinite loop, no matter if I call require_once or require. Would this be the correct approach or is it just a temporary messy fix?
  9. Hiya, I am using PHPMailer to send emails from my local host. I have written a function which is supposed to send emails to registered users who have chosen the option to receive them. (I.e. newsletter subscription, etc) function email_users($subject, $body) { include('core/db/db_connection.php'); $sql = "SELECT email, first_name FROM `_users` WHERE allow_email = 1"; $query = mysqli_query($dbCon, $sql); while (($row = mysqli_fetch_assoc($query)) !== false) { $body = "Hello ". $row['first_name'] . ", <br><br>" . $body; email($row['email'], $subject, $body); } } The code that is calling the function: if (isset($_GET['success']) === true && empty($_GET['success']) === true) { ?> <h3 class="email_success">Emails have been sent</h2> <a href="admin.php" class="email_success_a">Go back to the admin page</a> <?php } else { if (empty($_POST) === false) { if (empty($_POST['subject']) === true) { $errors[] = 'A message subject is required.'; } if (empty($_POST['body']) === true) { $errors[] = 'A body message is required.'; } if (empty($errors) === false) { echo output_errors($errors); } else { email_users($_POST['subject'], $_POST['body']); header('Location: email_users.php?success'); exit(); } } // generate form otherwise Any idea why I'm getting Fatal error: Cannot redeclare PHPMailerAutoload() ? I would also like to point out that even with this error, the function still works and the emails are being sent...
  10. Hello, I have an unordered list with 5 classes (don't ask).. <ul class="error_list reg_errors chpw_errors actv_errors profile_errors"> I have used .error_list:nth-child(1) to target reg_errors and .error_list:nth-child(2) to target chw_errors class. How can I target the 5th class of this element without using :last-child? [i will be adding more classes to it] I've tried :nth-child(5n+1) and it works, however it is also targeting the reg_errors class. I know this is a mess, but I can't find a better solution as I need to dynamically generate each class depending on the user's action.
  11. Sorry if that sounded ungrateful, I see your point and I thank you for taking the time to look at my question
  12. You are right. The order in which I was doing this is wrong. The correct way is: function login($username, $password) { include('core/db/db_connection.php'); $user_id = get_user_id($username); $username = sanitize($username); $password = md5($password); $sql = "SELECT COUNT(user_id) FROM `_users` WHERE username = '$username' AND password = '$password'"; $query = mysqli_query($dbCon, $sql); return (mysqli_result($query, 0) == 1) ? $user_id : false; } However, next time I'm looking for an answer, a little bit of specificity won't hurt.
  13. Hi there, mysql_query is deprecated and it will be removed on future PHP versions. Use mysqli_query instead. mysqli_query takes two parameters - the database connection and the actual query, therefore you have to include the database connection file in your code. For example : $dbCon = mysqli_connect("localhost", "root", "password", "database_name") or die(mysqli_error()); As you can see, I am storing the database connection in a variable. To implement this into mysqli_query we now need to store the actual query in a variable (you could also write the full query as the second parameter but it will make your code less readable) $sql = "SELECT COUNT(*) as Num FROM property WHERE $where "; Now to implement this with mysqli: $query = mysqli_query($dbCon, $sql); For mysql_result you can use the below function which is basically a mysqli_result: function mysqli_result($res,$row=0,$col=0) { $numrows = mysqli_num_rows($res); if ($numrows && $row <= ($numrows-1) && $row >=0) { mysqli_data_seek($res,$row); $resrow = (is_numeric($col)) ? mysqli_fetch_row($res) : mysqli_fetch_assoc($res); if (isset($resrow[$col])) { return $resrow[$col]; } } return false; } After all this, your line should look like: $total_results = mysqli_result($query, 0); Hope this helps in a way or another.
  14. Hello, I have inserted a user into my database table through phpMyAdmin using the predefined MD5 function. (I know md5 is not secure and I should use bcrypt istead, but I don't need that type of security, my only purpose is not to store the passwords in plain text) Now my problem is that whenever I try to log the user in, I can never read the hashed password back. This is my code: The function that is testing for the username and password: function login($username, $password) { include('core/db/db_connection.php'); $sql = "SELECT COUNT(user_id) FROM `_users` WHERE username = '$username' AND password = '$password'"; $query = mysqli_query($dbCon, $sql); $user_id = get_user_id($username); $username = sanitize($username); $password = md5($password); // issue return (mysqli_result($query, 0) == 1) ? $user_id : false; // possible issue } The logging processing code: if (empty($_POST) === false) { $username = $_POST['username']; $password = $_POST['password']; if (empty($username) === true || empty($password) === true) { $errors[] = 'Username and/or password fields must not be left blank'; } else if (user_exists($username) === false) { $errors[] = 'Username does not exist! Please register before logging in.'; } else if (user_active($username) === false) { $errors[] = 'You haven\'t activated your account yet'; } else { $login = login($username, $password); if ($login === false) { $errors[] = 'Username/password incorrect'; } else { echo 'ok' . '<br/>'; //set user session //redirect user } } print_r($errors); } How can I read the stored MD5 password to allow my registered users access? Many thanks.
×
×
  • 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.