Dynamic sort by header in PHP - php

I'm trying to create a dynamic header on Name which gives the user the ability to sort by ASC or DESC, the results is from the 'register'-table in MySQL. I have tried a couple of codings, but it hasn't given the correct result as of now. Hope anyone is able to help me :)
I have tried making another variable, but I couldn't manage to create the correct one.
<?php
$sql = "SELECT * FROM register";
if($sqlData = mysqli_query($db, $sql)) {
if(mysqli_num_rows($sqlData) > 0) {
echo "<table border ='1' bgcolor='#FFF' width='100%'>";
echo "<tr>";
echo "<th><a href='overview.php?order=name'>Name</a></th>";
echo "<th>Score</th>";
echo "</tr>";
while($row = mysqli_fetch_array($sqlData)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['score'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($sqlData);
} else{
echo "No results in DB";
}
} else{
echo "Error couldn't connect $sql. " . mysqli_error($db);
}
mysqli_close($db);
?>

Hm, that's not a good idea to sort table using MySQL each time user clicked on the table's header.
I suggest you to use javascript for it. Example

Related

Data not required is being displayed

I have a form where the user enters data e.g. AXZAA QS1QS. This data is Posted to my PHP script. The PHP Script connects to a MYSQL database which contains at the moment 2 records.
The idea is that the PHP script will take the input and compare it to the records in the database. If the records exist they are displayed in a table on a web page otherwise, an error message is displayed.
I am having a number of problems with my PHP script and have modified my script a number of times. However, the thing I am having the biggest problem with is this:
When the form appears for the first time, the message record doesn't exist appears twice, this is before the user has entered any data and is seeing the form for the first time. See picture below.
After entering data (when the PHP script was partially working correctly), if there is a match i.e. records existed, along with the records in the table I would receive an error message telling me that records were not found. To see if I could resolve the problem I added code to tell me what records could not be found, the records that couldn't be found were the ones that were found and the other records from the database which I wasn't looking for. I know the SQL query in my PHP script tells the script to get everything from the database however, I would have thought the if statement would have fixed the problem.
Sorry about writing such a long problem and I hope it's not confusing.
enter code here
<?php
//Connect to the database connection file
require 'databaseconnection.php';
$searchBar=(isset($_POST['searchBar']) ? $_POST['searchBar'] :null);
$userdata = trim($searchBar);
$cleaned_data = preg_split('/[\s]+/', $userdata);
$sql = "SELECT DISTINCT * FROM atable_2";
$result = mysqli_query($database_connection, $sql);
echo "<table border>
<tr>
<th>Allocation</th>
<th>Codes</th>
<th>Names</th>
</tr>";
while($putdatabaseanswer_intoarray = mysqli_fetch_array($result)) {
$allocation_id = $putdatabaseanswer_intoarray["allocation"];
$codes_id = $putdatabaseanswer_intoarray["codes"];
$names_id = $putdatabaseanswer_intoarray["names"];
foreach($cleaned_data as $value) {
if($value==$codes_id) {
echo "<tr>";
echo "<td>" . $allocation_id. "</td>";
echo "<td>" . $codes_id . "</td>";
echo "<td>" . $names_id . "</td>";
echo "</tr>";
}
else
{
echo "<br />";
echo "One or more of the records have not been found: $codes_id";
echo"<br />";
}
}
}
echo "</table>";
?>
Wouldn't it be better to assign $searchbar after an if statement like
`<?php
//Connect to the database connection file
require 'databaseconnection.php';
if(isset($_POST['searchBar']))
{
$searchbar = $_POST['searchBar'];
$userdata = trim($searchBar);
$cleaned_data = preg_split('/[\s]+/', $userdata);
$sql = "SELECT DISTINCT * FROM atable_2";
$result = mysqli_query($database_connection, $sql);
echo "<table border>
<tr>
<th>Allocation</th>
<th>Codes</th>
<th>Names</th>
</tr>";
while($putdatabaseanswer_intoarray = mysqli_fetch_array($result)) {
$allocation_id = $putdatabaseanswer_intoarray["allocation"];
$codes_id = $putdatabaseanswer_intoarray["codes"];
$names_id = $putdatabaseanswer_intoarray["names"];
foreach($cleaned_data as $value) {
if($value==$codes_id) {
echo "<tr>";
echo "<td>" . $allocation_id. "</td>";
echo "<td>" . $codes_id . "</td>";
echo "<td>" . $names_id . "</td>";
echo "</tr>";
}
else
{
echo "<br />";
echo "One or more of the records have not been found: $codes_id";
echo"<br />";
}
}
}
echo "</table>";
}
else{
echo "<p>Please enter a search term</p>";
}
?>
You could then execute the MySQL query within that "if" statement rather than having it execute assuming there is a value

How to display dates in two html tables side by side according to month?

I am trying to display status of employee for each date in a month in the given application.
i have divided data in two tables.
Now, if you can see , My tables are displaying dates correctly.
But i want to start new table for each month. i.e. whenever 1st date of new month begins, i want to start the procedure of rendering dates for the month again.
So i will be able to distinguish them by their months.
I hope i have explained the problem correctly.
Please provide guidance on this .
Thanks in advance.
My code for the given problem :
<?php
$name=$_SESSION['sess_username'];
$dateofattendance=$_SESSION['sess_date'];
$time="00-00-00";
$status="absent";
$counter=0;
$conn = new mysqli('localhost', '', '', 'test');
$sql="SELECT dateofattendance,timeofattendance, status,timeofdeparture FROM attendance Where emp='$name' ORDER BY dateofattendance ASC ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
echo "<table class='main'><tbody><tr><td >";
// create the opening table
echo "<div align='left'><table class='sep1'style='float:left;'; border='black' cellpadding='5' ><thead> <tr><th> Date </th><th>IN</th><th>OUT</th><th>Status</th></tr></thead>tbody>";
while($row = $result->fetch_assoc())
{
// create the row
echo "<tr><td>" . $row["dateofattendance"]. "</td><td>" . $row["timeofattendance"]. "</td><td>" . $row["timeofdeparture"]. "</td>";
if($row["status"]=='present')
{
echo "<td ><span class='label label-success'>". $row["status"]."</span></td>";
}
else
{
echo "<td><span class='label label-danger'>". $row["status"]."</span></td>";
}"
</tr>";
$counter++;
// when the counter is 15, close this table and open another
if($counter == 15)
{
echo "</td><td>"; // move to the next cell in our wrap table
echo "</tbody></table></div> ";
echo "<table class='sep2'style='float:left;'border='black'cellpadding='5'><thead> <tr><th> Date </th><th>IN</th><th>OUT</th><th>Status</th></tr></thead><tbody>";
}
}
// close the last table
echo "</tbody></table>";
// close our wrapper table
echo "</td></tr></tbody></table>";
}
$conn->close();
?>
Instead of having a counter and creating a new table when it hits 15, you want to have a variable that stores the month number of the last row rendered, and check if the month number of the next row to be rendered matches. If it doesn't match, generate a new table.
The following code is produces the results you want. I've tested it with a database table with identical structure (table named "test_employees").
Note, the code outputs valid HTML and I re-formatted the echo statements and added newline chars to make the both the PHP and HTML source code more readable.
This code could be cleaned up considerably, so it's by no means good production code, but again, it demonstrates the logic you are after.
One item to note, the code only works within a given year. Additional code would be required if you wanted to display tables across multiple years.
If this helps you, please mark my answer.
I can also spend more time to refactor this code if you want. Let me know and I'll reply faster the next time.
<!DOCTYPE html>
<html>
<head>
<title>table test</title>
</head>
<body>
<?php
$name=$_SESSION['sess_username'];
$dateofattendance=$_SESSION['sess_date'];
$time="00-00-00";
$status="absent";
$counter=0;
$conn = new mysqli('localhost', '', '', 'test_employees');
$sql="SELECT dateofattendance,timeofattendance, status,timeofdeparture FROM attendance Where emp='$name' ORDER BY dateofattendance ASC ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
echo "<table border='1'>";
echo "<thead>";
echo "<tr>";
echo "<th>Date</th>";
echo "<th>IN</th>";
echo "<th>OUT</th>";
echo "<th>Status</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
$first_iteration = 1;
$row = $result->fetch_array(MYSQLI_ASSOC);
$last_month_num = split('-', $row["dateofattendance"])[1];
while($row = $result->fetch_assoc())
{
$current_month_num = split('-', $row["dateofattendance"])[1];
if ($first_iteration == 1) { // do nothing the first time around
$first_iteration = 0;
}
else if ($current_month_num == $last_month_num) { // only close row in current table
echo "</tr>";
}
else { // close table and start new table
echo "</tr>";
echo "</table>";
echo "<table border='1'>";
echo "<thead>";
echo "<tr>";
echo "<th>Date</th>";
echo "<th>IN</th>";
echo "<th>OUT</th>";
echo "<th>Status</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
}
echo "<tr>" . "\n";
echo "<td>" . "\n" . $row["name"] . $row["dateofattendance"] . "\n" . "</td>" . "\n";
echo "<td>" . "\n" . $row["timeofattendance"] . "\n" . "</td>" . "\n";
echo "<td>" . "\n" . $row["timeofdeparture"] . "\n" . "</td>" . "\n";
if($row["status"]=='present')
{
echo "<td><span class='label label-success'>". $row["status"]."</span></td>";
}
else
{
echo "<td><span class='label label-danger'>". $row["status"]."</span></td>";
}
$counter++;
$last_month_num = split('-', $row["dateofattendance"])[1];
}
echo "</tr>";
echo "</table>";
}
$conn->close();
?>
</body>
</html>

select SQL table from php variable

I have selected a random table from a list/array and I want to be able to call this random table with the mysqli_query function i.e. select a table dynamically
Here is my code:
<?php
$mysqli=mysqli_connect(HOST,USERNAME,PASSWORD,DATABASE);
// Check connection
if (mysqli_connect_errno($mysqli))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Looks at all prodcuts and selects those that have special offers enabled
// Selects a random table from the array
$tables_special = ["ajbs_products_console" ,"ajbs_products_console_games", "ajbs_products_pc", "ajbs_products_pc_games", "ajbs_products_pc_parts"];
$rtable = $tables_special[floor (rand(0,count($tables_special)-1))];
echo "<p>".$rtable." was selected</p>";
$products = mysqli_query("SELECT * FROM '".$rtable."'");
echo "<p>".$products."</p>";
while($productRow = mysqli_fetch_array($products))
{
if ($productRow['product_specials'] == 1)
{
echo "<table>";
echo "<tr>";
echo "<td rowspan='2'><img src=" . $productRow['product_image'] . "/></td>";
echo "</tr>";
echo "<table border='1'>";
echo "<tr>";
echo "<td>Product Name</td>";
echo "<td>" . $productRow['product_name'] . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Description</td>";
echo "<td>" . $productRow['product_description'] . "</td>";
echo "</tr>";
echo "</table>";
}
}
mysqli_close($mysqli);
?>
Im at a loss of why this is not working
Thanks,
Bull
You should not quote table names with single quotes but with backticks, single quotes makes it a string instead of a table name;
Also, the function mysqli_query takes an extra parameter, the connection.
$products = mysqli_query("SELECT * FROM '".$rtable."'");
should be;
$products = mysqli_query($mysqli, "SELECT * FROM `".$rtable."`");
Try
$products = mysqli_query($mysqli, "SELECT * FROM ".$rtable);

Printing two separate SQL table data on the dynamically populated table - PHP

Can someone please help me on the following code? Simply put, I'm trying to get two separate SQL tables' data, one on the horizontal side (brands) and the other (distributors) on the vertical side of a dynamically populated table.
my issue is, if you go through the code I cant get the text boxes populated under each respective brand name I get to display from the database. The text boxes are appearing only for the first brand name column.
My second issue if how do I assign a unique ID or a name to a dynamically populated text box here?
<?php
$q=$_GET["q"];
include ("../connection/index.php");
$sql="SELECT * FROM distributors WHERE rsm='".$q."'";
$sqlq="SELECT * FROM brands";
$result = mysqli_query($db,$sql) or die ("SQL Error_er1");
$resultq = mysqli_query($db,$sqlq) or die ("SQL Error_er2");
echo "<table border='1'>
<tr>
<th>Distributor</th>";
"<tr>";
while($rowq = mysqli_fetch_array($resultq))
{
echo "<td>" . $rowq['bname'] . "</td>";
}
"</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['dname'] . "</td>";
echo "<td><input type='text' name='txt1'></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($db);
?>
You're creating loop without relating to eachother, and the same goes for the execution of the querys...
If you want to solve it you will have to nestle the loops together, something like:
<?php
$q=$_GET["q"];
include ("../connection/index.php");
$sql="SELECT * FROM distributors WHERE rsm='".$q."'";
$result = mysqli_query($db,$sql) or die ("SQL Error_er1");
echo "<table border='1'>
<tr>
<th>Distributor</th>";
"<tr>";
//Go through all distributors
while($rowq = mysqli_fetch_array($result)) {
echo "<td>" . $rowq['bname'] . "</td>";
//Show all brands for current distributor
$sqlq="SELECT * FROM brands where distributor_id = " . $rowq['rsm'];
$resultBrands = mysqli_query($db,$sql) or die ("SQL Error Brands");
while($row = mysqli_fetch_array($resultBrands))
{
$id = $row['rsm'];
echo "<tr>";
echo "<td>" . $row['dname'] . "</td>";
echo "<td><input type='text' name='textBox[]'></td>";
echo "</tr>";
}
//End show all brands for current distributor
}
//End Go through all distributors
A better solution though, would be something like (of course $q has to validated before input inside of query and also binded with bind_param()).
<?php
$q=$_GET["q"];
include ("../connection/index.php");
$sql = " SELECT * FROM distributors d";
$sql .=" LEFT JOIN brands b ON (d.brand_id = b.brand_id)";
$sql .=" WHERE d.rsm=$q";
$result = mysqli_query($db,$sql) or die ("SQL Error");
echo "<table border='1'>";
while($rowq = mysqli_fetch_array($result))
{
$id = rowq['rsm'];
echo "<tr>";
echo "<td>" . $rowq['dname'] . "</td>";
echo "<td>" . $rowq['bname'] . "</td>";
echo "<td><input type='text' name='textBox[]'></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($db);
?>
Take notice of the name='textBox[]'. From PHP you can access the variable with $_POST['textBox'] (or $_GET['textBox'] and PHP will return an array).

How To Edit/Delete Stored Data From Database In PHP

EDIT
I have a mysql table with fields as follows:
Products - serial, name, description, price, picture.
the viewproducts.php page is as follows:
<?php
$result = mysql_query("SELECT * FROM products ")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Products';
} else {
echo "<table border='0'><table border='1' width=100%><tr><th>Product Name</th><th>Description</th><th>Price</th><th>Image</th><th>Edit</th><th>Delete</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['description']. "</td>";
echo "<td>£" . $info['price']." </td>";
echo "<td>" . "<img src='../getImage.php?id=" . $info['serial'] ."'/></td>";
echo '<td> Edit</td>';
}
}
echo "</tr>";
echo "</table>";
?>
my edit.php page looks like this:
<?php
$product_id = $_GET['serial'];
$result = mysql_query("SELECT * FROM products WHERE serial = '$product_id'")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Products';
} else {
echo "<table border='0'><table border='1' width=100%><tr><th>Product Name</th><th>Description</th><th>Price</th><th>Image</th><th>Edit</th><th>Delete</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['description']. "</td>";
echo "<td>£" . $info['price']." </td>";
echo "<td>" . "<img src='../getImage.php?id=" . $info['serial'] ."'/></td>";
}
}
echo "</tr>";
echo "</table>";
?>
when i click on edit from thr viewproducts.php page, it goes to edit.php page where nothing is showing up. the serial id on the address bar is coming up as follows:
http://www.********.com/****/admin/edit.php?product_id=
I want to be able to edit any product clicked on from the viewproduct.php page and transfered to edit.php page. I dont think my edit.php page is set up corretly.
Please help,
Thanks
You can pass via $_GET the id of the product and then, in the edit/delete page, retrieve that parameter. Obviously you have to sanitize the input properly before using it. For example, the link of the each product should look like this:
echo '<td>Edit</td>';
In the edit page you should have something like:
$id = $_GET['id'];
// For example, if the product id is an integer
// you can sanitize it doing this
$id = (int) $id
You could pass it as an argument to your php file in wich you want to edit/delete the product:
Edit Product
Then in your edit.php you will pick up the id of the product and load it's data from the database.
[edit.php]
$product_id = isset($_GET['product_id']) ? intval($_GET['product_id']) : null;
if(!$product_id) {
exit();
}
// query your database for the product
$row = mysqli_query("SELECT * FROM <table> WHERE product_id = $product_id");
// then you output your html with fields populated from the result from the database

Categories