Indexing alphabetically ordered table with A-Z as "links" - php

I have a rather complicated question but perhaps you already understand what I am trying to accomplish by reading my title, hopefully.
I have a big list stored in SQLite and I am outputting the table into my webpage using php looping, but the problem that still remains is how to add index per letter.
For instance you have a list of items, each of which range from A all the way to Z
I only want to display every letter at one time, so if A comes first then only A should by default be visible
the rest should be accessed using a tab or link system with indexing (A - Z)
feedback please!
$stmt = $db->prepare('SELECT Title, Description, Alternative FROM TblOne;');
$stmt->execute();
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "<table>";
echo "<thead><tr><th>Title</th><th>Description</th><th>Alternative</th></tr></thead>";
foreach($res AS $val) {
echo "<tr>";
foreach($val AS $val1) {
echo "<td><a href='.html'>$val1</a></td>";
}
echo "</tr>";
}
echo "</table>";

If you want to get the letters that start the field, use:
select distinct left(title, 1)
from tblOne
If you want to get the list that starts with a given letter:
SELECT Title, Description, Alternative
FROM TblOne
where left(title, 1) = LETTERYOUWANT

Related

Print a database table and colour the parent row basing on its child colour

A PHP page must show the content of a database's table. In another table, there is the value I will use to print the row accordingly and show as a child.
$result = pg_query($conn, "SELECT *,'SENT' as direction FROM table1 WHERE identification LIKE '%$identification%' AND expedition LIKE '$expedition' order by date DESC LIMIT '$limit' ");
This, inside a WHILE, will print this kind of table:
while ($row = pg_fetch_row($result)) {
$sql2 = pg_query($conn, " SELECT quantity FROM expedition WHERE identification='$row[2]' ");
$row2 = pg_fetch_row($sql2);
$color="white";
if ($row2[0] == "-1") { $color="red";}
if ($row2[0] == "1") { $color="green";}
if ($row2[0] == "0") { $color="grey";}
echo "<tr bgcolor=\"$color\">
<td><button class=\"btn btn-info\" type=\"button\" data-toggle=\"collapse\" data-target=\"#$row[2]\">+</button></td>
<td>row[0]</td>
<td>row[1]</td>
<td>row[2]</td>
<td>row[3]</td>
<td>row[4]</td>
<td>...and more</td>
</tr>";
echo "<tr><td colspan=9><div style=\"background-color:$color\" id=\"$row[2]\" class=\"collapse\">$row2[0]</div></td></tr> ";
I am using bootstrap to add a button that, once clicked, will open a hidden row with the content of $sql2. Query that I will print straight after the </tr>.
Notice the 1st query as row[] and the second query as row2[].
The problem:
If the second query contains more than 1 result and in all cases identification is not a PK (therefore there could be more), I am not able to print for each row the colour of its childs.
I need to extend the second query to manage a WHILE loop, in order to extract, through identification, all the values of its parent.
IF, sql2 contains -1 or 1 or 0, the parent and itself must be painted accordingly.
IF, sql2 contains different values, both of them must be painted red (as error).
The obvious choice would be to move the SQL2 at the end of the first WHILE, in this case I can have SQL2 with all the records I want.
just like using arrays or the FOR structure.
Stays though the fact that moving the code would not allow me to print all the rows, because html is wrote already.
In this case I believe I'd need Jquery to highlight the values once they are written already.
I do not know a thing of Jquery and I'd appreciate any suggestion or help.
Attached a image to show what I achieved, the green bar only contain 1 child as the code above. Forgive the ugly interface!

Create a table with blank squares for missing mysql data

I've written a PHP script that can populate a table in a particular way so that multiple events (or no events) can be put in one square in an HTML - similar to the layout a calendar would have. But, there's a problem, the while statement I created to fill in squares in the table when there is no data doesn't detect when there is data, and fills the entire table with empty squares. This is what the output looks like (The page is styled using Bootstrap 3). From the mysql data I have provided, these events should be in the square at {Period 1, Monday}.
Here is my data in a mysql database; mysql data
Here is a snippet of the part of the page related to this table;
<?php
$query = "SELECT * FROM configtimetabletwo WHERE term = ".$term." AND week = ".$week." ORDER BY period, day LIMIT 100;";
$results = mysqli_query($conn, $query);
$pp=1; //The current y value of the table
$pd=0; //The current x value of the table
echo '<tr><td>';
while($row = mysqli_fetch_row($results)) {
while((pd!=$row[3] or $pp!=$row[4]) and $pp<6){ //This while statement fills in empty squares and numbers each row.
if($pd==0) {
echo $pp."</td><td>";
$pd++;
}
elseif($pd<5){
echo "</td><td>";
$pd++;
}
else {
echo "</td></tr><tr><td>";
$pd=0;
$pp++;
}
}
echo '<a href="?edit='.$row[0].'" class="label label-default">';
echo $row[5].' '.$row[6].' - '.$row[7]."</a><br>";
}
echo "</td></tr></table>"
?>
I haven't been able to figure out why this happens so far, thanks in advance to anyone who has any idea what's going on.
In the comments below my question, pavlovich pointed out the error. In this case, it was simply an issue of forgetting to use a $ to reference a variable. It would seem that this doesn't throw an error in a while statement like it would elsewhere.

How to display sql row in option list on php page

I have create 3 categories. in sql named as Buyer, Seller and Common.
I want to display them in my page as select option with drop down.
basically i want if user post some thing. he should chose that category. and in future if any one click on these categories.
it should display all the content which linked to that category.
here is my php
include "connect.php";
$sql="SELECT Seller,Buyer, Common FROM category order by name";
echo "<select name= Buyer value='Buyer'>Buyer</option>";
foreach ($dbo->query($sql) as $row){
echo "<option value=$row[Buyer]>$row[Seller]</option>";
}
echo "</select>";
and my data base table
replace this line, also add quotes to your value and use {}
echo "<option value='{$row['Buyer']}'>{$row['Seller']}</option>";
^ ^
Also when you are concatenating the arrays in echo, its good to use {}, else you will get syntax errors.
try this
foreach ($dbo->query($sql) as $row) {
echo $row['Seller'];
}

Update MySQL-database with array values

How can I update a database with the values from an array? For example, let’s say we got a database with three tables:
Meals:
mealnr(PK), name, sort
Ingredients: ingredientnr(PK), name, stock
Structure: mealnr(FK), ingredientnr(FK), amount
I filled the database with some meals and ingredients. Every meal consists of multiple ingredients. The chef decides you only need 75g of ingredient x instead of 100g for meal y, so it needs to be changed in the database. Of course it can be done with SQL-commands, but I want to do it using a form in PHP.
First I made a page where all the meals are displayed. A meal can be edited using the edit-button next to it and based on the mealnr, you can change the amount of one or multiple ingredients for that particular meal. On the edit-page all the ingredient names and amounts are displayed in a table. The amount fields are textfields, those can be edited.
I made this script, but I don’t know exactly how I can update my database with the values of an array. I tried it with a foreach-loop, but it doesn't work.. yet. Can somebody help me?
<?php
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db("eatit", $conn);
$id = $_REQUEST['mealnr'];
$result = mysql_query("SELECT meals.name AS mealname, structure.amount, ingredients.name AS ingredientname
FROM Meals, Structure, Ingredients
WHERE meals.mealnr = structure.mealnr
AND structure.ingredientnr = ingredients.ingredientnr
AND meals.mealnr = '$id'");
if(isset($_POST['save']))
{
$new_amount = $_POST['amount[]'];
foreach ($new_amount as $value) {
mysql_query("UPDATE structure SET amount ='$value', WHERE mealnr = '$id'")
or die(mysql_error());
}
}
mysql_close($conn);
?>
<p><strong>Ingredients:</strong></p>
<?php
echo "<table>";
echo "<tr>";
echo "<th>Ingredient</th>";
echo "<th>Amount (gr)</th>";
echo "</tr>";
while($ingredient = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>";
echo $ingredient['ingredientname'];
echo "</td>";
echo "<td>";
echo '<input type="text" formmethod="post" name ="amount[]" value="' . $ingredient['amount'] . '" />';
echo "</td>";
echo "</tr>";
}
?>
<input type="submit" name="save" value="save" />
In your HTML markup you have declared the elements holding the name amount as an array by using amount[].
So, in your php code that receives the data it's enough to just refer to the amounts this way:
$new_amount = $_POST['amount'];
instead of:
$new_amount = $_POST['amount[]']; // in fact, this is wrong
Your foreach is fine, you should add some checks so that the $value actually contains a value that you expect, for example an int, float or not less than zero (or whatever checks you find necessary).
foreach($new_amount as $value){
if($value != '' && $value >= 1){
//sql statements goes here.
}
}
Receiving form data this way and then directly injecting the result to your SQL statement is always dangerous:
$id = $_REQUEST['mealnr'];
If you declare that you expect an integer (as the id's should be) before you directly inject the code to your SQL statement you have already written safer code.
$id = (int)$_REQUEST['mealnr'];
Also, just for the record - the mysql_* library is deprecated. As pointed out in the comments, try using PDO or mysqli instead - really!

Nested while loop in PHP is not working for MySQL database queries

All the whole day I'm trying to solve this problem but still no luck.
The scenario is: I am developing a vertical menu which should query groups and items of those groups in a menu respectively, but groups are being populated without its items.
Code was written in the following way:
$data1 = mysql_query(select groupnames from groups where categoryy='Agriculture');
while($info1=mysql_fetch_array($data1))
{
echo $info1[0];
$data2==mysql_query(select itms from groupitems where categoryy='Agriculture' and groupname='$info1[0]');
while($info2=mysql_fetch_array($data2))
{
echo $info2[0];
}
}
In the above code, groups are being populated nicely but no items from groupitems table are being populated. If I write Grain (Grain is one of the group of agriculture in my database) instead of groupname=$info1[0] then it works. But it should be got dynamically from the query.
Please help, I'm in trouble.
at last its solved! here's the code:
<?php
include "aPannel/dbconn.php";
$query="select GroupName from categorygroup where categoryy='Agriculture'";
$i=0;
$result=mysql_query($query);
$num=mysql_num_rows($result);
$groupname=mysql_result($result ,$i ,"GroupName");
mysql_close();
if ($num=="0") echo "<p>Sorry, there are no groups to display for this Category.</p>";
else
{
echo "<p>There are currently <strong>$num</strong> groups represented in our database.</p><br>";
while($i < $num)
{
$groupname=mysql_result($result ,$i ,"GroupName");
include("aPannel/dbconn.php");
$query2 = "SELECT subcategory FROM groupsubcategory WHERE groupname='$groupname'"; // count number of items in each group
echo $query2 . "<br/>";
$resultt=mysql_query($query2);
$countt=mysql_num_rows($resultt);
mysql_close();
echo $countt . "subcategories" . "<br/>"; // display number of items
$i++;
}
} // end if results
?>
Your queries are not wrapped around double-quotes (" ") . Always remember that what you pass to mysql_query method is a string argument. And also $data2==.... seems wrong.
So, change the code like this
$data1=mysql_query("select groupnames from groups where categoryy='Agriculture'");
while($info1=mysql_fetch_array($data1))
{
echo $info1[0];
$infoTemp=$info1[0];
$data2=mysql_query("select itms from groupitems where categoryy='Agriculture'
and groupname='$infoTemp'");
while($info2=mysql_fetch_array($data2))
{
echo $info2[0];
}
}
I hope it should work
EDIT: Also are you sure column itms in second query or items ?
EDIT: added temporary variable

Categories