I'm trying to create a search query where in the user could either search the database using the firstname or lastname or both. I am able to do this using 1 type of search only, but if I do both I'm not sure how I could do this.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Search Contacts</title>
<link href="site.css" rel="stylesheet">
</head>
<body>
<nav id="nav01"></nav>
<div id="main">
<h3>Search Contact Details</h3>
<form method="post" action="#" id="searchform">
First Name:<br>
<input type="text" name="fname">
<br>Last Name:<br>
<input type="text" name="lname">
<br>
<input type="submit" name="submit" value="Search">
</form>
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
$myquery = mysqli_real_escape_string($connection,$_POST["fname"]);
$myquery2 = mysqli_real_escape_string($connection,$_POST['lname']);
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// SQL query
if (!empty($myquery)) {
$sql = "select distinct ID, FirstName, LastName, Email, PhoneNumber
from Userlist where FirstName LIKE '%". $myquery ."%' OR LastName LIKE '%".$myquery2."%'";
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0)
{
//Headers
echo "<table>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
}
mysqli_close($conn);
?>
<footer id="foot01"></footer>
</div>
<script src="script.js"></script>
</body>
</html>
You can do like this:
<?php
if(strlen($_POST["fname"])>0 AND strlen($_POST["lname"])>0){
$sql = "SELECT ID, FirstName, LastName, Email, PhoneNumber FROM Userlist WHERE FirstName LIKE '%". $_POST["fname"])>."%' AND LastName LIKE '%". $_POST["lname"])>."%'";
}
elseif(strlen($_POST["fname"])>0 AND strlen($_POST["lname"])==0){
$sql = "SELECT ID, FirstName, LastName, Email, PhoneNumber FROM Userlist WHERE FirstName LIKE '%". $_POST["fname"])>."%'";
}
elseif(strlen($_POST["lname"])>0 AND strlen($_POST["fname"])==0){
$sql = "SELECT ID, FirstName, LastName, Email, PhoneNumber FROM Userlist WHERE LastName LIKE '%". $_POST["lname"])>."%'";
}
else{
//No keywords specified
}
?>
You can simply use OR and distinct on ID, so that you only get 1 entry if the user searchs for both, FirstName and LastName
$myquery = mysqli_real_escape_string($connection,$_POST["fname"]); //<<< change $connection to your connection variable
$myquery2 = mysqli_real_escape_string($connection,$_POST['lname']);
$sql = "select distinct ID, FirstName, LastName, Email, PhoneNumber
from Userlist where FirstName LIKE '%". $myquery ."%' OR LastName LIKE '%".$myquery2."%'";
You should escape everything you search for in your query, either with
mysqli_real_escape_string
as written above, or you better use a prepared statement
EDIT:
This :
$myquery = mysqli_real_escape_string($connection,$_POST["fname"]);
$myquery2 = mysqli_real_escape_string($connection,$_POST['lname']);
needs to be after you established your connection. And as you are using $conn for your connection, you need to change it to
$myquery = mysqli_real_escape_string($conn,$_POST["fname"]);
$myquery2 = mysqli_real_escape_string($conn,$_POST['lname']);
Like this:
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$myquery = mysqli_real_escape_string($conn,$_POST["fname"]);
$myquery2 = mysqli_real_escape_string($conn,$_POST['lname']);
Your code is subject to be sql injection attack and so i have tried to make it better with corrections.
<h3>Search Contact Details</h3>
<form method="post" action="#" id="searchform">
First Name:<br>
<input type="text" name="fname">
<br>Last Name:<br>
<input type="text" name="lname">
<br>
<input type="submit" name="submit" value="Search">
</form>
<?php
/*USE PDO prepared statement to prevent mysql injection attacks*/
//PDo constructor instantiating instance of database object.
$pdo = PDO('mysql:host=localhost;dbname=YourDatabaseName;charset=utf8', 'YourUserName', 'YourPassword');
//check if something is submitted
if(isset($_POST['submit']) ){
//remove tags from the user input
$fname = strip_tags('%'.$_POST['fname'].'%');
$lname = strip_tags('%'.$_POST['lname'] .'%');
//you need to use the if- conditional to
//check if one or both fields are set
if ( (isset($fname) && !empty($fname)) || (isset($lname) && !empty($lname)) ) {
try{
$sql = "SELECT distinct ID, FirstName, LastName, Email, PhoneNumber
FROM Userlist
WHERE `FirstName` LIKE :FirstName OR `LastName` LIKE :LastName";
//Prepare the statment
$query = $pdo->prepare($sql);
$query->bindParam(':FirstName', $fname, PDO::PARAM_STR);
$query->bindParam(':LastName', $lname, PDO::PARAM_STR);
$query->execute();
$result = $query->fetchAll();
} catch (Exception $e) {
print "Database Problem: " . $e->getMessage();
}
}
//you can use foreach to display the result.
foreach ($result as $res):
echo $rs['FirstName']; //and so on
endforeach;
}
else{
echo 'search for some thing';
}
?>
Related
I'm making a newsletter for my promo website and it doesn't work for me, its a very simple form, just a register.php and connect.php to connect the database with the php. The code looks like this:
The connect.php
<?php
$servername = "localhost";
$username = "root";
$password = "laidinis69";
$database = "promo";
$con = mysqli_connect($servername, $username, $password, $database);
?>
The register.php
<?php
include('connect.php');
$form_name = $_POST['name'];
$form_email = $_POST['email'];
$query = 'SELECT * FROM subscribers WHERE name="' .$form_name. '";';
if($result = mysqli_query($con, $query)) {
if(mysqli_num_rows($result) == 0) {
$query = 'INSERT INTO subscribers (name, email) VALUES("'.$form_name.'","'.$form_email.'")';
if(mysqli_query($con, $query)) {
echo "registered";
}
} else {
echo "already exists";
}
}
header('Location: register.php');
?>
The form on my index.html file:
<form action="register.php" method="post">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
<input type="submit" name="register" value="Subscribe">
</form>
When I press on Subscribe button, it redirects me to register.php and does not put in data in the database.
I believe you need to try changing this line
if($result = mysqli_query($con, $query)) { ...
to this
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result) == 0) {
$query = 'INSERT INTO subscribers (name, email) VALUES ("'.$form_name.'","'.$form_email.'")';
and be sure to delete the extra } that goes with the if-satement you'll be deleting.
I'm new to PHP and would like to start a simple query system by just searching identification number and it will print out full name, date of birth, gender and identification number.
The first file name of the page is search.php.
Inside of the file contains
<html>
<body>
<form action="result.php" method="get">
ID Number: <input type="text" name="idnumber"> <input type="submit" value="Search"><br>
</form>
<p>Input ID number</p>
</body>
</html>
After that, I created a database named users and with following columns (id, full_name, date_of_birth, gender, identification_number)
What code should I write into result.php to let the search result of identification number match and found it will print all the details of the person and the search keyword must 100% match.
Example of the scenario.
In database has John Doe, 20 September 1990, Male, 900920A44.
Search keyword "900920A44" will print out corresponding user's information but if search keyword "900920A" will not print out anything because other user might had a "900920A55" identification number.
Files:
search.php & result.php
Please advise.
try this
FORM
<html>
<body>
<form action="result.php" method="get">
ID Number: <input type="text" name="idnumber"> <input type="submit" name="form_submit" value="Search"><br>
//PUT THE NAME FOR SUBMIT BUTTON
</form>
<p>Input ID number</p>
</body>
</html>
result.php
//database connection
global $conn;
$servername = "localhost"; //host name
$username = "username"; //username
$password = "password"; //password
$mysql_database = "dbname"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
if(isset($_GET['form_submit']))
{
$IDNUMBER =$_GET['idnumber'];
$stmt = $conn->prepare("select * from your_table_name_here where identification_number=? ");
$stmt->bind_param('s',$IDNUMBER);
$stmt->execute();
$val = $stmt->get_result();
$row_count= $val->num_rows;
if($row_count>0)
{
$result =$val->fetch_assoc();
print_r($result);
}
else
{
echo "identification_number not Match";
}
$stmt->close();
$conn->close();
}
Use this.
login.php
<html>
<body>
<p>Input ID number</p>
<form action="result.php" method="get">
ID Number: <input type="text" name="idnumber"> <input type="submit" value="Search"><br>
</form>
</body>
</html>
result.php
<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "users";
mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database) or die("Could not select database");
$idmark = $_GET['idnumber'];
$sql = "select * from student where identification_number = '".$idmark."'";
$result = mysql_query($sql);?>
<table width="70%" border="1px solid black">
<tr style="background-color:green; color:white">
<th><strong>ID</strong></th>
<th><strong>Name</strong></th>
<th><strong>DOB</strong></th>
<th><strong>GENDER</strong></th>
<th><strong>Identification No</strong></th>
</tr>
<?php if (mysql_num_rows($result)>0) { $i=0;
while($row = mysql_fetch_assoc($result)) { ?>
<tr class="<?php echo ($i%2) ? 'even' : 'odd' ?>">
<td><?php echo $row['id'];?></td>
<td><?php echo $row['full_name'];?></td>
<td><?php echo $row['date_of_birth'];?></td>
<td><?php echo $row['gender'];?></td>
<td><?php echo $row['identification_number'];?></td>
</tr>
<?php $i++;}}
?>
I'm trying to use a simple form to run a database search. I'm not getting a database connection error so I'm pretty certain that's not the problem. I checked my target page for the echo display, but I'm not receiving any out put.
<!DOCTYPE HTML>
<html lang = "en">
<head>
<title>Tech Order Department.html</title>
<meta charset = "UTF-8" />
</head>
<body>
<h3>Search Contacts Details</h3>
<p>You may search either by first or last name</p>
<form method="post" action="Search.php" id="searchform">
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form>
<?php
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['name'])){
$name=$_POST['name'];
//connect to the database
$servername = "localhost";
$username = "XXXXXXXXX"; // removed
$password = "XXXXXXXXX"; // removed
$dbname = "oldga740_SeniorProject";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//-select the database to use
$mydb=mysql_select_db("oldga740_SeniorProject");
//-query the database table
$sql="SELECT ID, FirstName, LastName FROM Staff WHERE FirstName LIKE '%" . $name . "%' OR LastName LIKE '%" . $name ."%'";
//-run the query against the mysql query function
$result=mysql_query($sql);
//-create while loop and loop through result set
while($row=mysql_fetch_array($result)){
$FirstName =$row['FirstName'];
$LastName=$row['LastName'];
$ID=$row['ID'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . "" .$FirstName . " " . $LastName . "</li>\n";
echo "</ul>";
}
}
else{
echo "<p>Please enter a search query</p>";
}
}
}
?>
</body>
</html>
I have that people can add team names to my MySQL table. Now I want them to edit it. I have tried several tutorials but i can't figure it out. I like to know what i am doing wrong.
This is my admin.php:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
if(isset($_POST['team'])){
$team = $_POST['team'];
$ID = $_POST['id'];
$query = mysql_query("SELECT * FROM e2teams WHERE Team='$team' and ID='$ID'");
if(mysql_num_rows($query) > 0 ) { //check if there is already an entry for that username
echo "$team bestaat al!";
}
else{
mysql_query("INSERT INTO e2teams (Team) VALUES ('$team')");
header("location:e2admin.php");
}
}
mysql_close();
?>
<html>
<body>
<h1>Add teams</h1>
<form action="e2admin.php" method="POST">
<input type="text" name="team" placeholder="Team naam" /><br>
<input type="submit" value="Toevoegen" />
</form>
<?php
$table = "e2teams";
$sql = "SELECT * FROM e2teams";
$result = mysql_query($sql, $dbhandle);
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)) {
echo $row['Team']. "<a href='edit.php?edit=$row[1]'>Bewerk</a><br>";
}
}
?>
</body>
</html>
The add teams works. but the edit button doesn't work yet. If I click on edit I go to the edit.php page; here I want to add the new name and need the Team to change in the MySQL row.
This is my edit.php:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
if( isset($_GET['edit'])) {
$id = $_GET['edit'];
$res = mysql_query("SELECT * FROM e2teams");
$row= mysql_fetch_array($res);
}
if (isset ($_POST['nieuwenaam'])) {
$newname = $_POST['nieuwenaam'];
$id = $_POST['id'];
$sql = "UPDATE e2teams SET Team='$newname' WHERE id='$id'";
$res = mysql_query($sql) or die ("Fout bij updaten".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=edit.php'>";
}
?>
<html>
<body>
<form action="edit.php" method="POST">
<input type="text" name="nieuwenaam" placeholer="test" /><br>
<input type="hidden" name="id" placeholder="idnaam" value"s" /><br>
<input type="submit" value="Update" />
</form>
</body>
</html>
I also like to know how to delete team names but this is maybe for a next question.
This should work:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
$id = intval($_GET['edit']);
if($id > 0) {
$res = mysql_query("SELECT * FROM e2teams WHERE `id` = $id");
$row= mysql_fetch_array($res);
$newname = mysql_real_escape_string($_POST['nieuwenaam']);
if (!empty($newname)) {
$sql = "UPDATE e2teams SET Team='$newname' WHERE id=$id";
$res = mysql_query($sql) or die ("Fout bij updaten".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=edit.php?edit=$id'>";
}
}
?>
<form action="edit.php?edit=<?= $id; ?>" method="POST">
<input type="text" name="nieuwenaam" placeholer="test" /><br>
<input type="submit" value="Update" />
</form>
</body>
</html>
Edit: Also, about the intval() and mysql_real_escape_string(). Since you were using $_GET without any filter, I've added intval() function on it. Without filtering $id you could've been easily attacked by some sort of e.g. SQL Injection. Same with mysql_real_escape_string(). You might read about this filter function in php manual. For further study I recommend changing mysql_ functions to PDO or mysqli prepared statements. Happy coding!
Check your edit form. You have to put the value attribute like this value="s" no like value"". I think thats all.
I assume when they click on the edit link it's passing the id of the team so the edit.php select should be something like:
$id = (int)$_GET['edit'];
if (!empty($id))
{
$sql = "SELECT * FROM e2teams WHERE id='$id'";
$result = mysqli_query($sql);
$row = mysql_fetch_assoc($res);
}
//... keep the rest of code as is
Now you need to change the HTML form to:
<form action="edit.php?edit=<?php echo $row['id'] ?>" method="POST">
<input type="text" name="nieuwenaam" placeholer="test" value="<?php echo $row['Team'] ?>" /><br>
<input type="hidden" name="id" placeholder="idnaam" value"<?php echo $row['id'] ?>" /><br>
<input type="submit" value="Update" />
</form>
The HTML:
<html>
<?php include 'C:\xampp\htdocs\paxdb\head.php';
include 'config/menu.php';?>
<div id="dataentry">
<!--This section is the demographic text field area-->
<form method="post" action="dataentered.php">
First Name: <input type="text" name="First_Name"/></br>
</br>
Last Name: <input type="text" name="Last_Name"/></br>
</br>
E-mail: <input type="text" name="email"/></br>
</br>
<!--This section is the age range checkbox selection area-->
<p><u><b>Age Range</b></u></p>
<input type="checkbox" name="age[]" id="20-25" value="20-25"/> 20-25</br>
<input type="checkbox" name="age[]" id="26-30" value="26-30"/> 26-30</br>
<input type="checkbox" name="age[]" id="31-35" value="31-35"/> 31-35</br>
</div>
<div id="checkboxes">
</div>
<!--This section is the trips take checkbox area-->
<div id="tripstodatetype">
<p><u><b>WHAT TYPE OF TRIPS TO DATE HAVE YOU TAKEN?</b></u></p>
<input type="checkbox" name="trip2date[]" id="Bus" value="Bus"> Bus </br>
<input type="checkbox" name="trip2date[]" id="Car" value="Car"> Car</br>
<input type="checkbox" name="trip2date[]" id="Weekend fly-in" value="Weekend fly-in"> Weekend fly-in </br>
</div>
<div id="tripstodateborder">
</div>
<!--This section is the type of trip client likes best checkbox area-->
<div id="triplikebest">
<p><u><b>WHAT TYPE OF TRIP DO YOU LIKE BEST?</b></u></p>
<input type="checkbox" name="triplikebest[]" value="Bus"> Bus </br>
<input type="checkbox" name="triplikebest[]" value="Car"> Car</br>
<input type="checkbox" name="triplikebest[]" value="Weekend fly-in"> Weekend fly-in </br>
</div>
<div id="triplikeborder">
</div>
and the PHP:
<html>
<?php
include 'head.php';
include 'config/menu.php';
$host="localhost";
$username="somename";
$password="somepass";
$dbname="pax";
$dbc = mysql_connect($host, $username, $password, $dbname);
if (!$dbc)
{
die('Error connecting to MySQL server' . mysql_error());
}
mysql_select_db($dbname, $dbc);
$first_name = mysql_real_escape_string($_POST['First_Name']);
$last_name = mysql_real_escape_string($_POST['Last_Name']);
$email = mysql_real_escape_string($_POST['email']);
$age = $_POST['age'];
$my_range = "";
foreach($age as $range) {
$my_range = $my_range . mysql_real_escape_string($range) . ", ";
}
$trip2date = $_POST['trip2date'];
$my_triprange = "";
foreach($trip2date as $triprange) {
$my_triprange = $my_triprange . mysql_real_escape_string($triprange) . ", ";
}
mysql_query("INSERT INTO `pax` (`First_Name`, `Last_Name`, `email`, `age`,`trip2date`)
VALUES('$first_name','$last_name','$email', '$my_range','$my_triprange')")
or die(mysql_error());
mysql_close($dbc);
?>
<div class = "entered">
<p>Success! Your Data Has Been Submitted. Please click on <b>'DATA ENTRY'</b> above to enter another. </P>
</div>
<?php include 'footer.php';?>
</div>
</div>
</body>
</html>
If I were to put the triprange data into a separate table, how would I convert the INSERT query to perform the insert into the new table? (let's say the new/second table is called 'trip'). -OR- Does it make more sense to use a second INSERT query here? If so, how should it appear to remain connected to the first table/ID
thank you in advance.
looking at your code, are you trying to enter the same data twice into different tables?
if not you should make your query a variable, so the line would read something like this...
$query1 = mysql_query("INSERT INTO `pax` (`First_Name`, `Last_Name`, `email`, `age`,`trip2date`)
VALUES('$first_name','$last_name','$email', '$my_range','$my_triprange')")
or die(mysql_error());
you could look into repeating the insert statement for another table but use the same variables declared in the original code.
if i am on the wrong lines, could you maybe explain a little more?
mysqli_multi_query();
Read the manual here: http://php.net/manual/en/mysqli.multi-query.php
EDIT:
<?php
/* connection conf */
// use p: if you want to have a persistent connection
// this will improve the speed and resource usage of opening a connection
$host = "p:localhost";
$username = "somename";
$password = "somepass";
$dbname = "pax";
/* make connection */
$lnk = mysqli_connect($host, $username, $password, $dbname);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* prepare variables */
$first_name = mysqli_real_escape_string($_POST['First_Name']);
$last_name = mysqli_real_escape_string($_POST['Last_Name']);
$email = mysqli_real_escape_string($_POST['email']);
$age = $_POST['age'];
$my_range = "";
foreach($age as $range) {
$my_range = $my_range . mysqli_real_escape_string($range) . ", ";
}
$trip2date = $_POST['trip2date'];
$my_triprange = "";
foreach($trip2date as $triprange) {
$my_triprange = $my_triprange . mysqli_real_escape_string($triprange) . ", ";
}
/* execute query */
mysqli_query($lnk, "INSERT INTO `pax` (`First_Name`, `Last_Name`, `email`, `age`,`trip2date`) " .
"VALUES('$first_name','$last_name','$email', '$my_range','$my_triprange');"
);
/* execute multi query INSERT */
mysqli_multi_query($lnk, "INSERT INTO `pax` (`First_Name`, `Last_Name`, `email`, `age`,`trip2date`) " .
"VALUES('$first_name','$last_name','$email', '$my_range','$my_triprange');"
"COMMIT;"
);
/* execute multi query SELECT */
$query = "SELECT CURRENT_USER();";
$query .= "SELECT `email` FROM `pax` ORDER BY `id` LIMIT 5";
if (mysqli_multi_query($lnk, $query)) {
do {
/* store first result set */
if ($result = mysqli_store_result($lnk)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($lnk))
printf("-----------------\n");
} while (mysqli_next_result($lnk));
}
/* close conenction */
mysqli_close($dbc);
// I used your code and some samples from the PHP manual.
// Hope this piece of code helps you and others to understand mysqli better.
// Thanks to PHP for having the best manual.
?>