Get an output after a select option in html - php

So basically, i have a database that simulates an airport, and i want to make a page that after a selected category i provide the total amount of customs fees of the category(example: category selected=electronics, output wanted= eletronics = somenumber) the select tag in the html is dynamic based on the category(so if i remove a category the select option disappears). The problem is that i don't know how to display the amount. I've managed to display the selected option but i have no idea on how to pair the amount with the category.
Sorry for the messy explaination, but it's really hard for me to explain my problem in another language, please help a poor student
For any doubts about the code just ask
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Dazi</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="style.css">
<script src="script.js"></script>
</head>
<body>
<form action="home.php" method="GET">
<select name="categoria" id="cate">
<?php
$conn = MySQLi_connect("localhost","root","","aeroporto");
if (!$conn)
die("Problems");
$query = "select CA.descrizione as 'categoria', sum(C.dazio) as 'qta_dazi'
from controlli C inner join merci M on C.id=M.id_controllo_fk inner join categorie CA on CA.id=C.id
group by CA.id";
$res=MySQLi_query($conn ,$query);
while( $row= MySQLi_fetch_array($res,MYSQLI_ASSOC))
{
$c=$row["categoria"];
$n=$row["qta_dazi"];
$cat=$_GET["categoria"];
echo "<option value='$c'>$c</option>";
}
echo"</select>";
echo"<input type='submit' value='Visualizza il totale'>";
echo"<br><br><br>";
if(isset($cat)){
echo $cat." =";
}
$ok= MySQLi_close($conn);
if (!$ok)
die("problems");
?>
</form>
</body>
</html>

During the loop, check if $c ever equals $cat (note that you can set $cat outside the loop, since it does not change as a result of the DB query). At that point, set a separate variable (which has scope outside the loop) to denote the matching amount, and use that in your display:
$cat=$_GET["categoria"];
$val = "";
while( $row= MySQLi_fetch_array($res,MYSQLI_ASSOC))
{
$c=$row["categoria"];
$n=$row["qta_dazi"];
if ($c == $cat) $val = $n; //check the category value from the DB against the GET variable.
echo "<option value='$c'>$c</option>";
}
echo"</select>";
echo"<input type='submit' value='Visualizza il totale'>";
echo"<br><br><br>";
if(isset($cat)) {
echo $cat." = ".$val;
}

Just for didactical purpose, do not use this in production.
In home.php:
$categoryId = $_REQUEST['categoria'];
//sanitization...
$conn = MySQLi_connect("localhost","root","","aeroporto");
//...
$query = "select sum(C.dazio) as 'prezzo_dazi', count(C.dazio) as 'qta_dazi'
from controlli C join categorie CA on CA.id = C.id WHERE CA.id = $categoryId";
$res=MySQLi_query($conn ,$query);
if( $row = MySQLi_fetch_array($res,MYSQLI_ASSOC))
{
echo "Dazi: {$row['prezzo_dazi']} € (qt. {$row['qta_dazi']}";
}else{
echo "Categories doesn't have any Dazio assigned.";
}
MySQLi_close($conn);
Usually a small attention o research on Google it's enough to have an higher understanding of the programming concept.
Cheers.

Related

How do I query two tables for a filtered result in mysql

