[Better Solution?]Category based form - php

I am busy making a multi-shop shopping site like amazon.com, ebay, carousell.com etc...
Now when users create a listing I made a custom fields system that get the custom fields from a mysql table then outputs them into the form.
The Code:
Okay so first this is the listings table:
ID
list_title
list_brand
seller_id
1
Two sticks
Mr Sticks
1012
Then we have listings_meta which is where I store the custom fields like for a pillow it would be type of filling or for a stick it would be color of stick:
ID
listing_id
meta_key
meta_value
1
1
stick_color
brown
Now the meta key comes from a database table called [form_fields] which is linked the the categories like this
[form_fields]:
ID
meta_key
type
meta_link
1
stick_color
select
0
2
stick_length
input
0
3
rock_weight
input
0
4
brown
option
1
5
blue
option
1
And the category table[cats]:
ID
category
4
Sticks
5
Stones
Link custom fields and categories[cat_meta]:
ID
meta_id
cat_id
1
1
4
2
2
4
3
3
5
So now that you know how the items link with each other lets dive into the PHP code:
Now fist when a user clicks create product that will be given a popup asking which category they want to list the product thats done with a simple select query then they will be redirected to a new page called new_product.php?cat=[id of category from database ID]
new_product.php?cat=4
Now some of the fields are the same for all products they are the ones in listings table
But for custom fields its a bit more complex
:
<input type="text" name="list_title " placeholder="Title">
</br>
<input type="text" name="list_brand " placeholder="Brand">
</br>
<?php //get custom fields from custom_inputs table
//query the database for fields id and
$stmt = $conn->prepare("SELECT `meta_id ` FROM `cat_meta` WHERE `cat_id` = ?");
$stmt->bind_param("i", $_GET['cat']);
$stmt->execute();
$stmt_results = $stmt->get_result(); // get result
while($row_get = $stmt_results->fetch_assoc()){
$field_id[] = $row_get['meta_id ']; //store all id's in array
}
if(empty($field_id)){ //no custom field found in database
return 0;
}else{
foreach($field_id as $field_id){ //loop ID's to get multiple
$stmt = $conn->prepare("SELECT `meta_key `, `type ` FROM `form_fields` WHERE `ID` = ?");
$stmt->bind_param("i", $field_id);
$stmt->execute();
$stmt_results = $stmt->get_result(); // get result
while($row = $stmt_results->fetch_assoc()){
$field_name[] = $row['meta_key']; //get key aka title
$field_type[] = $row['type']; //get the type of input
}
}
}
foreach ($field_name as $index => $field) { //combine the type and meta key
$type = $field_type[$index];
if($type === "select"){ //field type is a select
echo '</br><select name="body['.$field.']">';
echo '<option selected Disabled value="">Select Option</option>';
//get options from `form_fields` linked to this meta_id
$stmt = $conn->prepare("SELECT `meta_key` FROM `form_fields` WHERE `meta_linked` = ? AND `field_type` = 'option'");
$stmt->bind_param("s", $field);
$stmt->execute();
$stmt_results = $stmt->get_result(); // get result
while($row = $stmt_results->fetch_assoc()){
echo '<option value='.$row['meta_key '].'>'.$row['meta_key'].'</option>';
}
echo '</select>';
}
if($type === "input"){ //field type is a user input
echo "<input name='body[$field]' placeholder='$field'>";
}
}
?>
Yes I know the code is very messy but I will clean it up before it is pushed but my issue is I feel like this seems over-complex/not efficient, Can anyone recommend a better way to build custom fields based on the category that was selected.
Also i do not include a lot of html and other php processing code as i dont think it needs to be included but if you need more info i will give it :)

Related

PDO select only returns first row

