I'm trying to create an html form to provide information about the salaries table in my database, the user should be able to pick year between 1986-1996 and choose if she wants to see the total salary of that year or the average salary of that year.
I have no idea how I link up these scripts and I can't find much online.
html file:
<html>
<body>
<fieldset>
<form id="frmName" method=post action="Oppgave4.php" onsubmit="">
<h1>Oppgave 4</h1>
Choose year:
<select id="frmName" onChange="">
<option selected disabled hidden>----</option>
<option name="1986">1986</option>
<option name="1987">1987</option>
<option name="1988">1988</option>
<option name="1989">1989</option>
<option name="1990">1990</option>
<option name="1991">1991</option>
<option name="1992">1992</option>
<option name="1993">1993</option>
<option name="1994">1994</option>
<option name="1995">1995</option>
<option name="1996">1996</option>
</select>
Total or average salary:
<select id="frmName" onChange="">
<option selected disabled hidden>----</option>
<option name="Total">Total salary</option>
<option name="Average">Average salary</option>
</select>
<input type="submit" value="Submit" id="submit">
</p>
</form>
</fieldset>
</body>
</html>
php file:
<?php
$year = ($_POST['1986'], $_POST['1987'], $_POST['1988'], $_POST['1989'], $_POST['1990'],
$_POST['1991'], $_POST['1992'], $_POST['1993'], $_POST['1994'], $_POST['1995'],
$_POST['1996'], $_POST['Total']);
$average = $_POST['Average'];
$conn = mysqli_connect("localhost", "root", "", "employees");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sqlavg = "SELECT AVG(salaries.salary) AS average FROM salaries
WHERE from_date = '$year'";
$result = $conn->query($sql);
if (!empty($result) && $result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["average"] ."</td></tr>";
}
echo "</table>";
$sqlsum = "SELECT SUM(salaries.salary) AS total FROM salaries
WHERE from_date = '$year'";
$result = $conn->query($sql);
if (!empty($result) && $result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["total"] ."</td></tr>";
}
echo "</table>";
} else { echo "0 results"; }
$conn->close();
?>
What you're trying to do is literally PHP/MySQL 101 and there is a lot online on how to do this. Having said that you are making some mistakes in your code. First, you should name the <select>
<select name="year">
Then you should give each option a value:
<option value="1994">1994</option>
...// do each one like this
This way, when the form is submitted to the PHP you can find it in the POST array:
$year = $_POST['year'];
That is just a start. You have a second drop-down that also needs a name and each option should have a value attribute.
<select name="calculation_type">
<option>----</option>
<option value="Total">Total salary</option>
<option value="Average">Average salary</option>
</select>
Which will be found like this in the POST array:
$average = $_POST['calculation_type'];
Your form needs a name and does not need the onsubmit The action should be the name of the PHP script which will perform the calculations:
<form name="form_name" method=post action="Oppgave4.php">
Warning
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!
Suggestion
You should go work through some basic PHP tutorials like those offered by https://www.learn-php.org/ (a free, interactive website) or other services
Related
In my form, I generate the select options from my MySQL data table. But when I submit the form without any value, it returns to a blank page and does not show any validation error. When I select a value and submit the form, it inserts the value to MySQL table. No MySQL or PHP error is thrown. I am assuming the problem is the query for the select option is not running. But if it is the problem, what should be the good practice to avoid this problem?
My form is:
<?php
require 'db.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$ad_di = "";
$ad_di_err = "";
if (empty(trim($_POST["ad_di"]))) {
$ad_di_err = "District cannot be empty.";
} else {
$ad_di = trim($_POST["ad_di"]);
}
if (empty($ad_di_err)) {
$sql = "INSERT INTO address (ad_di) VALUES (?)";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("i", $p_ad_di);
$p_ad_di = $ad_di;
if ($stmt->execute()) {
$id = $mysqli->insert_id;
header("location: add.php?id=$id&update=success");
}
$stmt->close();
}
}
}
?>
<form id="acEdit" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" class="contact-form">
<div class="row">
<div class="col-3">
<div class="form-group">
<label>District</label>
<select name='ad_di' id='ad_di' class='custom-select'>
<option value=''>Select one ...</option>
<?php
$qDistrict = "SELECT * FROM districts order by name ASC";
echo "<select name='ad_di' id='ad_di' class='custom-select'><option value=''>Select one ...</option>";
foreach ($mysqli->query($qDistrict) as $rowDistrict) {
echo "<option value={$rowDistrict['id']}>{$rowDistrict['name']}</option>";
}
echo "</select>";
?>
</select>
<span class="invalid-feedback"><?php echo $ad_di_err; ?></span>
</div>
</div>
</div>
</form>
The above query for select options returns as following when the page is loaded first,
<select name="ad_di" id="ad_di" class="custom-select">
<option value="">Select one ...</option>
<option value="28">Dist A</option>
<option value="11">Dist B</option>
<option value="35">Dist C</option>
<option value="33">Dist D</option>
</select>
But when the validation error occurs, the returning page doesn't have any options, just returns
<select name="ad_di" id="ad_di" class="custom-select">
<option value="">Select one ...</option>
</select>
I'd like to create "Exact Search" with multiple options but the answer says "Could not search".
In the table, price, one and pre are rows.
If the answer matches one and pre, the separated price will be come out. If not, the reply will be "Try agian".
Edited : I have three tables - pre, one and price.
- KA 1 will win 100
- KA 5 will win 500
- MA 3 will win 100
- MA 1 will win 200
- BA 3 will win 800
Edited : I changed the code now and no error shown but the result was always 'Try Again'.
<?php
$output = NULL;
$link = mysqli_connect("localhost","root","","searchdemo") or die("Unable to select database" . mysqli_error($link));
if(isset($_GET['search'])){
$searchq = $_GET['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query ($link, "SELECT * FROM `345` WHERE pre = '$searchq' AND one = '$searchq'") or die("<b>Error</b> : ".mysqli_error($link));
$count = mysqli_num_rows($query);
if ($count == 0){
$output = 'Try Again';
}else{
while($row = mysqli_fetch_array($query)){
$onen = $row['one'];
$pren = $row['pre'];
$price = $row['price'];
$output = 'You won '.$price.' now';
}
}
}
?>
<form name="search1" action="index.php" method="GET">
<b>Prefix</b>
<select name="pre">
<option value="">Pick a prefix</option>
<option value="Ka">Ka</option>
<option value="Ba">Ba</option>
<option value="Ma">Ma</option>
</select>
<b>Number</b>
<select name="one">
<option value="">Pick a number</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<input type="submit" name="search" value="Search" />
</form>
<?php
print ("$output");
//echo ($output);
?>
If die() is called, it means that the query failed, so I'd start looking for a reason there.
You are missing WHERE in your query, it should start with
SELECT * FROM 345 WHERE ...
Keep in mind that your code is open for SQL injecion attack. You must to escape all user input that gets into your query.
Simplest way to do it is to use http://php.net/manual/en/function.mysql-real-escape-string.php (deprecated since PHP 5.5) or http://php.net/manual/en/mysqli.real-escape-string.php. You could also use PDO prepared statements for your queries (http://php.net/manual/en/book.pdo.php)
Some general pointers for you here:
You need a WHERE clause in your SQL statement to define the criteria of your search. The search will work without it but it will return everything, which is not what you want. (This has already been fixed)
You need a AND or an OR statement between your variables, in your WHERE clause, because you are asking "show this WHERE condition1 is true AND/OR condition2 is true"
Replace your die command with a better and more informative feedback:
This will output why the search failed. Use this to fix further errors.
or die("Could not search: ".mysql_error());
As mentioned by jedrzej.kurylo, you are wide open for injection attacks on your database and it is very important to fix these, either as they suggest or by upgrading your code to using MySQLi or PDO . Do this now while you're still learning the basics of SQL because it's far better than getting into the bad habit of using old, deprecated and insecure MySQL.
Finally I got the answer and that was so easy. What a dumb I am! :)
I do really thanks to #Martin and #jedrzej.kurylo
<?php
$output = NULL;
$link = mysqli_connect("localhost","root","","searchdemo") or die("Unable to select database" . mysqli_error($link));
if(isset($_POST['search'])){
$spre = $_POST['pre'];
$sone = $_POST['one'];
$query = mysqli_query ($link, "SELECT * FROM `345` WHERE pre = '$spre' AND one = '$sone'") or die("<b>Error</b> : ".mysqli_error($link));
$count = mysqli_num_rows($query);
if ($count == 0){
$output = 'Try Again';
}else{
while($row = mysqli_fetch_array($query)){
extract($row);
$onen = $row['one'];
$pren = $row['pre'];
$price = $row['price'];
$id = $row['id'];
$output = 'You won '.$price.' now';
}
}
}
?>
<form name="search1" action="index.php" method="POST">
<b>Prefix</b>
<select name="pre">
<option value="">Pick a prefix</option>
<option value="Ka">Ka</option>
<option value="Ba">Ba</option>
<option value="Ma">Ma</option>
</select>
<b>Number</b>
<select name="one">
<option value="">Pick a number</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<input type="submit" name="search" value="SEARCHING" />
</form>
<?php
print ("$output <br />");
?>
I am looking for a way to search for data from the database using input type box list, I tried make the code but it doesn't display anything:
html code:
<form action="users.php" method="post" name="searching">
<select name="users">
<option selected="selected" value="">-- select --</option>
<option value="1">user1</option>
<option value="2">user2</option>
<option value="3">user3</option>
</select>
<input type="submit" name="search" value="find">
</form>
php code:
if (isset($_POST['users'])) {
$key = trim ($_POST['users']);
$s = "SELECT * FROM users where user_name LIKE '%$key %'";
$res = mysql_query($s) or die('query did not work');
while($row = mysql_fetch_array( $res ))
{
?>
User ID: <?php echo $row['user_id'] ?>
User Name: <?php echo $row['user_name'] ?>
<?php
}
?>
when I try the code I didn't get any result and when I remove the while loop and put this instead of it :
<?php echo $key; ?>
it gives me the numbers of the selected value, for example if I select user2 the result will be 2. and I want the result to be user id and user name.
you need to fetch all the user name in your drop down select box
<select name="users">
<option selected="selected" value="">-- select --</option>
<?php $s2 = "SELECT * FROM users";
$q2=mysql_query($s2) or die($s2);
while($rw=mysql_fetch_array($q2))
{
echo '<option value="'.$rw['userid'].'">'.$rw['username'].'</option>';
}</select>
?>
<?php if (isset($_POST['search'])) { // submit button name here
$key = $_POST['users'];
$s = "SELECT * FROM users where user_id='".$key."'";
$res = mysql_query($s) or die($s);
while($row = mysql_fetch_array( $res ))
{
?>
User ID: <?php echo $row['user_id'] ?>
User Name: <?php echo $row['user_name'] ?>
<?php
}
?>
edit your html to this,you will get the in $_POST which will be in value='something'
<form action="users.php" method="post" name="searching">
<select name="users">
<option selected="selected" value="">-- select --</option>
<option value="user1">user1</option>
<option value="user2">user2</option>
<option value="user3">user3</option>
</select>
<input type="submit" name="search" value="find">
</form>
Or if value is the id of user then change query to this
$s = "SELECT * FROM users where user_id='".$key."'";
I can't seem to get the following code to make a dropdown menu that contains data from a mysql database. The "include('connect.php');" connects to the mysql database and I know it works on separate pages. Any suggestions?
Below is the entire code.
listCustomer
<BODY>
<H1>Find Customer's Albums Page</H1>
From a dropdown list of customers, a user should be able to pick a customer and see a list of albums (all fields in the CD table) purchased by that customer.
<HR>
<FORM ACTION="listCustomer.php" METHOD="POST"/>
Customer:
<select name="mydropdownCust">
<option value="101">101</option>
<option value="102">102</option>
<option value="103">103</option>
<option value="104">104</option>
<option value="105">105</option>
<option value="106">106</option>
<option value="107">107</option>
<option value="108">108</option>
<option value="109">109</option>
<option value="110">110</option>
</select>
<BR>
<?php
include('connect.php');
$query = "SELECT Cnum, CName FROM Customer";
$result = mysql_query ($query);
echo "<select name=dropdown value=''>Dropdown</option>";
while($r = mysql_fetch_array($result))
{
echo "<option value=$r["Cnum"]>$r["CName"]</option>";
}
echo "</select>";
?>
<BR>
<INPUT TYPE="SUBMIT" Value="Submit"/>
</FORM>
<FORM ACTION="listMenu.html" METHOD="POST"/>
<INPUT TYPE="SUBMIT" Value="Main Menu"/>
</FORM>
</BODY>
</HTML>
<?php
include('connect.php');
$query = "SELECT Cnum, CName FROM Customer";
$result = mysql_query ($query);
echo "<select name='dropdown' value=''><option>Dropdown</option>";
while($r = mysql_fetch_array($result)) {
echo "<option value=".$r['Cnum'].">".$r['CName']."</option>";
}
echo "</select>";
?>
From the looks of things, you're missing an opening option tag, so it's just outputting "Dropdown" as a line of text.
Edit
Just to be completely transparent, because I did not have connect.php, I had to add my own DB connections. My whole page looked thusly:
<?
//Adding to display errors.
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<HTML>
<HEAD>
</HEAD>
<BODY>
<H1>Find Customer's Albums Page</H1>
From a dropdown list of customers, a user should be able to pick a customer and see a list of albums (all fields in the CD table) purchased by that customer.
<HR>
<FORM ACTION="listCustomer.php" METHOD="POST"/>
Customer:
<select name="mydropdownCust">
<option value="101">101</option>
<option value="102">102</option>
<option value="103">103</option>
<option value="104">104</option>
<option value="105">105</option>
<option value="106">106</option>
<option value="107">107</option>
<option value="108">108</option>
<option value="109">109</option>
<option value="110">110</option>
</select>
<BR />
<?php
// BEGIN ADDED CONNECTION HACKY GARBAGE
$con=mysql_connect("localhost","root","root");
// Check connection
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$selected = mysql_select_db("sample",$con)
or die("Could not select examples");
// END ADDED CONNECTION HACKY GARBAGE
$query = "SELECT Cnum, CName FROM Customer";
$result = mysql_query ($query);
echo "<select name='dropdown' value=''><option>Dropdown</option>";
while($r = mysql_fetch_array($result)) {
echo "<option value=".$r['Cnum'].">".$r['CName']."</option>";
}
echo "</select>";
?>
<BR />
<INPUT TYPE="SUBMIT" Value="Submit"/>
</FORM>
<FORM ACTION="listMenu.html" METHOD="POST"/>
<INPUT TYPE="SUBMIT" Value="Main Menu"/>
</FORM>
</BODY>
</HTML>
First off, you are missing an option opening tag, as correctly mentioned by stslavik. But this is not causing the issue here as it seems (it's auto-corrected by the browser - in my tests atleast).
Secondly, this wont work (problem causer):
echo "<option value=$r["Cnum"]>$r["CName"]</option>";
You should use
echo "<option value=".$r["Cnum"].">".$r["CName"]."</option>";
or, as I always prefer single quotes to enclose echo or print output strings:
echo '<option value='.$r['Cnum'].'>'.$r['CName'].'</option>';
Third alternative (complex syntax: What does ${ } mean in PHP syntax?)
echo "<option value={$r["Cnum"]}>{$r["CName"]}</option>";
assuming you get data from the database try this
echo "<option value={$r['Cnum']}>{$r['CName']}</option>";
try,
echo "<option value=' . $r['Cnum'] . '>' . $r['CName'] . '</option>";
instead of
echo "<option value=$r[Cnum]>$r[CName]</option>";
I will like to get multiple request after clicking submit. Meaning that after i clicked submit and get the result, i will like to inquire results again and click submit again. I don't want to lead myself back to nothingness.
<?php
error_reporting(0);
if (!$_POST['submit'])
{
<form action="http://localhost/test.php" method="post">
Type of Leave:
<select name="leave">
<option value=""selected="selected"></option>
<option VALUE="Medical Leave"> Medical Leave</option>
<option VALUE="Unpaid Leave"> Unpaid Leave</option>
</select>
<input type="submit" name="submit" value="Check!" />
</form>
<?php
}
else
{
$conn=odbc_connect("employee","","") or die (odbc_errormsg());
if (!$conn)
{
exit
("Connection Failed: " . $conn);
}
else
{
$choice = $_POST['leave'];
$sql="SELECT * FROM balance WHERE ID=$username";
$rs=odbc_exec($conn,$sql);
?>
<?php
while (odbc_fetch_row($rs))
{
$choice=odbc_result($rs,"$choice");
echo "<tr><td>$choice</td>";
}
odbc_close($conn);
echo "</table>";
}
}
Currently the code itself queries out the expected output that I want, but the only downside is it stays there as an output. What my aim is to have the submit and the select choice option stays there so that I can continue to output the result I want, thanks.
The best user experience would be to use AJAX to dynamically change the results table depending on what is chosen in the dropdown. For a simpler solution, you could try moving the form up and out of the if/else loop. Put the form first, then after the form prints, check for if ($_POST['submit']).
In this example, I also added a little function to add selected="selected" to whichever option was chosen for this submit. It's very rough, but you get the idea.
<?php
function matchPost($name,$val) {
if($val == $name)
echo 'selected="selected"';
}
?>
<form action="http://localhost/test.php" method="post">
Type of Leave:
<select name="leave">
<option value=""></option>
<option <?php matchPost('Medical_Leave',$_POST['leave']); ?> VALUE="Medical_Leave"> Medical Leave</option>
<option <?php matchPost('Unpaid_Leave',$_POST['leave']); ?> VALUE="Unpaid_Leave"> Unpaid Leave</option>
</select>
<input type="submit" name="submit" value="Check!" />
</form>
<?php
if ($_POST['submit'])
{
$conn=odbc_connect("employee","","") or die (odbc_errormsg());
if (!$conn)
{
exit
("Connection Failed: " . $conn);
}
else
{
$choice = $_POST['leave'];
$sql="SELECT * FROM balance WHERE ID=$username";
$rs=odbc_exec($conn,$sql);
?>
<?php
while (odbc_fetch_row($rs))
{
$choice=odbc_result($rs,"$choice");
echo "<tr><td>$choice</td>";
}
odbc_close($conn);
echo "</table>";
}
}