How to seperate results from a mysql select - php

I apologize for this beginner question but unfortunately it is my level.
I have a fairly simple web page for my work, it is a index.php page that when opened goes out to a DB and retrieves the contents of a certain column. It then places the results in a drop down pick list.
Here is my problem, this column is a list of materials for customers. Some customers have more than 1 different type of material, while others have one.
Therefore my pick list can look like:
Apple /n
Orange; Apple; banana/n
banana;peach /n
orange/n
I am trying to come up with something that when I pull the data from the mysql DB that my php seperates the materials and only provides unique items.
Here is my code for creating picklist:
<p><select size="1" name="material" ID="material" onChange="showfield(value);">
<option value=''><None></option>;
<?php
while ($row = mysql_fetch_array($query))
{
$rowmod = strtr($row['material']," ","_");
echo "<option value='$rowmod'>$row[material]</option>";
}
?>
Here is my mysql select:
$query="select distinct material from TABLE-A order by material";
Update:
I think my Mysql is right, I think I played around with the php strtr and I was able to remove the ; and add lines in, but now I do not know how to make it cycle through and create my
here is the new code:
$row[product]";
}
?>
some output from my $row will have only one product, some will have 2 or more, I wonder if I have to put another while loop after the $rowmod?
I have a feeling I am close, but hoping for some guidance.

First of all, you should make a material table, indexed with an auto_increment id, and use that ID in what you call TABLE-A in a column material_id. Like that you'll have a list of unique material in one table dedicated to it, where you can even add some columns for the details of the material, etc..
Then I am unsure of your needs/use-case, but it looks like you'll need a customer_material table to link a customer with its material(s) so that you know which customer uses which material. It would have an id auto-incremented, as it should always be for any table for better practices, a customer_id and a material_id, with an unique index on the both last columns (customer_id+material_id) to be sure you link one material to one customer only once and not many time each material for the same customer.
Then when you'll need to list the materials for a given customer, just use this query:
select m.id, m.name
from customer_material cm
join material m on cm.material_id = m.id
where cm.customer_id = YOUR_CUSTOMER_ID
If you need to list all materials uniquely, you;ll then need this query:
select m.id, m.name
from material m
order by m.name /* optional, to order by the material name */
And voila. As I am unsure of your use-case the schema of the DB might be a bit different, but I think anyway the main problem in your issue is that the DB is not well architected. Lemme know if I something is unclear here.

You mentioned that different customers have different materials, but that is not reflected in your SQL query because there is no WHERE clause, meaning that you are selecting all unique values from the materials table regardless of any condition. But with that aside, I think that if you change your code slightly you will get some data.
$query="select distinct `material` from `TABLE-A` order by material"
<p><select size="1" name="material" ID="material" onChange="showfield(value);">
<option value=''><None></option>;
<?php
while ($row = mysql_fetch_assoc($query))
{
$rowmod = strtr($row['material']," ","_");
echo "<option value='$rowmod'>$row['material']</option>";
}
?>

Related

get list from table used to create "filter button"