I want to select several rows from my database and get each id where the name, material and size fits the binded value. I have tried doing this, but I only get the first row back:
foreach($_POST["txtName"] as $key => $name){
if(!empty($name) || !empty($_POST["txtMaterial"][$key]) || !empty($_POST["txtSize"][$key])){
echo $name.' '.$_POST["txtMaterial"][$key].' '.$_POST["txtSize"][$key];
$sQuery = $db->prepare('SELECT * FROM products WHERE name = :sName AND material = :sMaterial AND size = :sSize');
$sQuery->bindValue(':sName', $name);
$sQuery->bindValue(':sMaterial', $_POST["txtMaterial"][$key]);
$sQuery->bindValue(':sSize', $_POST["txtSize"][$key]);
$sQuery->execute();
$aOrders = $sQuery->fetchAll();
foreach($aOrders as $aOrder){
echo 'x';
}
}
}
From the echo before the query I get this back:
" 3 20BACURI 2 4ELVA "
Which is the material, size, name and material, size, name of two products. However, I only get the row of the first one back. Can anyone help me out why that is?
<input name='txtName[]' class='txtName' type='text'><div class='nameOfProduct'>".$aCategoryName['name']."</div>
<div class='add'>
<div id='adding'>+</div>
</div>
The value of the name is added in js when clicked on the .add class:
$('.add').click(function(){
$placeholder = $(this).siblings('.nameOfProduct').html()
$(this).siblings('.txtName').val($placeholder)
})

How can i use the id from one table item to connect another tables item

I am pretty new to php and sql and am learning as i create a web app so i'm wondering how this would be possible, if at all, or if there are better practices for this sort of task.
just as an example:
Say i have a database with 2 tables
one is author, the other book
author table
-----------
id | author
1 | jones
2 | jane
book table
----------
id | title | author
1 | Learning php | 1 <- i want this to reference the author from author table
2 | Foobar | 1
3 | How to give a proper high five | 2
i have a form that gets the authors name from a query as a select tag and i want to assign the id as the value for author in the book table when i submit the form
$authorQuery = mysqli_query($con, "SELECT * FROM author");
<form id="bookForm" action="books.php" method="POST">
<label for="title">Book Title</label>
<input type="text" name="title">
<label for="author">Author</label>
<select id="author" name="author">
<?php
while($row = mysqli_fetch_array($authorQuery)) {
//display as an array in a drop down list
echo '<option>' . $row['author'] . '</option>';
}
?>
</form>
How would i go about this?
I will make the options values as the authors Ids, change this
echo '<option>' . $row['author'] . '</option>';
to this
echo '<option value="' . $row['id']. '">' . htmlspecialchars($row['author']) . '</option>';
Now, when this form is submitted , at the server you will receive the id of the author in the $_POST['author'] variable, so you can make your update query using the id instead of the name of the author.
$query = "update book set author_id = ? where title = ?";
$stmt = $con->prepare($query);
$stmt->bind_param("is", $_POST['author'], $_POST['title']);
$stmt->execute();
suggestions:
this scheme means that your relationship is 1:m (1 author can write many books, but 1 book is must be written by only 1 author), this is not correct, as many books are written by many authors, so you need to use a third conjunction table to represent the many to many relationship m:m
The search on MySQL is case insensitive by default, however it's better to make a <select> for the books instead of <input> and assign the IDs of the books to the <option>s instead of typing the title (unless you have too much books to fit in a select), so you make sure you avoid any typos in the title of the book when you need to fill the form to assign an author to a book
The easiest way will be to
<?php $stmt = $conn->prepare("SELECT * from book")
$stmt->execute();
foreach($stmt as $row){
$id = $row['author'];
$stmt = $conn->prepare("SELECT * from author WHERE id='$id'")
$stmt->execute();
foreach($stmt as $row){
$name = $row['author'];
?><option value="<?php echo $name;?>"><?php echo $name;?></option>
}
}
The Complex Method is
$stmt = $conn->prepare("SELECT *, book.author AS bookauthor FROM book LEFT JOIN author ON author.id=book.id");
$stmt->execute();
foreach ($stmt as $row) {
?><option value="<?php echo $row['bookauthor'];?>"><?php echo $row['bookauthor'];?></option>
}

Get selected values in multiselect form field

