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>");
Related
I'm trying to understand how to write a query to distinguish if a user has access to certain form or not. I know what I am asking here looks easy but when I tried to implement it, it was whole different thing.
Maybe I am doing it wrong.
Before starting I want to mention the two tables names in start:
sys_forms,
sys_forms_in_groups
Also I am putting a SQL Fiddle link at the end.
Here is what I am trying to do.
If you can see the picture, on top dropdown box (it's a select2 dropdown), user selects the group and it will return GroupID, on the base of which I want to populated the below datatable. (DataTable is just showing groups, it's a dummy, but it will show forms, will fix it if problem is solved)
Now here the problem arise:
I want datatables to show all the forms available in sys_forms table in datatables but in actions columns of datatables only those checkboxes/switches should show granted which are available in the selected group(Group can be selected for select2 dropdown as said before).
GroupID is the column of other table sys_forms_in_groups.
All I want is that all the forms should show in the datatables no matter what group I choose, but Actions column in table should display Granted if the group has access to that particular form.
forms_in_groups is for showing if group has access to that certain form or not. For example:
FormID GroupID
------------------------------
1 1
2 1
1 2
FormID 1 is available to both groupID 1 and 2, on other hand FormID 2 is avaialable only to GroupID 1.
Here is my SQL Fiddle.
Edit
The SQL Fiddle is not working, so putting screenshots here.
Table : sys_forms
Table : sys_forms_in_groups
I have tried this query, but it only returns forms for the selected group, where I want that all forms should show but they must show granted in Actions Columns on checkboxes/switchButtons
SELECT * FROM (`sys_forms`) INNER JOIN `sys_forms_in_groups`
ON `sys_forms_in_groups`.`FormID` = `sys_forms`.`FormID` WHERE `GroupID` = 1;
I think you're, incorrectly, trying to offload the issue onto MySQL.
It's not MySQL's job to render the forms and show whether a selected group has access to a specific form. That will fall onto your rendering of the page; using Select2 in this case.
You just want to retrieve all forms, then show whether the selected group has access to a specific form. That comes down to some Javascript that makes that check for you and displays it properly.
If you want to return all forms, the query would be:
SELECT * FROM (`sys_forms`) INNER JOIN `sys_forms_in_groups`
ON `sys_forms_in_groups`.`FormID` = `sys_forms`.`FormID`;
If you only want the forms that group 1 has access to, the query would be just as you have it:
SELECT * FROM (`sys_forms`) INNER JOIN `sys_forms_in_groups`
ON `sys_forms_in_groups`.`FormID` = `sys_forms`.`FormID` WHERE `GroupID` = 1;
I didn't do a lot of digging into Select2, so I can't really help you in that aspect.
What I can see from your database schema, an inner join is the correct choice here based on the data you are looking for. The only issue I can see is in the WHERE clause. Seems that it may try to look for GroupID in the sys_forms table, so try specifying.
SELECT * FROM (`sys_forms`) INNER JOIN `sys_forms_in_groups`
ON `sys_forms_in_groups`.`FormID` = `sys_forms`.`FormID` WHERE
`sys_forms_in_groups`.`GroupID` = 1;
Finally Problem Solved and working perfectly fine, but after solving that problem i found out there is an other issue i didnt think of, but thats another matter. xD.
However, It was a little rough way to solve but i got what i wanted.
Here is how i did it,
I first needed to update my select query to,
SELECT f.FormID
, f.FormName
, f.FormCIPath
, MAX(g.IsMenuLink) AS IsMenuLink
, GROUP_CONCAT(DISTINCT g.GroupID ORDER BY g.GroupID) AS GroupIDs
FROM `sys_forms` f
JOIN `sys_forms_in_groups` g
ON g.FormID = f.FormID
AND g.GroupID IN (1,2)
GROUP BY f.formID
Here you can see it will return all the forms which belongs to group 1 and group 2 but in a way that 1 and 2 will be in same column separated by comma.
Here how it shows now.
I am not a very complex query master so i am very much grateful to stackoverflow community to help me with the query. As i wanted to join both results to show in comma separated value.
After the MysQL the jquery work was not much difficult, i only sent the group ID for which i wanted the result to show in table. and there i got this result in return where i separate the GroupIDs with javascript split function and i get my groups.
Thankyou again everyone.
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>";
}
?>
Firstly, I'm quite new to PHP having only dived in some three weeks ago but loving it as a new thing to learn! I have a specific problem that I cannot seem to find a solution for via Google. I'm running a test page that will form the basis of a final product for a local recreational club that runs competitions and wants to display the results online on their website.
I've created a MySQL database and called it 'results' and imported as a CSV a sample of competition results. My code to connect to the database works as the page displays the "Database Connection Established" message.
The database contains a table called 'z_any_year_results' and the table structure looks like this:-
Record_Number Field Value
1 Field_1 Value_1
2 Field_2 Value_2
3 Field_3 Value_3
4 Field_4 Value_4
5 Field_5 Value_5
I understand how to select the specific table using
mysql_select_db("results") or die(mysql_error());
$data = mysql_query("SELECT z_any_year_results FROM results")
but I need to echo a specific field from the table in a specific section of the web page. So for example, in one section of the page I need to output the field containing the value Field_1 and nearby on the page the field containing the value Value_1. But in another section of the page I need to output the field with the value Field_4 and nearby on the page, the field containing the value Value_4. So I guess my problem is how to extract a specific piece of data from a table to the exclusion of all other records in the table and outout it as an echo on the web page. I cannot find anything on the web that is written in a simple step-by-stepway to help novices like myself understand.
Can anyone point me in the right direction on how to achieve this?
Many thanks in advance.
You are using a type of data design known as key/value design. In other words, each row has the name of a data item and its value. That's not an ideal sort of design for a beginner to use, because it makes for fairly intricate queries.
To answer your question, if you want a certain named field's value you use this query.
SELECT Value FROM z_any_year_results WHERE Name = 'Field4'
But, maybe you want a design that resembles your application's entities a little more closely.
You might have an entity, a table, called, contestant, another called contest, and another called prize.
contestant is a table with columns like contestant_id, surname, givenname, email etc
e.g. 1 , Ellison, Larry, larry#oracle.com
Then you can use queries like SELECT * FROM contest WHERE YEAR(datestart) = 2016 which will make your queries more closely reflect the logic of your application.
I am building a website with PHP, I am not so good at php but i have found good tutorial online.
The website is for people to register as a dog walker, so when someone registers i want them to check the box of the areas that corresponds to them but there are many areas (100+) so I do not know whats the best way to do it using php and mysql. (i dont know anything about JS but i cant look for tutos)
Should all the names of the areas be store in one fild in the database or i have to build one field for each area?
I want people to be able to update the areas.
Then i wanted to have a select form with the search button.
I just want to know in words what is the best way to do it.
Thank you.
I think the best practice is to get a one-to-many relationship in your database. Which means in a simplified way '1 walker can have many areas'.
If I understond Sable Foste's comment correct, he's telling you to create one column in your user table for each area, this would require a massive database table. Besides, updating your script would be a huge pain in the ass since you would have to add each area manually. Instead I would suggest you to create two tables:
table users
user_id
user_name
table areas
area_id
area_name
Fill the areas table with all options you have. Now, when a user wants to register on your page, you can perform an SQL query which fetches all areas like so:
$areas = $database->query("SELECT * FROM areas ORDER BY area_name ASC");
if( $database->num_rows( $areas ) > 0 ) {
foreach( $database->fetch_array($areas) as $area ) {
echo '<input type="radio" name="area[]" value="'.$area['area_id'].'" /> '.$area['area_name'].'<br />';
}
}
$database illustrates a database wrapper in this example. You can also use mysql_ functions, however, they are about to be deprecated from PHP, so instead try to find tutorials on mysqli_ functions or PDO database layer.
As you can see I've named the fields area[], by doing this we get an array after we submit our register form. This array can be looped and contains all checked radio buttons. Each radio button contains the area_id:
if( isset( $_SERVER['REQUEST_METHOD'] == "POST" )) {
// Make sure you check data here and insert the user in the database first before proceeding
foreach( $_POST['areas'] as $area_id ) {
// Do something with the $area_id
}
}
Since we still have no option to connect the area_id to the user_id. To do so, we create another table that saves the connections:
table users_to_areas
area_id
user_id
In this database you will store each $area_id together with the $user_id of a newly registered or logged in user. NOTE: if you are updating a userprofile you can simply delete all previous records (DELETE FROM users_to_areas WHERE user_id = $user_id) and insert them again using the same looping method as above.
On the edit profile page, you can use the same script to list all areas again, to see if a user is connected to the area you can use a simple query (SELECT COUNT(*) FROM users_to_areas WHERE user_id = $user_id AND area_id = $area_id), if the num_rows() function returns 1 then the checkbox should be checked, otherwise it should be unchecked.
Hope this kicks you off in the right direction, good luck.
You should store all of your fields in separate rows. So if you have 100 areas, you should have 100 1 column rows (you can have more columns if there are other corresponding information you want to store).
The rest of your question is much more open-ended. You'll need to show some examples of what you are working with or have built to make it more clear
I am building my first PHP/MySQL site and i would like to return search results from two fields in my one table within the database - Catagory, and Location (There are 15 fields in total in the table, but there are only two required for the search).
Each option will have a drop down menu which will list a fixed number of choices in each field - for instance, there will probably be 15 or so Locations, and 7 or 8 Catagories.
I want the user to be able to select an item from either one or both drop down menus, click a 'Search' or #Go' button, and be presented with the results.
As mentioned, i am brand new to PHP/MySQL so apologies if my question is a little 'simple' and i hope someone can point me in the right direction.
Thanks
Dan
EDIT:
Brad, Conner, I don't have anything thus far i'm afriad in terms of the search query specifics, i'm just starting to research how to do it hence complete lack of code in my question!
But to try and be more specific, the only fields i want to return results from are Location and Job Catagory - these are two fields of about 15 in my table that are already populated with fixed terms - e.g, Location may have London, Manchester, Leeds, and Catagory may have Administrative, Management, Clerical etc - there is no option for the visitor to input a new term, only select from a drop down menu of pre-arranged items.
The other fields in my table aren't relevant to the search (salary, company, contact email etc), so...I am thinking i only need two queries, and results can also be displayed if you only send one (e.g, you aren't bothered about job location, just speciality, you could still find all the results and decide if you fancied relocating). Is that any better or more helpful?
Thanks for you help so far.
Dan
A user enters a search query and you'd like to select the rows from your table that contain or exactly match that query? If so, something like
For if category contains $search_query
SELECT category, location
FROM table
WHERE concat(' ', category, ' ') LIKE '%$search_query%'
Or if it is an exact match you would use this for your conditional instead:
WHERE category = '$search_query'
I'm probably offtrack though, you need to specify like Brad said
Dan you need to build your sql statement dynamically. Below is a simple peice of code to demonstrate what I mean. Always besure to escapse user data to provent sql inject.
if ( isset($_POST['go']) ){
$location = $_POST['location'];
$category = $_POST['category'];
$sql = "SELECT * FROM table ID IS NOT NULL ";
if ( $location !="" ){
$sql .= " AND location = " . $location;
}
if ( $category !="" ){
$sql .= " AND category = " . $category;
}
}
Without any details on your table structure and the data in question, the basics would be somethign like:
SELECT ...
FROM ...
WHERE (field1 = $location_option) or (field2 = $category_option)