How can search the database by month through drop down in php - php

Please help me
I want to search the data of employee by month like january, february etc. by drop down list
and the date field is date type 0000-00-00.How can I search this type of data in php
thank you..
<code>
<select name="month" id="month">
<option>
</option>
<option>
January
</option>
<option>
February
</option>
<option>
March
...

You first need to give your form options some values for the month numbers. This will be queried by your database. You action can be the page that you want to display the data
<form method="post" action="process.php">
<select name="month" id="month">
<option></option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
</select>
</form>
process.php
the "username" and "password" and the database username and password used to connect to the database
<?php
// Make a MySQL Connection
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database_name") or die(mysql_error());
$date = mysql_real_escape_string($_POST['month']);
// Retrieve all the data from the "example" table
//set date_column to the date field in your database
$sql ="SELECT * FROM table_name WHERE MONTH(date_column) = $date";
$result = mysql_query($sql)
or die(mysql_error());
// store the record of the "example" table into $row
while($row = mysql_fetch_array($result)){
// Print out the contents of the entry
extract($row, EXTR_PREFIX_INVALID, '_');
//change these to whatever you want to display
echo "Name: ".$row['column1'];
echo " Age: ".$row['column2'];
}
?>
EDIT:
I've rewritten it for you and i've tested it also. This is presuming you're using MySQLi
This uses prepared statement which make it more secure. Have a look here for more info http://mattbango.com/notebook/code/prepared-statements-in-php-and-mysqli/
In the SELECT statement you can put whatever tables you want but the rest should be good to go.
<html>
<head>
</head>
<body>
<form method="post" action="testing.php">
<select name="month" id="month">
<option></option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<input type="submit" value="submit" name="submit"/>
</form>
</body>
</html>
<?php
// Include connection file here and replace these variables
$hostname="localhost";
$username="username";
$password="password";
$dbname="dbasename";
/* Create a new mysqli object with database connection parameters */
$db = new mysqli($hostname, $username, $password, $dbname);
// Create statement object
$stmt = $db->stmt_init();
// Create a prepared statement
if($stmt->prepare("SELECT name, month, blah FROM test WHERE MONTH(month) = ?")) {
// Bind your variable to replace the ?
if(!$stmt->bind_param('s', $month)) {
//if BIND fails, display an error
printf("Errormessage: %s\n", $stmt->error);
}
// escape the POST data for added protection
$month = isset($_POST['month'])
? $db->real_escape_string($_POST['month'])
: '';
// Execute query
if(!$stmt->execute()) {
printf("Errormessage: %s\n", $stmt->error);
}
// Bind your result columns to variables
if(!$stmt->bind_result($name, $url, $logo)) {
printf("Errormessage: %s\n", $stmt->error);
}
// Fetch the result of the query
while($stmt->fetch()) {
echo $name;
}
// Close statement object
$stmt->close();
}
?>

Related

Connect an interactive html form to a sql database

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

How to search/filter by month or year from database

I want to filter the report based on month or year using dropdown search button.
I'm having problem because the data for month that being search cannot be displayed.
Here are some codes that I've tried:
if(!empty($_POST['search'])){
$sql = "SELECT * FROM complain
WHERE MONTH(timeComplain)='".$_POST['search']."'";
$query = $conn -> query($sql);
$row = $query -> fetch_assoc();
}
<form action="report.php" method="post">
<div class="w3-left">
<select name="search" class="w3-select" value="">
<option value=""></option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<input type="submit" id="search" value="Filter">
</div>
</form>
You forgot to execute the query.
Use PDO instead.
Your PHP code should look like this:
if(!empty($_POST['search'])){
$sql = "SELECT * FROM complain WHERE MONTH(timeComplain)= :month";
$query = $conn->prepare($sql);
$params = array(':month' => $_POST['search']);
$query->execute($params);
$row = $query->fetch();
// then you can do "echo $row['']"
}
You should execute the query before any results are received.
Your $conn should look like this:
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try { $conn = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8",
$username, $password, $options); }
catch(PDOException $ex){ die("Failed to connect to the database: " . $ex->getMessage());}
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

<option> values showing as 0 in database

