how to create several autocomplete fields with html5 and mysql - php

I want to create a simple html input page to enter data into mysql db for later use. In order to save time on input I would like to have some fields as autocomplete fields.
I found a script here and after adjusting some values it looks like this
<?php
//connect to mysql database
$connection = mysqli_connect("localhost","user","password","autocomplete_test")
or die("Error " . mysqli_error($connection));
//fetch data from database
$sql = "select distinct First_Name from data";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
?>
<!DOCTYPE html>
<html>
<head>
<title>Autocomplete Textbox in HTML5 PHP and MySQL</title>
</head>
<body>
<label for="fname">First Name</label>
<input type="text" list="firstname" autocomplete="off" id="fname">
<datalist id="firstname">
<?php while($row = mysqli_fetch_array($result)) { ?>
<option value="<?php echo $row['First_Name']; ?>"><?php echo $row['First_Name']; ?></option>
<?php } ?>
</datalist>
<?php mysqli_close($connection); ?>
</body>
</html>
This works great for one field but when I try to add a second field I cannot figure out how to make the second field autocomplete too. In my example I want a second field for 'Last_Name'. It's in the database and I can call all values for First_Name and Last_Name with while and echo as a simple display of what's there before the html part.
Whatever I try I get autocomplete for first field or for second field or just the first entry from db for both fields.
Please help. Thanks.

There's nothing stopping you from simply querying the database twice, and outputting two inputs:
<?php
//connect to mysql database
$connection = mysqli_connect("localhost","user","password","autocomplete_test")
or die("Error " . mysqli_error($connection));
//fetch data from database
$sql1 = "select distinct First_Name from data";
$result1 = mysqli_query($connection, $sql1) or die("Error " . mysqli_error($connection));
$sql2 = "select distinct Last_Name from data";
$result2 = mysqli_query($connection, $sql2) or die("Error " . mysqli_error($connection));
?>
<!DOCTYPE html>
<html>
<head>
<title>Autocomplete Textbox in HTML5 PHP and MySQL</title>
</head>
<body>
<label for="fname">First Name</label>
<input type="text" list="firstname" autocomplete="off" id="fname">
<datalist id="firstname">
<?php while($row = mysqli_fetch_array($result1)) { ?>
<option value="<?php echo $row['First_Name']; ?>"><?php echo $row['First_Name']; ?></option>
<?php } ?>
</datalist>
<label for="lname">Last Name</label>
<input type="text" list="lastname" autocomplete="off" id="lname">
<datalist id="lastname">
<?php while($row = mysqli_fetch_array($result2)) { ?>
<option value="<?php echo $row['Last_Name']; ?>"><?php echo $row['Last_Name']; ?></option>
<?php } ?>
</datalist>
<?php mysqli_close($connection); ?>
</body>
</html>

Related

Dynamic dropdown for a webpage is not populating from my database

I cannot figure out why the dynamic dropdown won't populate from my database.:
<!doctype html>
<html>
<body>
<h2>Insert Album</h2>
<form action="insertalbum.php" method="POST">
Title: <input type="text" name="atitle" maxlength='50' required><br>
Band: <select name='bands'>
<?php
$conn = mysqli_connect("Server","database","password","username"); //i put in these placeholder for my actual credentials
// Check connection
if(mysqli_connect_errno()){
echo nl2br("Failed to connect to MySQL: " . mysqli_connect_error() . "\n ");
}
$query = "SELECT DISTINCT name FROM band";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
unset($name);
$name = $row['name'];
echo '<option value="name"> $name </option>';
}
?>
</select>
<br>
Published Year: <input type="number" name="pyear" min='1900' max='2020' required><br>
Publisher: <input type="text" name="pname" maxlength='50' required><br>
Format:<select> <option value="record"> Record </option>
<option value="cd"> CD </option>
<option value="casette"> Casette </option>
</select> <br>
Price: <input type="number" name="price" min='0' max='9999.99'><br>
<input type="submit" value="Insert">
</form>
</body>
</html>
this a example:
<select id="employee">
<option value="" selected="selected">Select Employee Name</option>
<?php
/* connection */
$conn = mysqli_connect("Server","database","password","username");
/* query */
$sql = "SELECT id, employee_name, employee_salary, employee_age FROM employee LIMIT 10";
/* get data from db */
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
/* build your dropdown*/
while( $rows = mysqli_fetch_assoc($resultset) ) {
?>
<option value="<?php echo $rows["id"]; ?>"><?php echo $rows["employee_name"]; ?></option>
<?php } ?>
</select>

