Jump to content

Recommended Posts

I'm quite new to PHP. I have a selection dropdown, which sends the data to the phpmyadmin database.
This works fine, but I'd like it to be selected as default when I'm opening it again.

Here is how my code currently looks like:

$category_query = "SELECT * FROM categories";
$categories = mysqli_query($connection, $category_query);
if (isset($_GET['id'])) {
    $id = filter_var($_GET['id'], FILTER_SANITIZE_NUMBER_INT);
}

<select name="category">
    <?php while ($category = mysqli_fetch_assoc($categories)) : ?>
    <option value="<?= $category['id'] ?>"><?= $category['title'] ?></option>
    <?php endwhile ?>
</select>

Here is what I've tried:

<option value="<?= $category['id'] ?>"><?= $category['title'] ? "selected" : ""?></option>

I basically just inserted "selected" into it, but it's not the correct way, because every single option is shown as "selected".

Here is an image about the frontend:

Does anyone know how to make it to work? This is the last thing I need to fix on the website.
Thank you for being here!

Képernyőfelvétel (492).png

Something like this

<select name="category">
    <?php while ($category = mysqli_fetch_assoc($categories)) : 
          $sel = $_GET['category']==$category['id'] ? 'selected' : '';
          echo "<option $sel value='{$category['id']}'>{$category['title']}</option>";
          endwhile;
    ?>
</select>

 

48 minutes ago, Barand said:

Something like this

<select name="category">
    <?php while ($category = mysqli_fetch_assoc($categories)) : 
          $sel = $_GET['category']==$category['id'] ? 'selected' : '';
          echo "<option $sel value='{$category['id']}'>{$category['title']}</option>";
          endwhile;
    ?>
</select>

 

Thank you for your reply!

 

I inserted your coding and this is what I get:

Quote

Undefined index: category - which is this line: sel = $_GET['category']===$category['id'] ? 'selected' : '';

I've changed "category" to "id" because it is already defined, the warning disappears, but the problem is that "id" is the id of the post and not the category.

4 minutes ago, Barand said:

Then where are you holding the current value that you want to show as selected?

I have a different script where it gets handlet like this:

if (isset($_POST['submit'])) {
    $id = filter_var($_POST['id'], FILTER_SANITIZE_NUMBER_INT); //generated an id for the post itself
    $category_id = filter_var($_POST['category'], FILTER_SANITIZE_NUMBER_INT); //attaches choonen the categorys id to the post
}

//uploading to the database
$query = "UPDATE posts SET category_id=$category_id WHERE id=$id LIMIT 1";
$result = mysqli_query($connection, $query);

And then in the new script I fetch the category data and get these values with the form:

//fetching categories
$category_query = "SELECT * FROM categories";
$categories = mysqli_query($connection, $category_query);

if (isset($_GET['id'])) {
    $id = filter_var($_GET['id'], FILTER_SANITIZE_NUMBER_INT);
    $query = "SELECT * FROM posts WHERE id=$id";
    $result = mysqli_query($connection, $query);
    $post = mysqli_fetch_assoc($result);
}

<form action="<?= ROOT ?>editing-logic.php" enctype="multipart/form-data" method="POST">

Sorry if the explanation is not describing enough, I try to make it as clear as possible.

is the following a true statement - you are picking an existing 'post' to edit via the $_GET['id'] input, and what you are showing us is the code that would allow the category(_id) to be changed? are you also editing other 'post' columns?

next, you (will) have an issue if there are user/validation errors in the post method form processing code, in that you would want to initially populate the form field values with the existing data, then after the form has been submitted, populate the form field values with the submitted form data, so that the user doesn't need to keep reentering the changes over and over. the way to do this is to define an internal array variable that will initially receive the existing data, if the form has never been submitted (this internal array variable will be empty), then receives a trimmed working copy of the $_POST data inside the post method form processing code. this variable then gets used throughout the rest of the code.  an element in this array variable would be what gets used in the code setting the selected attribute for the category select/option menu. $post in SELECT ... FROM posts ... code is this variable.

here's a laundry list of issues based on the snippets of code -

  1. there's no useful comments to help anyone looking at the code know what it is trying to do, i.e. what my first paragraph is asking.
  2. the $_GET['id'] input is a 'required' input for this page. if it isn't set, doesn't contain a integer > 0, or the SELECT query using it doesn't match a row of data, that's an application error. you should trim, then validate this input. if it isn't valid, setup and display a unique and helpful error message for each possible type of failure. only use it if it is valid, then if the query doesn't match a row of data, setup a unique and helpful error message for that and don't even display the edit form if there's no data to edit.
  3. i recommend that you pre-fetch any data from a SELECT query into an appropriately named php variable, then test/use that variable in the html document. you are doing this for the $post data. do the same for the category data. this will separate the different concerns in the code, making it easier to test, debug, and maintain the code.
  4. don't attempt to detect if the submit button is set. there are cases where it won't be. instead detect if a post method form was submitted. if there can be more than one set of post method form processing code on a page, use a hidden field with a unique value in it to control which set of form processing code to execute.
  5. ALL the post method form processing code needs to be inside the conditional statement that has detected if the form has been submitted.
  6. if the UPDATE query can result in duplicate data for columns that must be unique, you need error handling for that query that tests the error number and sets up a unique and helpful error message for any problem with the data values that were submitted.
  7. to get the form to submit to the same page it is on, leave the entire action='...' attribute out of the form tag.
  8. you should use the FILTER_VALIDATE... flags. not the FILTER_SANITIZE ... flags. you want to validate input data, not sanitize it. if it is not valid, repopulate the field with the value and let the user correct what is wrong with it. since you are not testing the return value from the filter_var() calls, you doesn't actually know if the test failed or not before using the values. the current code is using boolean false values when filter_var() fails, which can trigger sql data type errors, which is exactly what hackers want as feedback when they intentionally do things to trigger errors.
  9. you should also use prepared queries when supplying external, unknown, dynamic values to a query when it gets executed. you would also want to switch to the much simpler PDO extension. a prepared query, while only adding one php statement per query, when using the PDO extension, actually simplifies the sql query syntax and provides protection for all datatypes.

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.