Go through result query without foreach loop - php

I am currently working on a project where it would come in handy to deal with a query result without having to use foreach loops to access everything of the array.
Let me explain it with an example:
I am selecting something from the database like
"SELECT * FROM table WHERE clientgroupid = 1"
The shown result is
name country phone clientgroupid
john america 12313 1
mike netherland 3123123 1
So I basically get 2 rows with that content as a result.
Now I would go on and run through that result array with a foreach and output it that way.
But that would limit my output to just 2 rows.
Which in the picture would result in the output of just enough input fields for 2 persons.
What I need is, that I show all results from the database in those input fields.
But there not "filled out" fields should be shown as well - in order to give the Moderator the posibility to fill it out to add more people to the database.
Please correct me if my way of thinking is completly off here - I welcome all suggestions or solutions
Thank you
EDIT
The issue is as following:
When I get 2 rows as a result from the database I would only create 2 lines of content like here :
But I also want to have all other input fields shown, so that the moderator can add more clients if needed.
So the output with 2 found Clients and rest empty fields would look like this:

Related

PHP echoing a specific field from a table in MySQL

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.

Have an array in a SQL field. How to display it systematically?

I have a field in a data feed coming in with some values separated by commas. For one record, the values are:
A06,C05,C06,C15,C18,C19,C21,C22,E05,E22,G11,J02,J07,L04,L07,M01,M05,N03,N07,N10,N11,N12,N18,N19,N20,N24,O02,O03,O04,O06,O09,O14,O15,O16,O20,O21,O31,Q01,Q04,Q08,R07,S08,T08,T12,T23,T32,U01,U03,U04,U06,U13,W09,W11,W16,W19,W30,W45,X02,X03,X12,Z07
I have a separate table with some descriptions as to what each code means. When I query the main table and get this field name as a value, I can use explode to get it into an array and use a foreach loop to output each value.
The problem is, I want to display the description stored in another table. What's the proper way of iterating through this to display these values in a list?
As an example, C21 means "Gated Community."
You can use FIND_IN_SET() function for that.
Example you have record like this
Orders Table
------------------------------------
OrderID | attachedCompanyIDs
------------------------------------
1 1,2,3 -- comma separated values
2 2,4
and
Company Table
--------------------------------------
CompanyID | name
--------------------------------------
1 Company 1
2 Another Company
3 StackOverflow
4 Nothing
Using the function
SELECT name
FROM orders, company
WHERE orderID = 1 AND FIND_IN_SET(companyID, attachedCompanyIDs)
will result
name
---------------
Company 1
Another Company
StackOverflow
As you have tagged codeigniter you could use the built in Active Record's method $this->db->where_in(); to get the description. For example consider the code below
$codes = array('A06', 'C05', 'C06');
$this->db->where_in('description', $codes);
// Produces: WHERE codes IN ('A06', 'C05', 'C06')
For more information about Active Records of Codeigniter refer Active Record Class
For more information on how mysql WHERE IN works refer Tutorial
Just for follow the books, the best way of doing this in SQL language is to use the relationship.
For understand this I recommend you read this simple paper http://net.tutsplus.com/tutorials/databases/sql-for-beginners-part-3-database-relationships/
and maybe this http://www.informit.com/articles/article.aspx?p=30875&seqNum=5 for SELECT the data, or search for yourself on the web, and I recommend you to try yourself the examples. SQL Relationship Is good and necessary for security and many others reasons.

Generic structuration of a web form and a MySQL's table for saving a array of undefined length

In a web form i will ask the user for their job experiences, this data will have no fixed lenght. I need to let the user insert all the items he needs, every item will content 3 fields; job title, description and year.
My firts problem is, how can i ask in the html form for the items? i mean, whats the best way to ask items with no fixed lenght using html/php (and maybe ajax)? I saw some sites that have a button (add one) when you hit it a new item slot is showed, but i have no idea of how to implement this, an example will be sufficient.
The second part is, how can i managed the data flow in post or get?, until now, i only use fixed fields, so i always know in my php script how many post or get vars i will get. How can i use multiple POST vars without knowing the amount of them?
And the last one (and the more important), how will be the best structure for my table in MySQL? If i get multiple items for a fixed table where i will have all my users, how can i resolve the multiple items issue? For example, if my table is:
User | password | job_experiences
admin | root | (this is just a cell, how can i save multiple items here?)
jonh | 1234 | (this is just a cell, how can i save multiple items here?)
Thanks for any help!!!!
Those are 3 questions, and it's best to post 3 questions, instead of discussing all of them. I will post the basics, and if you have specific questions, ask.
First, use button to add, and a JavaScript to clone an existing row (which can have more then one input field). For fieldnames use something like company_name[] - the [] is the important part, at this will send the field as an array. If you are editting profile, you can use company_name[$id] to preserve the mapping.
Second, in PHP you will receive this as $_POST['company_name'] which will be numeric array with all the company names. Or if you specify $id - with the corresponding keys. So, you have to loop trough all company_names, if there are other fields - you retrieve them the same way, using the current key. Example:
for (i =0; i<$_POST['comany_name'].length;i++) {
$company = $_POST['comany_name'][$i];
$start_year = $_POST['from'][$i];
...
}
Next, you need 1 table for the users (username, password), and another for job experiences (userid, company, description, from, to). This is called 1:M relation