Deleting data in database with dropdown menu in PHP

I am struggling with deleting data in my database with my drop-down menu.
My drop-down menu looks like this
<form method="post" action="admin.php">
<h3>Delete a user</h3>
<select name="username">
$sql = mysqli_query($connection, "SELECT username FROM users");
while ($row = $sql->fetch_assoc()){
?>
<option value="username" name="username">
<?php echo $row['username']; ?></option>
<?php } ?>
<input type="submit" name="delete" value="Delete User">
</form>
And this is displaying the users all good like i want it, so here is the php for it
<?php
include('connect.php');
if(isset($_POST['delete'])) {
$username = $_POST['username'];
mysqli_query("DELETE FROM `users` WHERE `username` = '$username' ");
echo "User was deleted!";
}
?>
So when i hit the submit button "Delete User", it looks like i get sent to admin.php and nothing happens.
How can i fix this?
Thanks.
Replace name="username" from <option></option>
Echo value in value of option.
Connection variable missing in admin.php page
Updated Code
<select name="username">
<?php
$sql = mysqli_query($connection, "SELECT username FROM users");
while ($row = $sql->fetch_assoc()){?>
<option value="<?php echo $row['username']; ?>"><?php echo $row['username']; ?></option>
<?php }?>
</select>
admin.php
$stmt = $connection->prepare("DELETE FROM `users` WHERE `username` = ?");
$stmt->bind_param('s', $username);
$stmt->execute();
1.<option value="username" name="username"> Need to be <option value="<?php echo $row['username']; ?>">
2.Connection variable is missing . Need to be:-
mysqli_query($connection,"DELETE FROM `users` WHERE `username` = '$username' ");
Modified code need to be:-
Form code:-
<?php
//comment these two lines when code started working fine
error_reporting(E_ALL);
ini_set('display_errors',1);
include('connect.php');
?>
<form method="post" action="admin.php">
<h3>Delete a user</h3>
<select name="username">
<?php
$sql = mysqli_query($connection, "SELECT username FROM users");
while ($row = mysqli_fetch_assoc($sql)){?>
<option value="<?php echo $row['username']; ?>"><?php echo $row['username']; ?></option>
<?php }?>
</select>
<input type="submit" name="delete" value="Delete User">
</form>
Php code:-
<?php
//comment these two lines when code started working fine
error_reporting(E_ALL);
ini_set('display_errors',1);
include('connect.php');
if(isset($_POST['delete'])) {
$username = $_POST['username'];
if(mysqli_query($connection,"DELETE FROM `users` WHERE `username` = '$username' ")){
echo "User was deleted!";
}
}
?>
Note:- Always do some error-reporting so that you will get error and rectify that.
Your query is vulnerable to SQL INJECTION so read about prepared statements and use them.
Change
<option value="username" name="username">
<?php echo $row['username']; ?></option>
To
<option value="<?php echo $row['username'] ?>" name="username">
<?php echo $row['username']; ?></option>
You are not putting the value in select option that's why nothing happens
Just replace
<option value="username" name="username">
<?php echo $row['username']; ?></option>
<?php } ?>
with
<option value="<?php echo $row['username']; ?>">
<?php echo $row['username']; ?></option>
<?php } ?>
It will work for you.

Search multiple Criteria - And/or search in PHP