I have a table with buildings(8052monticello) and a separate table with offices(individualspecs), Upon clicking on a respective building link in the buildings page I send the building id to through a get request to the handling page unit_specs.php, however unit_specs is showing me all the units in the table, however I only want unit_specs.php to display the units corresponding to its respective building. How can I fix this?
$querystats='SELECT individualspecs.Space, individualspecs.Size,
individualspecs.Price, individualspecs.Id';
$querystats.= ' FROM individualspecs';
$querystats.= ' INNER JOIN 8052monticello ON
individualspecs.fk_Id=8052monticello.id';
if ($r = mysqli_query($connection, $querystats)) { // Run the query.
// Retrieve and print every record:
while ($row = mysqli_fetch_assoc($r)) {
if ($row['Price']){
print "<p><h3> Unit # {$row['Space']}</h3>
{$row['Size']} Sq Feet<br>
{$row['Price']} Monthly rent<br>
Edit
Delete
</p><hr>\n";
}
}
}
units table
buildings table
here is the full code:
<!doctype html>
<html lang="en">
<head>
<style>
.container{
padding: 1em;
}
</style>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-
Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<meta charset="utf-8">
<title>View the units # </title>
</head>
<body>
<div class="container">
<h1>Units</h1><hr>
<?php // Script 12.6 - view_BUILDINGS.php
$connection = mysqli_connect('localhost', 'user', 'password',
'BUILDINGS');
// Define the query but only for info:
$querystats='SELECT individualspecs.Space, individualspecs.Size,
individualspecs.Price, individualspecs.Id';
$querystats.= ' FROM individualspecs';
$querystats.= ' WHERE individualspecs.fk_building= 8052monticello.UNIT';
if ($r = mysqli_query($connection, $querystats)) { // Run the query.
// Retrieve and print every record:
while ($row = mysqli_fetch_assoc($r)) {
if ($row['Price']){
print "<p><h3> Unit # {$row['Space']}</h3>
{$row['Size']} Sq Feet<br>
{$row['Price']} Monthly rent<br>
Edit
Delete
</p><hr>\n";
}
}
}
//end of get image query
else { // Query didn't run.
print '<p style="color: red;">Could not retrieve the data because:<br>' .
mysqli_error($connection) . '.</p><p>The query being run was: ' .
$querystats . '</p>';
} // End of query IF.
mysqli_close($connection); // Close the connection.
?>
</div>
</body>
</html>
Couple of things here...
You aren't using anything from 8052monticello so there's no reason to join it in
Assuming your request looks something like /unit_specs.php?id=123, you need to compare individualspecs.fk_Id (your building ID) with $_GET['id']. The best way to do so is use a prepared statement and bind the parameter.
For example
$buildingId = $_GET['id'] ?? null; // PHP 7 syntax, use "$buildingId = isset($_GET['id']) ? $_GET['id'] : null;" for older versions
$stmt = $connection->prepare(
'SELECT Space, Size, Price, Id FROM individualspecs WHERE Price > 0 AND fk_Id = ?');
$stmt->bind_param('i', $buildingId); // bind the first parameter as an integer
$stmt->execute();
// I just find bind_result() easier to work with, YMMV
$stmt->bind_result($space, $size, $price, $id);
// PHP's alternative syntax makes for better readability IMO
while ($stmt->fetch()) : ?>
<p>
<h3> Unit # <?= $space ?></h3> <!-- FYI: H3 should not be in a P tag -->
<?= $size ?> Sq Feet<br>
<?= $price ?> Monthly rent<br>
Edit
Delete <!-- deleting via a GET request is a bad idea -->
</p>
<hr>
<?php endwhile;
Useful links:
PHP: Prepared Statements
Alternative syntax for control structures
mysqli_prepare()
mysqli_stmt_bind_param()
mysqli_stmt_execute()
mysqli_stmt_bind_result()
mysqli_stmt_fetch()

Return particular rows in a column

I am using mysql database and I am looking for a way to display particular rows for column B when the column A value meets a specific criteria.
For Example in TBL_NAME:
ColumnA = Months
ColumnB = Holidays
Veterans Day
Thanksgiving
etc...
I would like to display on a page all the Holidays occurring in the month of November. I do not want to display any holidays in other months. Here is the code I have which is returning the error "Unknown column 'ColumnA' in 'where clause'."
<?php
error_reporting(0);
require 'db/connect.php';
$Month=November;
$data = $conn->query("SELECT * FROM TBL_NAME WHERE ColumnA=$Month") or die($conn->error);
$numRows = $data->num_rows;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Database Connect</title>
</head>
<body>
<?php
// Print results to the page
while($row = $data->fetch_assoc()) { ?>
<p><?php echo $row['LinkName']; ?></p>
<?php } ?>
</body>
</html>

Online Task Manager for website