I cannot upload to the database drop down menu variables, when the form is submitted the text area is blank. I am new to coding and all of the information I have found thus far has been unable to help me. The students first and last names are submitting fine I just now need to process their grades
These are the Subjects:
English<br>
<select name="Grade">
<option value="-">-</option>
<option value="A*">A*</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="Fail">Fail</option>
</select><br>
Maths<br>
<select name="Grade2">
<option value="-">-</option>
<option value="A*">A*</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="Fail">Fail</option>
</select><br>
Science<br>
<select name="Grade3">
<option value="-">-</option>
<option value="A*">A*</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="Fail">Fail</option>
</select><br>
I need to upload them to here:
$DB_HOST = "localhost";
$DB_USERNAME = "admin";
$DB_PASSWORD = "chichester";
$DB_NAME = "results";
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$examboard = $_POST["examboard"];
$grade = $_POST["grade"];
$grade2 = $_POST["grade2"];
$grade3 = $_POST["grade3"];
$additionalcomments = $_POST["Additional Comments"];
$conn = new mysqli($DB_HOST, $DB_USERNAME, $DB_PASSWORD, $DB_NAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO studentresults (Name,lastname,examboard,additionalcomments) VALUES ('$fname','$lname','$examboard','$grade','$grade2','$grade3','$additionalcomments')";
$sql = "INSERT INTO studentresults (grade, grade2, grade3) VALUES ('$grade','$grade2','$grade3')";
if ($conn->query($sql) === TRUE) {
echo "Student exam results have been successfully submitted. ";
} else {
echo "Error, please try again later. : " . $sql . "<br>" . $conn->error;
}
//close connection
$conn->close();
Now how do I overcome this, the script and database does not show an errors. All I need to do is process a series of exam results and display this in a database. The tag seems to have confused matters.
1) you are updating the insert query.
2) The query you have written is wrong as there number of columns is different than the number of values given.
3) $_POST["Additional Comments"]; this won't work, as array key cannot contain space.
Why do you have two $sql insert statements? Only use one.
INSERT INTO ___ (col1,col2) VALUES ('data1','data2');
You can't have spaces in $_POST['']; variables.

Updating the mysql database based on user input