PHP MYSQL edit form, trying to implode/explode row to checkboxes?

I have a form that has multiple categories. They are separated by checkboxes, so one could check any number of categories that their post/story will be in.
The values are stored inside a db row separating them by commas while INSERT
GetSQLValueString(implode($_POST['r_category'],", "), "text"),
So in the database I could have an entry that looks like this:
2,3,6,12
Which those are category numbers.
I am now building an edit form feature to use to Edit and UPDATE these records. I can not find a way to "EXPLODE" the values into checkboxes on the edit form??
So if you log in and go to the ENTRY that you want to edit for example, I have Checkboxes separating the Categories, so it will be easy to check and uncheck to add and not add... I have tried everything I could to get the values to POST and be checked when viewing this Edit Form.
Here is an example of one of my Category Check boxes on my edit form page, but it is not working when I have multiple Categories, like the example above.. 2,3,6,12 ?? :
<input type="checkbox" name="r_category[]"
<?php if (!(strcmp("2", $row_Recordset2['r_category']))) {
echo "checked=\"checked\"";} ?> value="2" />Cat 2
Thanks in advance NINJAS!!
I can not find a way to "EXPLODE" the values into checkboxes on the edit form
This line is so close to the answer that I'm seriously wondering if this is a joke post.
Given your database structure as it is, you can use the explode() function to break the value into an array based on a delimiter. For example:
$values = "1,2,3,4";
$array_of_values = explode(",", $values);
After this, $array_of_values will contain an array of four elements with the values of 1, 2, 3, and 4 respectively.
When deciding whether or not to display the checkbox as checked, you can use the in_array() function to make that call:
if (in_array("2", $array_of_values)) {
echo 'checked="checked"';
}
Beyond that, let me take this opportunity to second what #MarkB said in the comments on this question: it's a bad idea to hold multiple values in a single database field. It makes searching for things harder, it makes adding values harder... it just makes everything more complex than it needs to be.
The best way to handle this would be to have a many-to-many table which stores rows of items and categories, with one row for each category that an item belongs to.
In other words, where you currently have this:
Item | Category
---------------
123 | 1,2,3,4
You would instead have a table that looks like this:
Item | Category
---------------
123 | 1
123 | 2
123 | 3
123 | 4
You can use it as shown below it could be helpful
if (in_array("2", $row_Recordset2['r_category'])) {echo "Checked";}
That in_array conditional never did work for me. I devised a totally front-end solution instead that works like a charm and automatically updates itself based on changes to the database. If you're interested, check it out here.
https://stackoverflow.com/a/26433841/1896348

Combining multiple rows or results with the same title to form drop down menus with PHP and MySQL

So I am picking up a project that was quit halfway through by the last guy so that I could get some more practice with PHP and databases. I have run into a problem, and I am sure it is common enough that there is a standard solution, but I am unable to find one.
The db I am working with has 4,600, so reorganizing is out of the question. It is a db of liquers for a wholesaler. Here is what the results page looks like currently:
What I am trying to set it up so the results are returned in list form, with only one title and dropdown menus for the different sizes/prices of products that looks like this:
The problem is that there are multiple entries in the db for each product. In this example there are 3, while some have 1, and some have 2.
I am really not sure how to go about this, and any help would be greatly appreciated. Thank you.
I'm not sure about the PHP syntax, but pseudocode here's what you could do:
allProductsReturnedFromMySQL = QueryYourDatabaseForAllProducts()
Hashtable[productId, List[productSizes]] dropDownsByProduct;
Hashtable[productId, commonProductInformation] uniqueProducts;
foreach (product in allProductsReturnedFromMySQL) {
if product.productId not in uniqueProducts
then add it with the product information that does not vary
if product.productId not in dropDownsByProduct
then add it with an empty list
append the size of this product to the corresponding list in dropDownsByProduct
}
After that little bit of logic you'll have all your unique products with the common properties for each one, and a way to fetch the corresponding sizes drop down. If you wanted to do this purely in SQL to minimize the data that's transferred, you could do something like this:
-- this would get you your products
select distinct id, property1, property2 from product
-- this would get you your drop downs by product
select id, size from product order by id
You can then build the same drop down hashtable by iterating through the second result set.
I'm not sure if this is the best way, but I've always approached this by altering the query so that it is sorted by product name. Then as you iterate through the rows, check to see if the product name matches the one you just processed. If it's the same, then this row is a different size of the same project.

Categories