Requesting some help on this task management system that i am making for class. I cant quite get it to work right. information is sometimes lost before it gets to the server and some of the last php code leeks thru to being seen on the site. can anyone tell me what i am doing wrong and help me to fix this? this code is supposed to allow you to send the task to a data base and the managing section relays the data from the database to the webpage.
data base is set up as this
3 Columns:
id - INT - 5 Length - Primary Key - AI.
description - VARCHAR - 255 Length.
active - BOOLEAN - 1 Length.
I am creating this on the hostica text editor that is within the site not an IDE if there are any discrepancy in the code
the website link is http://jtaylor84.net/taskmanager.php
I would like this code to work to take the information entered and relay it to the database and show in the managed tasks in order to have them up to be removed and show the tasks that have been entered.
<!DOCTYPE html>
<html>
<head>
<title>Online Task Manager</title>
<link href="style.css" rel="stylesheet">
</head>
<body>
<div id="main">
<?php
$con = mysqli_connect('localhost', 'root', '', 'Jhonny3_Task_Manager') or die(mysql_error());
if (isSet($_POST['createTask'])) {
if (isSet($_POST['desc']) && $_POST['desc'] != '') {
$desc = $_POST['desc'];
$q = mysqli_query($con, "INSERT INTO `tasks` VALUES ('', '$desc', '1')") or die(mysql_error());
if ($q) { echo 'Added task.';
}else
echo 'Failed to add task.';}}
if (isSet($_GET['removeTask']) && isSet($_GET['id'])) {
$id = $_GET['id'];
$q = mysqli_query($con, "UPDATE `tasks` SET `active`='0' WHERE `id`='$id'");
if ($q) { echo 'Task removed.';
}else
echo 'Failed to remove task.';}
?>
<h1>Add Task:</h1>
<form action='taskmanager.php' method='POST'>
Description of Task: <input type='text' name='desc'/>
<input type='submit' value='Create Task' name='createTask'/>
</form>
<h1>Manage Tasks:</h1>
<?php
$qu = mysqli_query($con, "SELECT * FROM `tasks` WHERE `active`='1'");
if (mysqli_num_rows($qu) > 0) {
after this section the code shows up on the web page and i am not sure why
while ($row = mysqli_fetch_array($qu)) {
echo "";
echo $row['description'];
echo "<a href='taskmanager.php?removeTask&id=".$row['id']."'>Remove Task</a>";
}
}
?>
<footer id="foot01"></footer>
</div>
<script src="sitescript.js"></script>
</body>
</html> `
Problem might be your php server .your code working fine in my server .

Php dropdown menu displaying data via MySQL

I've installed the MySQL database using the script as in http://www.databasejournal.com/scripts/practice-sql.html :
Then I have my PHP code learnt from Youtube video about how to populate dropdown with data from SQL, but It still can't work that nothing turns out when clicking the "Show details" submit button. I am still new to PHP and can't sort it out myself. Thank you !!
// PHP Code
<?php
require'require.php';
$usersQuery="
SELECT DISTINCT
c.cno,
c.cname,
o.eno,
o.shipped
FROM customers c
RIGHT JOIN orders o
ON c.cno=o.cno
group by (c.cname)
";
$users=$db->query($usersQuery);
if(isset($_GET['user'])){
$userQuery="
{$usersQuery}
WHERE c.cno=:cno";
$user= $db->prepare($userQuery);
$user->execute(['cno'=>$_GET['user']]);
$selectedUser=$user->fetch(PDO::FETCH_ASSOC);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Dropbox</title>
<script language=JavaScript>
</script>
</head>
<body>
<h3>My Dropdown</h3>
<form action="dropbox.php" method="get">
<select name="user">
<option value="">Choose one</option>
<?php foreach($users->fetchAll() as $user):?>
<option value="<?php echo $user['cno'];?>" <?php echo isset($selectedUser)&& $selectedUser['cno']==$user['cno']? "selected":""?> > <?php echo $user['cname'];?> </option>
<?php endforeach ?>
</select>
<input type="submit" value="Show details" >
</form>
<?php if(isset($selectedUser)):?>
<pre><?php echo($selectedUser['cno']);?></pre>
<?php endif; ?>
</body>
</html>
There is problem is you execute statement. you forget : in it and you have to pass array into it.It would be
$user->execute(array(":cno" =>$_GET['user']));
$selectedUser=$user->fetch(PDO::FETCH_ASSOC);
Read execute
This is a code that works.
I tried to commented all the modifications i made from ur code
But first let's look into the query u made :
SELECT DISTINCT c.cno, c.cname, o.eno, o.shipped
FROM customers c
RIGHT JOIN orders o
ON c.cno=o.cno
group by (c.cname)
DISTINCT and GROUP BY #strawberry said doesn't like to be in same query.
IN this query the GROUP BY clause "will merge" the result of the query BY cname.
ORIGINAL :
But let's suppose we entered 2 clients with the same name (it's possible coz PRIMARY KEY is cdo) and both of these clients ordered something. U'll miss one by using GROUP BY on a column that isn't a PRIMARY KEY.
BEST way to GROUP BY was on PRIMARY KEY.
Btw Ur variables names can be tricky (like $users & $user)
Original queries variables :
$usersQuery = "SELECT c.cno, c.cname
FROM customers c, orders o
WHERE c.cno = o.cno
GROUP BY c.cno";
AND
$userQuery = "SELECT *
FROM customers
WHERE cno = :cno";
EDIT : see Strawberry's comment (below)
GROUP BY VS DISTINCT
I was mistaking about how to build query so i made changes in this way. A better process (for the mind) is running with this query :
"SELECT DISTINCT c.cno, c.cname, c.street, c.zip, c.phone
FROM orders o
LEFT JOIN customers c
ON o.cno = c.cno"
Then add a WHERE clause when one user is returned by the form :
.
<?php
// My include of connecting to my DB - same as ur require.php i suppose
include("./inc.connect.php");
// As said before
$usersQuery = "SELECT DISTINCT c.cno, c.cname, c.street, c.zip, c.phone
FROM orders o
LEFT JOIN customers c
ON o.cno = c.cno";
$users = $db->query($usersQuery);
if(isset($_GET['user']))
{
// This query will return all informations about the user u selected
// $userQuery="{$usersQuery} WHERE c.cno=:cno"
// as #saty said u missed ':' but ur string query
// You included 2 clause WHERE
// (from usersQuery and the concatenation)
$userQuery = "{usersQuery} WHERE cno = :cno";
$user = $db->prepare($userQuery);
$user->execute(array(":cno" => $_GET['user']));
$selectedUser = $user->fetch(PDO::FETCH_ASSOC);
// Display the array (<pre> tag make it readable)
print "<pre>";
print_r($selectedUser);
print "</pre>";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Dropbox</title>
<script>
</script>
</head>
<body>
<h3>My Dropdown</h3>
<!-- Nothing important : just changed action value coz
of my name's page -->
<form action="index.php" method="get">
<select name="user">
<!-- Added "Default" value for first option -->
<option value="Default">Choose one</option>
<?php
// used echo only to display html tags -
// make it cleaner to read
foreach($users->fetchAll() as $user)
{
// Can't make the display Better - SRY
echo "<option value=\"" . $user['cno'] . "\"";
echo (isset($selectedUser) &&
($selectedUser['cno'] == $user['cno']))
? "selected" :"";
echo ">" . $user['cname'] . "</option>";
}
?>
</select>
<input type="submit" value="Show details">
</form>
<?php
if(isset($selectedUser))
echo "<pre>" . ($selectedUser['cno']) . "</pre>";
?>
</body>
</html>
Hope that helped.

PHP MySQL search using multiple text boxes to search multiple columns

I'm learning PHP and working on a project for searching books in a MySQL database. The user should be able to search by Book Title, Book Author and by the Category, using all, one or any combination of the 3.
At present here is my code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome to Library Management System</title>
<link href="main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php
require_once "db.php";
include "header.html";
if(isset($_POST["bookTitle"]))
{
$bookTitle = mysqli_real_escape_string($con, $_POST["bookTitle"]);
}
else
{
$bookTitle = NULL;
}
if(isset($_POST["bookAuthor"]))
{
$bookAuthor = mysqli_real_escape_string($con, $_POST["bookAuthor"]);
}
else
{
$bookAuthor = NULL;
}
if(isset($_POST["category"]))
{
$category = mysqli_real_escape_string($con, $_POST["category"]);
}
else
{
$category= NULL;
}
echo "Results by Book Title Search";
$bookTitle = mysqli_real_escape_string($con, $_POST["bookTitle"]);
$query = "Select * From book NATURAL JOIN category where category.CategoryDesc LIKE '%" .$category ."%' OR book.BookTitle LIKE '%" .$bookTitle ."%' OR book.Author LIKE '%" .$bookAuthor."%'";
$result=mysqli_query($con, $query) or die(mysqli_error());
echo '<table border="1" width="95%">'."\n";
echo "<tr><th>ISBN</th><th>Title</th><th>Author</th><th>Edition</th><th>Year</th><th>Category ID</th><th>Reserved</th><th>Reserve?</th><tr>";
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo "<tr><td>";
echo(htmlentities($row[0]));
echo("</td><td>");
echo(htmlentities($row[1]));
echo("</td><td>");
echo(htmlentities($row[2]));
echo("</td><td>\n");
echo(htmlentities($row[3]));
echo("</td><td>\n");
echo(htmlentities($row[4]));
echo("</td><td>\n");
echo(htmlentities($row[5]));
echo("</td><td>\n");
echo(htmlentities($row[6]));
echo("</td><td>\n");
echo('Edit
/ ');
echo('Delete');
echo("</td></tr>\n");
}
echo "</br>";
If I search using all three fields, the query returns the relevant results. If one or more of the fields is left blank, the entire database is returned, which is not what i want.
Is there a better approach to this?
you can use this
$condition="sasaaa";
$bookTitle=trim($_POST['bookTitle']);
$bookAuthor=trim($_POST['bookAuthor']);
$category=trim($_POST['category']);
if(isset($bookTitle))
$condition="booktitle=$bookTitle";
if(isset($bookAuthor))
$condition="bookAuthor=$bookAuthor";
if(isset($category))
$condition="category=$category";
and use this $condition variable in your SQl. use mysqli_real_escape_string().
Hope it will help you :)
It would be better to skip all your tests at the beginning, and simply build your query dynamically, only putting where conditions when your post variables are set. But if you wish to keep this logic (which isn't too good) , just replace your NULLvalues with empty string, and that should do the trick...

Categories