0

on the page that I am working on you can upload stuff to a database. You give it a title, category, description and image path. It's all working, except I want the possibility to choose the category from either a list of existing categories, or come up with a new one.

Right now I have two inputs with the same name (category), but it is always just the last one in the markup that sets the category in the database. So what I want is for the first input, which is a <select>, to be ignored IF you specify you own category. If you don't specify anything in that input, the first one should be the one to set the category.

I'm new to PHP and I don't know javaScript, but if I have to use it to solve this, so be it.

Here is what gets inserted into the database table:

$ad[] = strip_tags($_POST["title"], $strip);
$ad[] = strip_tags($_POST["category"], $strip);
$ad[] = strip_tags($_POST["text"], $strip);
$ad[] = strip_tags($_POST["image"], $strip);

$stmt = $db->prepare("INSERT INTO Object ('title', 'category', 'text', 'image') VALUES (?, ?, ?, ?)");
$stmt->execute($ad);

And here are the inputs:

$selectCategory = "<select id='input1' name='category'>";
foreach($categories as $category) {
  $selectCategory .= "<option value='{$category}'>{$category}</option>";
}
$selectCategory .= "</select>";

<?php echo $selectCategory; ?><br>
<input type='text' class='text' name='category'>

Thanks

  • Thank you so much, both of you @DorMoshkovitz and @itachi! Can't believe it was so simple... I chose your answer Dor since your line of code was directly implementable in mine, plus I learned a new function from it (`strlen()`). – Jakob Axén Johansson Nov 17 '14 at 19:36

2 Answers2

0

you can use different name attribute for the input text box.

e.g. <input type='text' class='text' name='customcategory'>

server side:

$category = !empty($_POST['customcategory']) ? $_POST['othercategory'] : $_POST['category'];

then insert the $category in database.

itachi
  • 6,323
  • 3
  • 30
  • 40
0

name the 2 inputs differently, say, category1 and category2, and if like that:

$ad[] = strlen($_POST["category2"]) ? strip_tags($_POST["category2"], $strip) : strip_tags($_POST["category1"], $strip);

that is called shorthand if (How do I use shorthand if / else?)

Community
  • 1
  • 1
Dor Moshkovitz
  • 371
  • 1
  • 3
  • 9