Not sure what I am doing wrong here. I would like to create a search that allows the user to do an and or search.
However when I use the below code, if I type in Brown as Colour1 it will return all results, same as post code.
The goal is to allow the user to search multiple fields to return a match. So Colour1 and Postcode
<html>
<head>
<title> Logo Search</title>
<style type="text/css">
table {
background-color: #FCF;
}
th {
width: 250px;
text-align: left;
}
</style>
</head>
<body>
<h1> National Logo Search</h1>
<form method="post" action="singlesearch2.php">
<input type="hidden" name="submitted" value="true"/>
<label>Colour 1: <input type="text" name="criteria" /></label>
<label>Colour 2: <input type="text" name="criteria2" /></label>
<label>PostCode: <input type="text" name="criteria3" /></label>
<label>Suburb: <input type="text" name="criteria4" /></label>
<input type="submit" />
</form>
<?php
if (isset($_POST['submitted'])) {
// connect to the database
include('connect.php');
//echo "connected " ;
$criteria = $_POST['criteria'];
$query = "SELECT * FROM `Mainlist` WHERE (`Colour1`like '%$criteria%')
or
('Colour2' like '%$criteria2%')
or
('PostCode' = '%$criteria3%')
or
('Suburb' like '%$criteria4%')
LIMIT 0,5";
$result = mysqli_query($dbcon, $query) or die(' but there was an error getting data');
echo "<table>";
echo "<tr> <th>School</th> <th>State</th> <th>Suburb</th> <th>PostCode</th> <th>Logo</th> <th>Uniform</th></tr>";
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['School'];
echo "</td><td>";
echo $row['State'];
echo "</td><td>";
echo $row['Suburb'];
echo "</td><td>";
echo $row['PostCode'];
echo "</td><td><img src=\"data:image/jpeg;base64,";
echo base64_encode($row['Logo']);
echo "\" /></td></td>";
echo "</td><td><img src=\"data:image/jpeg;base64,";
echo base64_encode($row['Uniform']);
echo "\" /></td></td>";
}
echo "</table>";
}// end of main if statment
?>
</body>
</html>
I can get it to work correctly when I use a dropdown list to select the criteria however I would like them to have multiple options to filter results.
<form method="post" action="multisearch.php">
<input type="hidden" name="submitted" value="true"/>
<label>Search Category:
<select name="category">
<option value="Colour1">Main Colour</option>
<option value="Colour2">Secondary Colour</option>
<option value="PostCode">Post Code</option>
</select>
<label>Search Criteria: <input type="text" name="criteria" /></label>
<input type="submit" />
</form>
<?php
if (isset($_POST['submitted'])) {
// connect to the database
include('connect.php');
echo "connected " ;
$category = $_POST['category'];
$criteria = $_POST['criteria'];
$query = "SELECT * FROM `Mainlist` WHERE $category LIKE '%$criteria%'";
$result = mysqli_query($dbcon, $query) or die(' but there was an error getting data');
In general you run your query with AND condition because it has criteria and you have it means that you have to show value by matching each criteria with receptive column. but it also depends on users or client how they want to show their field.
In short it doesn't have any rule how to show.
Played around with it for a bit and found the answer. I needed to define the criteria. see below code
<?php
if (isset($_POST['submitted'])) {
// connect to the database
include('connect.php');
//echo "connected " ;
$criteria = $_POST['criteria'];
$criteria2 = $_POST['criteria2'];
$criteria3 = $_POST['criteria3'];
$criteria4 = $_POST['criteria4'];
$criteria5 = $_POST['criteria5'];
$query = "SELECT * FROM `Mainlist` WHERE (`Colour1`like '%$criteria%') and (`Colour2`like '%$criteria2%')
and (`PostCode`like '%$criteria3%') and (`Suburb`like '%$criteria4%') and (`State`like '%$criteria5%')

php code to take values from two forms and insert it in table

I have two forms on one page. First one take names of students according to group. Second form is used to enter marks individually. Now i want to insert their marks but failed to do this. Kindly help me regarding this. My code is:
$faculty = null; //declare vars
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Not connected : ' . mysql_error());
}
mysql_select_db('Sims', $link) or die("cannot select DB");
if(isset($_POST["faculty"]))
{
$faculty = $_POST["faculty"];
}
?>
<script language="JavaScript">
function autoSubmit()
{
var formObject = document.forms['theForm'];
formObject.submit();
}
</script>
<form name="theForm" method="post">
<select name="faculty" onChange="autoSubmit();">
<option value="null"></option>
<option value="computer" <?php if($faculty == 'computer') echo " selected"; ?>>Computer</option>
<option value="commerce" <?php if($faculty == 'commerce') echo " selected"; ?>>Commerce</option>
</select>
<br><br>
<?php
if($faculty =='computer')
{
echo "<select name=\"name\">";
$sql = mysql_query("SELECT name FROM std_reg where faculty= 'computer' ") or die(mysql_error());
while($row = mysql_fetch_array($sql)){
echo "<option>".$row[name]."</option>";}
echo "</select>";
}
if($faculty =='commerce')
{
echo "<select name=\"name\">";
$sql = mysql_query("SELECT name FROM std_reg where faculty= 'commerce' ") or die(mysql_error());
while($row = mysql_fetch_array($sql)){
echo "<option>".$row[name]."</option>";}
echo "</select>";
}
?>
<br><br>
</form>
<form method="post">
math <input type="text" name="urdu" />
science <input type="text" name="science" />
social <input type="text" name="social" />
submit
</form>

How to pass table id to another table in PHP

There are 02 tables called item and customer.
item(item_id, item_name)
customer(cus_id, iid, cus_name)
I just tried to store item_id from item to the iid in the customer.
but it always showing null values.
My database is item_sales.
Here is my PHP code
<html>
<title></title>
<head></head>
<body>
<?php
$hostname = "localhost";
$database = "item_sales";
$username = "root";
$password = "";
$con = mysql_pconnect($hostname, $username, $password);
error_reporting(0);
?>
<form action="index.php" method="post" enctype="multipart/form-data">
<p>Customer Name : <input type="text" name="cus_name" /><br/><br/> </p>
<p>Select an Item:
<select name="iid">
<?php
$sql = mysql_query("SELECT * FROM item");
mysql_select_db($database,$con);
while($sqlv = mysql_fetch_array($sql))
{ ?>
<option id="<?php echo $sqlv['item_id']; ?>"><?php echo $sqlv['item_name']; ?></option>
<?php } ?>
</select>
</p>
<?php
if(isset($_POST['submit']))
{
$sql2 = "SELECT * FROM item WHERE iid='%item_id%'";
mysql_select_db($database,$con);
$mydata = mysql_query($sql2);
$cus_name = $_POST['cus_name'];
$sql3 = "INSERT INTO customer (cus_id, iid, cus_name) VALUES ('', '$_POST[iid]', '$cus_name')";
mysql_query($sql3);
}
?>
<input type="submit" name="submit" value="Add Sale" />
</form>
</body>
</html>
The reason it is not working is that you are attempting to save the iid select into the iid field, and I'm guessing the iid field in customer is a numeric type field, like INT - using the POST variable like this, you are going to be saving the text of the SELECT rather than the val.
What you need to do to fix this particular problem is set a "value" on each of the select options. You've set an ID but thats no real help here.
<select name="iid">
<?php
$sql = mysql_query("SELECT * FROM item");
mysql_select_db($database,$con);
while($sqlv = mysql_fetch_array($sql))
{ ?>
<option value="<?php echo $sqlv['item_id']; ?>"><?php echo $sqlv['item_name']; ?></option>
<?php } ?>
</select>
This is besides the point your code is very dangerous. I would recommend you do not use the original mysql functions as, 1) they don't offer any real protection from malicious users, and 2) they will be removed from PHP support very soon.
See this SO article on how to replace the mysql functionality from your PHP code : How can I prevent SQL injection in PHP?
That article also might help you understand the dangers your code offers.
The correct code is following :
<html>
<title></title>
<head></head>
<body>
<?php
$hostname = "localhost";
$database = "item_sales";
$username = "root";
$password = "";
$con = mysql_pconnect($hostname, $username, $password);
error_reporting(0);
?>
<form action="index.php" method="post" enctype="multipart/form-data">
<p>Customer Name : <input type="text" name="cus_name" /><br/><br/> </p>
<p>Select an Item:
<select name="iid">
<?php
$sql = mysql_query("SELECT * FROM item");
mysql_select_db($database,$con);
while($sqlv = mysql_fetch_array($sql))
{ ?>
<option value="<?php echo $sqlv['item_id']; ?>"><?php echo $sqlv['item_name']; ?></option>
<?php } ?>
</select>
</p>
<?php
if(isset($_POST['submit']))
{
$sql2 = "SELECT * FROM item";
mysql_select_db($database,$con);
$mydata = mysql_query($sql2);
$cus_name = $_POST['cus_name'];
$iid = $_GET['item_id'];
$sql3 = "INSERT INTO customer (cus_id, iid, cus_name) VALUES ('', '$_POST[iid]', '$cus_name')";
mysql_query($sql3);
}
?>
<input type="submit" name="submit" value="Add Sale" />
</form>
</body>
</html>

Categories