I'm updating a PHP form field from a dropdown (single value selected) to a multiselect (multiple values selected).
I have 2 DB tables, one where the complete list of team members reside, and the other where the selected team members reside.
On the PHP page, I want to get the values from the full team members table and show the full list as a multiselect form field.
Then I want to be able to get the values from the selected team member table and have them show as selected options in the full multiselect list mentioned above.
Any idea on how I would accomplish this?
Here's my code, although right now it just returns the full team member list without the selected values.
$query = "SELECT walkername FROM Team_Management WHERE active=1 ORDER BY walkername ASC";
$stmt = $mysqli->prepare($query) or die ("Couldn't execute query: ".mysqli_error($mysqli));
$stmt->execute();
$stmt->bind_result($walkers);
echo "<div class='form-group'>";
echo "<label class='col-lg-3 control-label' for='Walkers'>Walkers:</label>";
echo "<div class='col-lg-5'>";
echo "<select multiple class='form-control' name='walkers[]' id='Walkers'>";
while ($stmt->fetch()) {
echo "<option value='$walkers'>$walkers</option>";
}
echo "</select>";
echo "</div>";
echo "</div>";
$stmt->close();
** UPDATED **
So one thing that I should've added, is that the SELECTED_TEAM_MEMBERS field is a comma separated field.
TEAM_MANAGEMENT table
id || walkername
1 || John
2 || Kate
SELECTED_TEAM_MEMBER table
cid || walkers
1 | John,Ray,Kate
2 | Kate,Matt,Joe
In addition, each group in the walkers field in the SELECTED_TEAM_MEMBER table is tied to a unique client id (cid).
So how can I identify the selected walkers from the complete list in the TEAM_MANAGEMENT table by unique client id.
You can get the list of your selected user with a boolean in your SQL request
SELECT walkername,
CASE WHEN **selected_team_members_name** > '' THEN '1' ELSE '0' END as is_selected
FROM Team_Management
LEFT OUTER JOIN **SELECTED_TEAM_MEMBERS** ON **selected_team_members_name** = walkername
WHERE active=1
ORDER BY walkername ASC
With selected_team_members_name the name of the column in your table and SELECTED_TEAM_MEMBERS the name of your table
And now $walker is as array with 2 key: walkername and is_selected
And after you can try a if to put them the attribute 'selected' when you write your 'option' tag
while ($stmt->fetch())
{
$selected = "";
if($walkers['is_selected'] == '1'){ //If your walker is selected
$selected = "selected";
}
echo "<option ".$selected." value=".$walkers['walkername'].">".$walkers['walkername']."</option>";
}
I may not have understand the context but i hope i helped you.

include the url in mysql field in creating a menu

I want to make the generated list from mysql data clickable or url is included. Is there a way to do this? part of the field is menu_parent and menu_url.
This is the sample generated list...
Boats
Cars
Trucks
when one of the item is clicked, it will be directed to the corresponding link or url in the mysql.
this is the mysql fields
menu item | menu_url
boats | boats.html
cars | cars.html
trucks | trucks.html'
Any help is appreciated.
$sql=$dbh->prepare("SELECT * FROM table");
$sql->execute();
while($r=$sql->fetch()){
echo "<a href='".$r['menu_url']."'>".$r['menu item']."</a>";
}
I prefer Foreach Other Than While...
$result = "SELECT * FROM yourTable";
$query = $glb_connection->prepare($result);
$query->execute();
$qry = $query->fetchAll();
foreach ($qry as $menu) {
echo "<a href='".$menu['menu_url']."'>".$menu['menu item']."</a>";
}

MYSQL insert form- insert 1 of 3 possible options from dependent select boxes

I have been searching for an answer to this for about an hour and can't find what I am looking for...
I have 3 dependent select boxes on a INSERT form.(drop_1, drop_2, drop_3) Each of their values (int) represent the same field in the database called category.
I am looking for a way to choose only the highest value of the three as the value that gets inserted into the category field.
Here is what I have been trying (obviously doesn't work):
$drop_1 = ($_POST['drop_1']);
$drop_2 = ($_POST['drop_2']);
$drop_3 = ($_POST['drop_3']);
$category = max($drop_1, $drop_2, $drop_3);
This works only if I select an option from each of the 3 boxes, but if I select an option from only 1 or 2 of the boxes the form gets submitted to the DB with blank values.
your php seems fine:
<?php
$_POST['drop_1'] = 100;
$_POST['drop_2'] = null;
$drop_1 = ($_POST['drop_1']);
$drop_2 = ($_POST['drop_2']);
$drop_3 = ($_POST['drop_3']);
$category = max($drop_1, $drop_2, $drop_3);
echo $category;
would output:
100
so, problem is with the form.
$drop_1 = mysql_real_escape_string($_POST['drop_1']);
$drop_2 = mysql_real_escape_string($_POST['drop_2']);
$drop_3 = mysql_real_escape_string($_POST['drop_3']);
$query = "INSERT INTO table1 (category)
SELECT GREATEST('$drop_1', '$drop_2', '$drop_3') as new_cat ";

Categories