I want to insert the selected status timestamps in the corresponding column which user has chosen from the menu.
Brief explanation
Start from the database i have created columns like snap below.
Initially user will insert the sonumber and status, Now i need database to update current time and date in the database, remaining column initialized to zero.
Next user will select update option, here user will enter so-number as well as new status(from dropdown). Now i need database to update the new status with current time and store in the particular status column.
Starting with insert page saved as "insert.html" and "insert.php" Respectively
<form id="form1" name="form1" method="post" action="insert.php" >
<p>
<lable>ENTER SO NUMBER</lable>
<input type="text" name="soid" id="soid" maxlength="6" required>
<p>
<lable>SELECT DEPARTMENT</lable>
<select type="text" name="dept" id="dept">
<option value="NGS Analysis">NGS Analysis</option>
<option value="E-Array">E-Array</option>
<option value="Micro-Array">Micro-Array</option>
<option value="NGS Data">NGS Data</option>
</select>
</p>
<p>
<lable>SELECT STATUS</lable>
<select type="text" name="status" id="status">
<option value="Sample Recived">Sample Recived</option>
<option value="Mol Bio Extraction">Mol-Bio Extraction</option>
<option value="Extraction QC">Extraction QC</option>
<option value="Library Prep">Library Prep</option>
<option value="Library QC">Library QC</option>
<option value="Sequencing">Sequencing</option>
<option value="Data check">Data Check</option>
<option value="Re-Sequencing">RE-Sequencing</option>
<option value="QC Check">QC Check</option>
<option value="Analysis Started">Analysis Started</option>
<option value="Analysis Completed">Analysis Completed</option>
<option value="Report">Report</option>
<option value="Outbound">Outbound</option>
</select>
</p>
<p><button><img src="http://brandonmadeawebsite.com/images/art/icons/insert_icon.png" height="50" />INSERT</button></p>
</form>
insert.php
<?php
$so = $_POST['soid'];
$dp = $_POST['dept'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "status";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
$result = mysqli_query($conn, "INSERT INTO $dbname.statusinfo (soid, dept ) VALUES ( '$so','$dp')") or die(mysqli_error($conn));
echo "Inserted sucessfully with So Number <u><b>$so</b></u> Corresponding Status is <u><b>$st</b></u>";
$conn->close();
?>
Now below update script which is saved as "update.html","update.php" respectively
<form action="update.php" method="post" name="form2">
<p>
<lable>ENTER SO NUMBER</lable>
<input type="text" name="soid" id="soid" required>
<p>
<lable>SELECT STATUS</lable>
<select type="text" name="status" id="status">
<option value="Sample Recived">Sample Recived</option>
<option value="Mol Bio Extraction">Mol-Bio Extraction</option>
<option value="Extraction QC">Extraction QC</option>
<option value="Library Prep">Library Prep</option>
<option value="Library QC">Library QC</option>
<option value="Sequencing">Sequencing</option>
<option value="Data check">Data Check</option>
<option value="Re-Sequencing">RE-Sequencing</option>
<option value="QC Check">QC Check</option>
<option value="Analysis Started">Analysis Started</option>
<option value="Analysis Completed">Analysis Completed</option>
<option value="Report">Report</option>
<option value="Outbound">Outbound</option>
</select>
</p>
<p><button><img src="http://icons.iconarchive.com/icons/icons8/windows-8/32/User-Interface-Available-Updates-icon.png" height="50" /> UPDATE</button></p>
</form>
update.php
<?php
$so = $_POST['soid'];
$st = $_POST['samplerecived'];
$st1 = $_POST['molbioextraction'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "status";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
switch ($st):
case $st:$result = mysqli_query($conn, "UPDATE statusinfo SET `samplerecived`= CURTIME() WHERE soid='$so' ") or die(mysqli_error($conn));
break;
case $st1:$result1 = mysqli_query($conn, "UPDATE statusinfo SET `molbioextraction`= CURTIME() WHERE soid='$so' ") or die(mysqli_error($conn));
break;
echo "Updated sucessfully with So Number $so Current Status is set to $st ";
$conn->close();
?>
Kindly help me to do so, if you guys need any more information feel free to ask.
Thanks in advance
If I understand your problem correctly, you only need the user selected fields to be inserted and the other to be either NULL or some default value.
You have the default value for all the fields set as CURRENT_TIMESTAMP. This is why all the fields are being assigned a default value of the current timestamp. Remove the default value, allow them to be NULL (or set some default value other than CURRENT_TIMESTAMP) and your problem will be solved.

PHP retrieving tables from drop down list

Is there anyway of retrieving whole tables based on a drop down list? Like when i select one and press submit it will bring that particular table? 'gameResults' is the database which features tables. My code is as follows:
if(isset($_POST["submit"])) {
$tablesnames = $_POSt["tablenames"]; // name of selection list
if($_POST["tablenames"] == '1') { // if option 1 is selected
// display table
} }
<?php
$conn = mysql_connect("localhost", "xxxxxx", "xxxxxx");
mysql_select_db("gameResults", $conn)
or die ('Database not found ' . mysql_error() );
"SELECT TABLE FROM information_schema.tables WHERE table_schema = 'gameResults'";
$rs = mysql_query($sql, $conn)
or die ('Problem with query' . mysql_error());
?>
<html>
<body>
<form name ="tables" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>Choose form to display :
<select name="tablesnames" id="tablesnames">
<option value="nothing"> </option>
<option value="fixtures"> Fixtures </option>
<option value="results"> Results </option>
<option value="teams"> Teams </option>
<option value="seasons"> Seasons </option>
<option value="administrators"> Administrators </option>
<option value="users"> Users </option>
</select></p>
<input type="submit" name="submit" > <input type="reset"
<html>
</body>
First off, there is no column TABLE. What you are looking for is TABLE_NAME. Consider this example: (And please stop using mysql_ functions, use PDO or mysqli_ instead)
<?php
$tables = array();
// host, db user, db password, datababse
$con = mysqli_connect("localhost","test","test","test");
$query = mysqli_query($con, "SELECT `TABLE_NAME` FROM `information_schema`.`tables` WHERE `TABLE_SCHEMA` = 'test'");
$tables = mysqli_fetch_all($query, MYSQLI_ASSOC);
?>
<!-- loop thru the values -->
<select name="whatever">
<?php foreach($tables as $value): ?>
<option value="<?php echo $value['TABLE_NAME']; ?>"><?php echo $value['TABLE_NAME']; ?></option>
<?php endforeach; ?>
</select>

Categories