This must be something trivial but long to explain. I cannot form good question for google. I dont know if I should get this result in SQL query or I need to change PHP part which includes sql query. (My knowledge is small, I am making my own very simple planner website but im stuck on creating button for filtering options.)
Imagine I have table named “Records” with 3 columns “ID, Item, Category”.
In categories I write all data in CAPITAL LETTERS and categories can be repeating.
So example table Records looks like this(in columns layout like this: id-item-CATEGORY):
1-sleep-HEALTH 2-ate breakfast-FOOD&DRINK 3-drank
coffee-FOOD&DRINK 4-took eyedrops-HEALTH 5-tram to
work-TRAVEL
I know how to list all data from column Category, but I want to avoid repeating categories. I need to get list of categories like this (Health and Food&drink does not duplicate):
HEALTH FOOD&DRINK TRAVEL
So with this list I can than via php generate html select tag options.
In php part I would use something like this:
$query1=mysqli_query($db,"select * from Records asc”);
while($query2=mysqli_fetch_array($query1)){
echo “<option value=“.$query2[‘category_option’].”>”.$query2[‘category_option’].”</option>”
};
So the result HTML will look something like this.
<select>
  <option value="HEALTH">HEALTH</option>
  <option value="FOOD&DRINK">FOOD&DRINK</option>
  <option value="TRAVEL">TRAVEL</option>
</select>
Can you please point me right direction? Or mention some best practice to reach this kind of functionality. Thanks to all which try to help.
Use DISTINCT in your SQL:
SELECT DISTINCT Category FROM Records
No duplicates will be returned.
Have a play with it on this link https://www.w3schools.com/Sql/sql_distinct.asp
Note that now we are only fetching one column here instead of *.
You can also use GROUP BY:
SELECT * FROM Records GROUP BY Category
https://www.w3schools.com/Sql/sql_groupby.asp

fetching rating data from database to JSON array in php rest api

i'm developing an api that'll provide a rating value for each student. It's a two stage rating system Click Here . In STAGE-I UI view, student list appears with student name and rating points. To rate a student, one have click on the rating stars & STAGE-II appears with some rating categories. The rating of each student depends on this part. Each category's a rating value as Sum_of_Rating_value/rating_numbers. After rating all categories (or rating 2/3 of these), the result will be re-rated as Sum_of_ALL_Category/Category_number and be placed in STAGE-I student list UI view. N.B.:I've done all the calculations.
Now when i call the data in QUERY as:
<?php
$connection = mysqli_connect("localhost","root","pass","DB_NAME") or die("Error " . mysqli_error($connection));<br><br>
$stu_id=$_POST['stu_id'];<br><br>
$sql_query = " SELECT *, FORMAT(((SELECT SUM(view_rating.total_points+view_rating2.total_points2+view_rating3.total_points3+view_rating4.total_points4+view_rating5.total_points5) FROM view_rating,view_rating2,view_rating3,view_rating4,view_rating5) / (SELECT SUM(view_rating.rating_number+view_rating2.rating_number2+view_rating3.rating_number3+view_rating4.rating_number4+view_rating5.rating_number5) FROM view_rating,view_rating2,view_rating3,view_rating4,view_rating5) ),1) as average_rating,(select count(review) from review WHERE stu_id=14 )as review_count FROM student_info WHERE stu_id='$stu_id' ";<br><br>
$user_array=array();<br>
$main_array=array(); <br><br>
$result = mysqli_query($connection,$sql_query);<br>
while($row =mysqli_fetch_assoc($result))
{<br>
$user_array['stu_id']=$row['stu_id'];<br>
$user_array['name']=$row['name'];<br>
$user_array['mobile']=$row['mobile'];<br>
$user_array['email']=$row['email'];<br>
$user_array['gender']=$row['gender'];<br>
$user_array['Dept']=$row['Dept'];<br>
$user_array['blood_group']=$row['blood_group'];<br>
$user_array['average_rating']=$row['average_rating'];<br>
$user_array['review_count']=$row['review_count'];<br>
array_push($main_array,$user_array);<br>
}<br><br>
$mainarray=array("STUDENTS"=>$main_array);<br>
$jsonData = json_encode($mainarray, JSON_PRETTY_PRINT);<br>
echo $jsonData;<br>
?>
In JSON array, it doesn't pull average_rating and review_count from DB. It only shows null.But when i define stu_id as 2 or 3 in WHERE clause, it shows the same average_rating and same review not only in the defined stu_id but also in the other ids. But I want exact average_point/review fro each student. I think, the problem lies in the QUERY. So, can anyone help me out???
Your $sql_query is really hard to read; I would break it up into smaller pieces.
Why do you have (select count(review) from review WHERE stu_id=14 )as review_count as part of the query?
What's special about the magic number 14? It's generally a bad idea to have magic numbers in your code. Who is student 14? Why is this number hard-coded instead of using $stu_id or some other variable? This is probably related to why you're not getting a review_count.
If you do get a review_count when you change this to WHERE stu_id=2 or WHERE stu_id=3, it's probably either because review has entries for students 2 and 3 but not for student 14, or because $stu_id was either 2 or 3 when you made the query. I'd guess the latter.
Since your overall query is wrapped in an outermost FROM student_info WHERE stu_id='$stu_id', it should only grab information for the student with id $stu_id. If that id is not equal to 14, there's no information for student 14, so when you try to run the code for the review count on student 14 it doesn't find anything (you're searching in a dataset that was already filtered to only have data for student $stu_id).
I'm not sure about this because the code is very hard to read as it is currently structured, but I'd guess that's a good starting point for troubleshooting.

MySql data not showing on html form until page is refreshed

I have attempted to research this one and have also tried a number of fixes, all ending up a mess. I am novice with this and am aware I am using a deprecated version of PHP, code is not my job however I am stuck with fixing this for work because I will benefit by reducing errors and getting other people on board to maintain data. I am changing a PHP / MySQL application that was once all full of hard coded select boxes, I have created a small html form to CRUD a set of department names in a table called 'departments' and am now cross referencing this across the site.
The mysql 'department' table has 3 fields department_id, status, department_name
The form I am having trouble with updates a table called 'staff' it allows to CRUD this data in the staff table however on page load of the form it does not populate the department name it shows an empty select box.
The relevant field from the 'staff' table is staff_company.
I am able to open up a drop down box which is populated with all the correct options, if i leave the box untouched and update other data on the form it posts the original correct department_id maintaining the integrity of the data and on refreshing the page the correct department name does show. It is an issue if anyone else uses it as they may think that the field is empty when they try to edit and may make an incorrect selection, it is also sloppy, my thoughts are that I am somehow not declaring the variable early enough any suggestions in novice talk / beginner talk will be appreciated part of code below - plus I need to understand where I am going wrong so I can improve my skills (note page approximately 1600 lines therefore not posting whole page).
//editing departments using department id//
$select_dept_names = "SELECT *
FROM `departments`
WHERE status = 'active'
ORDER BY department_name ASC ";
$run_select_dept = mysql_query($select_dept_names,$link);
print(" <tr><td id='employee_left'>Department:</td><td><select name=\"staff_company\">
<option value=\"".$grab_staff['staff_company']."\">".$dept_data['department_name']."</option>");
while($dept_data=mysql_fetch_array($run_select_dept))
{
print("<option value=\"".$dept_data['department_id']."\">".$dept_data['department_name']."</option>");
}print("
</select></td></tr>");
Many thanks in advance - Cheers Jase
Updated code below
//line 346 queries
$select_dept_names = "SELECT * FROM departments
ORDER BY department_name ASC ";
// line 363 - storing and fetching data
$run_select_dept = mysql_query($select_dept_names,$link);
$dept_data = mysql_fetch_array($run_select_dept);
// line 1147 - editing departments using department id///////////NEEDS WORK Only showing first department then on F5 displays existing department
//var_dump($main_report[department]); die(); - outputs only one line from the 'department' table
if($main_report['department'] = $dept_data['department_id'])
{
print(" <table id='edit_table_within'>Department:</td><td> <select name=\"department\">
<option value=\"".$main_report['department']."\">".$dept_data['department_name']." </option>");
}
else print("<table id='edit_table_within'>Department:</td><td> <select name=\"department\"> <option value=\"\">Select..</option>");
while($dept_data=mysql_fetch_array($run_select_dept))
{
print("<option value=\"".$dept_data['department_id']."\">".$dept_data['department_name']." </option>");
}print("
</select></td></tr>");
If i'm understanding you well enough(and I'm probably not) I would recommend adding a peice of code that automatically refreshes the page when you confirm that data has been added or changed into database. Also you have a blank box in dropdown boxes because you are selecting a default option. Hope I'm understanding your question
After considerable time bashing the code around I have found a solution, this may be ugly and there may be more efficient ways of doing this however here is the final piece of code that works for me
//editing departments using department id//
$select_o_dept_names = "SELECT *
FROM `departments`
WHERE department_id = ".$main_report['department']."";
$run_select_o_dept = mysql_query($select_o_dept_names,$link);
$dept_o_data=mysql_fetch_array($run_select_o_dept);
$select_dept_names = "SELECT *
FROM `departments`
WHERE status = 'active'
ORDER BY department_name ASC ";
$run_select_dept = mysql_query($select_dept_names,$link);
print("<table id='edit_table_within'>Department:</td><td><select name=\"department\">
<option value=\"".$main_report['department']."\">".$dept_o_data['department_name']."</option>");
while($dept_data=mysql_fetch_array($run_select_dept))
{
print("<option value=\"".$dept_data['department_id']."\">".$dept_data['department_name']."</option>");
}print("
</select></td></tr>");

Selecting multiple fields from <option> and adding them to database

Background:
I am creating a three tier e commerce website which sells books. Within my website I have created a form (only accessible to staff members) which allows the staff member to add a new book to the system (the database).
At the moment I have a table within my database which records the following data:
book_isdn // unique identifier of each book.
book_cat
book_title
book_author
etc..
Along with this, I have created a table for book categories which stores the following:
cat_id
cat_title
I have defined the following rows in the categories table:
cat_id 1 = Business books
cat_id 2 = Computing books
cat_id 3 = Science books
cat_id 4 = History books
etc
The problem:
In the form which allows a staff member to add a new book, I have a list:
<select multiple name="b_category" style = "width:150px" required>
<?php
$get_cats = "select * from categories";
$run_cats = mysqli_query($connect, $get_cats);
while ($row_cats = mysqli_fetch_array($run_cats)) {
$cat_id = $row_cats['cat_id'];
$cat_title = $row_cats['cat_title'];
echo "<option value='$cat_id'> $cat_title </option>";
}
?>
</select>
I want to add a new book to the 'books' table with the corresponding cat_id for the category to which the book belongs to (i.e. business, computing etc.).
However, a book can also be in two categories, i.e. a book can be both in the field of business and computing.
The question:
How can I alter the form so that it selects multiple options from and adds them to the database, along with the cat_id?
For example:
if using the form I complete all other fields and select computing and business from the list, I want it so that upon clicking "Add new book", the form data is sent to the 'books' table where I will be able to see the new book and under the field of book_cat, I will see 1,2.
I am completely stumped. Is there any way to approach this issue? I hope I have explained this well.
Thanks.
Ok, let's start with something you have not asked for.
a) DB design
Please do not store a concatenated id value like 1,2 in book_cat.
That makes lookups and search hard, because you need to fetch & split every single time. That might only work for really small systems.
What you are looking for is a relation table from books to categories.
Name it like this books_to_categories, with book_id and cat_id.
Query: SELECT cat_id FROM books_to_categories WHERE book_id = 2;
Result: array one or more ids, then resolve the cat_id to it's name (cat_title) via the category table.
The keyword here is database normalization.
b) Formular
Ok, you have a drop down list box, where you can do multiple selections.
Now, the values of these selections need to be transfered to the server side.
One trick is to use array syntax, instead of
<select name="b_category" size=4 multiple>
just use
<select name="b_category[]" size=4 multiple>
and on the server-side var_dump($_POST['b_category']); to see the values received. Then simply iterate over the values of the array and make your database entries.

SQL queries or php code?

Hello i am in a delima
Suppose that i have 50 products in a category and i want to get all the features of my products...
Ofcourse a SQL join wont help because joining would return product info many times!
So here is the question.. what is better
PLAN A
Get all the products' features in category with one SQL query and then iterate with php each feature and put it in Product.
PLAN B
For each product get the features by calling a query
Other solutions accepted!
EDIT
My table schema outline is..
A table Product which has product info(per row)
A table features which has features (feature id )
A table for features' values
And a table that has Products with their features and values
$sql1 = "SELECT * FROM products P, ". //don't use star, make sure no fields are overwritten
INNER JOIN products_to_features PTF on P.id = PTF.project_id
INNER JOIN features F F.id = PTF.feature_id
ORDER BY P.id";
$r = mysql_query($sql1, $conn);
$arr = array();
$lastProductId = -1;
while ($row = mysql_fetch_assoc($r))
{
if ($row[p_id] != $lastProductId)
{
$lastProductId = $row['p_id'];
$arr['p_id'] = array('productName' => $row['p_name'],
'productPrice' = $row['p_price'],
'productFeatures' = array(),
//other fields from product table);
}
$arr['p_id']['productFeatures']['f_id'] = array('featureName' => $row['f_name'], blah...);
}
I don't know your fields obviously, and you may want to join on feature_values so that will be more work. You can do keys/values different (ie - product names as keys. Feature-name as keys with feature-value as values, whatever you want) but the point is this is doable (and recommended) in one query.
Not Plan B.
Whatever you do this can and should be done with one or at most two total queries (one for headers, one for correctly sorted list of features + id column). Whether that query is Plan A or some unmentioned Plan C depends on your exact table structure, which isn't clear from your question.
Generally, the less database queries you have to make, the better. It greatly depends on your table structure, but I'd go with Plan A.
A query inside a loop will greatly degrade performance of your application. Avoid it at all cost.
Show us the schema. There's a strong possibility a single SQL query will solve your problem.

Categories