I have a search.php in this I'm searching for three fields:
Form no.
Name
Telephone no.
But when I select a From no., from select option and enter in input a Telephone no. and press the search button it search for telephone no. instead of form no.
I want a search like when I select From no. and enter a value of than it should search only for form no nothing else and like all below two option:
serach.php
<div class="tleft">
<h2 class="tdilouge">Search Reports</h2><center>
<table class="tbleft">
<form action="searchbyform.php" method="get">
<thead>
<tr>
<td>
<select name="formnumber" id="formnumber" >
<option>Form No.</option>
<option>Name</option>
<option>Telephone No.</option>
</select>
</td>
<td><input type="text" name="formnumber" id="formnumber" placeholder="Enter" /></td>
<td><input type="submit" value="Search" /></td>
</tr>
</thead>
</form>
</table></center>
</div>
And this is submit.php I have a proper connection of database and column is table name:
submit.php
<?php
$formnumber = $_GET['formnumber'];
$sql = "SELECT * FROM colomn WHERE FormNo = $formnumber OR ConsumerName = $formnumber OR TelephoneNo = $formnumber";
$query = mysql_query( $sql );
if(mysql_num_rows($query) == 0)
{
echo "no result found";
}
echo "<table>";
echo "<thead></thead>";
while( $row = mysql_fetch_array( $query ) )
{
echo "<tr></tr>";
}
echo "</table>";
?>
You could just check which option the person has selected and depending on that selected option you could run the query that belong to that option.
Give the options a value, like this:
(You should change the select name because the textfield is already named formnumber)
<select name="form" id="form" >
<option value="form">Form No.</option>
<option value="name">Name</option>
<option value="telephone">Telephone No.</option>
</select>
So when you choose the option form no. , $_GET['form'] would be "form"
So just use an IF to check the 3 options.
EDIT:
The query when the Form no. has been chosen, will look like this:
"SELECT * FROM colomn WHERE FormNo = $formnumber"
And for the name and telephone no. You should just change the column name.
if($_get['form']="form"){
$sql="SELECT * FROM colomn WHERE FormNo = $formnumber";
}
if($_get['form']="name"){
$sql="SELECT * FROM colomn WHERE ConsumerName = $formnumber";
}
if($_get['form']="telephone"){
$sql="SELECT * FROM colomn WHERE TelephoneNo = $formnumber";
}
Also dont use mysql. Use mysqli or PDO instead.
Related
I have just started to learn PDO and have managed to do simple CRUD operations on one single table.
I am just doing a SELECT * from the table. But this table has a foreign key to another table, and I would rather show the value on that column instead of a ID.
So my table structure is the following. I have a joke table with id and joketext and a foreign key authorId. The author table has authorId and name for the author.
Instead of doing SELECT * on the joke table, I would rather create a view with the following code:
SELECT
joke.joketext,
author.name
FROM
author
INNER JOIN joke
ON author.id = joke.authorid
But for the CRUD operations I would like to show the author.name in a dropdown instead, so the users don't erroneously put in wrong values.
This is how index.php looks like:
<?php
//including the database connection file
include_once("config.php");
//fetching data in descending order (lastest entry first)
$result = $dbConn->query("SELECT * FROM joke ORDER BY id DESC");
?>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
Add New Data<br/><br/>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>Joke</td>
<td>AuthorId</td>
<td>Update</td>
</tr>
<?php
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
echo "<td>".$row['joketext']."</td>";
echo "<td>".$row['authorid']."</td>";
echo "<td>Edit | Delete</td>";
}
?>
</table>
and my edit file looks like this:
<?php
// including the database connection file
include_once("config.php");
if(isset($_POST['update']))
{
$id = $_POST['id'];
$name=$_POST['joketext'];
$authorid=$_POST['authorid'];
// checking empty fields
if(empty($joketext) || empty($authorid)) {
if(empty($joketext)) {
echo "<font color='red'>Name field is empty.</font><br/>";
}
if(empty($authorid)) {
echo "<font color='red'>Author field is empty.</font><br/>";
}
} else {
//updating the table
$sql = "UPDATE joke SET joke=:joketext, authorid=:authorid WHERE id=:id";
$query = $dbConn->prepare($sql);
$query->bindparam(':id', $id);
$query->bindparam(':joketext', $joketext);
$query->bindparam(':authorid', $authorid);
$query->execute();
// Alternative to above bindparam and execute
// $query->execute(array(':id' => $id, ':name' => $name, ':email' => $email, ':age' => $age));
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
}
?>
<?php
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$sql = "SELECT * FROM joke WHERE id=:id";
$query = $dbConn->prepare($sql);
$query->execute(array(':id' => $id));
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$joketext = $row['joketext'];
$authorid = $row['authorid'];
}
?>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
Home
<br/><br/>
<form name="form1" method="post" action="edit.php">
<table border="0">
<tr>
<td>Joke</td>
<td><input type="text" name="joketext" value="<?php echo $joketext;?>"></td>
</tr>
<tr>
<td>Author</td>
<td><input type="text" name="authorid" value="<?php echo $authorid;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>
Can someone show me a hint on at least the edit operations how the php code would like?
thanks
If you wish to provide a select element of available authors for the user to choose from on the edit page, rather than have them enter an ID number for an author, then you can select all the authors from the database and loop through them, building the options of your select element. A select element can show the user the name of the author, but pass the ID of the author back to the server. You can also pre-select an author to show the user the currently associated author by default and they only have to change it if it's wrong.
So first, select all the authors from the database:
$authorSql = 'SELECT * FROM author';
$authorQuery = $dbConn->prepare($authorSql);
$authorQuery->execute();
Then use that data to build a select element:
<select name="authorid">
<?php
while($author = $authorQuery->fetch(PDO::FETCH_ASSOC)) {
if ($author['id'] == $authorid) {
//The author is currently associated to the joke, select it by default
echo "<option value=\"{$author['id']}\" selected>{$author['name']}</option>";
} else {
//The author is not currently associated to the joke
echo "<option value=\"{$author['id']}\">{$author['name']}</option>";
}
}
?>
</select>
The output might look something like this:
<select name="authorid">
<option value="1">George Carlin</option>
<option value="2" selected>Richard Pryor</option>
<option value="3">Don Rickles</option>
</select>
Whatever option the user selects, they'll see on the page what is between the <option></option> tags, but the form will pass the value of the value property to the server as the authorid parameter.
The code that generates the select element replaces the <input type="text" name="authorid" value="<?php echo $authorid;?>"> and remains within the <td></td> tags.
Hope I managed to address your actual need, let me know if I missed the intent of your question.
Note: my code isn't tested, so some adjustment may be required.
EDIT #1: Fixed incorrect variable names.
I am trying to utilize the datalist element. Everything is working with 1 little hitch. The selectable list is showing 2 columns, both the street_id and street columns. I need the street_id that will be submitted but dont want the street_id to show in the datalist.
<?php
require 'connect_mysqli.php';
$sql = "SELECT * FROM streets";
$result = mysqli_query($con, $sql) or die ("Error " . mysqli_error($con));
?>
<form action="test.php" name="test" method = "post">
<datalist id="street" name="streets">
<?php while($row = mysqli_fetch_array($result)) { ?>
<option value="<?php echo $row['street_id']; ?>"><?php echo $row['street']; ?></option>
<?php
}
?>
</datalist>
<input type="text" name="street_val" id="test" autocomplete="off" list="street">
<input type="submit" value="Submit">
</form>
<?php
mysqli_close($con);
//test the output value
echo $_POST['street_val'];//
?>
You have coded a select list - which has separate values for display and returned values. In the datalist, you only need value="" for options and then it will only return that value. Also better to keep the server code and display code separate: i.e. populate or build the array in the PHP with your query, then in the HTML only display it.
I was wondering how to make a search form where user has 3 options to search with
Search By age (dropdown 18-25 & 26-40)
Search By gender (male or female)
Search By name
In my code, when I click "Submit" with blank fields, it's throwing all data which i don't it to:
<?php
$output = NULL;
if (isset ( $_POST ['submit'] )) {
// Connect to database
$mysqli = new Mysqli ( "localhost", "root", "2222", "matrimonialPortal" );
$search = $mysqli->real_escape_string ( $_POST ['search'] );
// Query the databse
$resultSet = $mysqli->query ( "SELECT * FROM mp_user WHERE name LIKE '%$search%' OR email LIKE '%$search%' OR salutation LIKE '%$search%' OR id LIKE '%$search%'" );
if ($resultSet->num_rows > 0) {
while ( $rows = $resultSet->fetch_assoc () ) {
$name = $rows ['name'];
$email = $rows ['email'];
$output .= "::<strong>The Details of your search</strong> ::<br /> Name: $name<br /> Email:$email<br /><br /> ";
}
} else {
$output = "Oops No results Found!!";
}
}
?>
<!-- The HTML PART -->
<form method="POST">
<div>
<p>
Search By name: <input type="TEXT" name="search" /> <input
type="SUBMIT" name="submit" value="Search >>" />
</p>
</div>
<div>Search By Age :
<select name="age">
<option></option>
<option value="18-20">18-20</option>
<option value="20-25">20-25</option>
</select><input type="SUBMIT" name="submit" value="Search >>" />
</div>
<br />
<div>
Search By Gender:
<select name="salutation">
<option></option>
<option value="0">--- Male ---</option>
<option value="1">--- Female ---</option>
</select> <input type="SUBMIT" name="submit" value="Search >>" />
</div>
<br> <br>
</form>
<?php echo $output; ?>
It seems like you are new to PHP. Here is a solution for you.
First HTML PART. Here use "action" which means that the page will locate the file and process data. For example action="search_process.php". But if you are processing the data from the same page use $_SERVER['PHP_SELF'];
<!-- The HTML PART -->
<form method="POST" action="$_SERVER['PHP_SELF']"> // here it will load the self page
<div>
<p>
Search By name: <input type="text" name="search_name" />
Search By age: <input type="text" name="search_age" />
Search By gender: <input type="TEXT" name="search_gender" />
<input type="submit" name="submit_name" value="Search >>" />
</p>
</div>
Now the PHP part:
<?php
if(isset($_POST['submit_name'])
{
//What happens after you submit? We will now take all the values you submit in variables
$name = (!empty($_POST['search_name']))?mysql_real_escape_string($_POST['search_name']):null; //NOTE: DO NOT JUST USE $name = $_POST['search_name'] as it will give undefined index error (though your data will be processed) and will also be open to SQL injections. To avoid SQL injections user mysql_real_escape_string.
$age = (!empty($_POST['search_age']))?mysql_real_escape_string($_POST['search_age']):null;
$gender = (!empty($_POST['search_gender']))?mysql_real_escape_string($_POST['search_gender']):null;
//Now we will match these values with the data in the database
$abc = "SELECT * FROM table_name WHERE field_name LIKE '".$name."' or field_gender LIKE '".$gender."' or field_age LIKE '".$age."'"; // USE "or" IF YOU WANT TO GET SEARCH RESULT IF ANY OF THE THREE FIELD MATCHES. IF YOU WANT TO GET SEARCH RESULT ONLY WHEN ALL THE FIELD MATCHES THEN REPLACE "or" with "and"
$def = mysql_query($abc) or die(mysql_error())// always use "or die(mysql_error())". This will return any error that your script may encounter
//NOW THAT WE HAVE GOT THE VALUES AND SEARCHED THEM WE WILL NOW SHOW THE RESULT IN A TABLE
?>
<table cellspacing="0" cellpadding="0" border"0">
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
</tr>
<?php while($row = mysql_fetch_array($def)) { // I HAD MISSED OUT A WHILE LOOP HERE. SO I AM EDITING IT HERE. YOU NEED TO USE A WHILE LOOP TO DISPLAY THE DATA THAT YOU GOT AFTER SEARCHING.
<tr>
<td><?php echo $row[field_name]; ?></td>
<td><?php echo $row[field_age]; ?></td>
<td><?php echo $row[field_gender]; ?></td>
</tr>
<?php } ?>
</table>
<?php } ?>
A perfect solution for your query. All the best.
Well i cant give you the whole code, but here are the few solutions..
Use 3 different forms with 3 different submit buttons.
Use radio buttons on html form, and make a check on PHP side and perform operations depending upon what or which radio is selected.
Use a button instead of submit, radio buttons, hidden fields, and pass data to different php page on form submit (this can be lengthy).
Well you have options.
You can replace your code
if ($resultSet->num_rows > 0) {
with this
if ($resultSet->num_rows > 0 and trim($search) != "") {
so it will not show all results if your input box is empty
hope this will help you
Edit
here is an example you can get idea
$qry = "SELECT * FROM test WHERE 1=1";
if($purpose!="")
$qry .= " AND purpose='$purpose'";
if($location!="")
$qry .= " AND location='$location'";
if($type!="")
$qry .= " AND type='$type'";
and for age
if ($age!='') {
$qry .= " AND age between ".str_replace('-',' and ',$age);
}
When you POST a blank variable and Query with %$search% and 'OR' other criteria, sql matches all records with space in column Name ! So you will have to use some variation of;
If(empty($POST['search']){ ['Query witbout Name parameter']} else{['Query with Name parameter']}
As for converting DOB to match age range. You will have to use
SELECT TIMESTAMPDIFF
answered here
calculate age based on date of birth
Recently,I'm creating a school library Ser with three table in database(Newlibrary).
Three table is - Econ books , Geo books ,Chem books
In each table, it have (Student name) and (Tel No.).
I want to create a poor search engine with( A drop down list - Use select table) and input (Tel in
which selected table)
Here is the code ,How to use A drop down list to select table( Econ books or Geo books or Chem books )and input tel to search in table which selected at the same time ?
((index.html))
<form method="GET" action="searchtitle">
<select name="booktype" value="<?=$['booktype']?>">
<option value="" selected="selected"></option>
<option value="a">Econbooks</option>
<option value="b">Geobooks</option>
<option value="c">Chembooks</option>
</select>
<input id="inputkeyword" type="text" name="keyword" placeholder="Please enter a keyword...."/>
<input type="submit" class="keyword" value="search" />
</form>
((searchtitle.php))
<?php
$keyword = $_GET['keyword'];
$con = mysql_connect("localhost","root","password");
mysql_select_db("newlibrary");
$sql = "Select * from borrower
where Telp='$keyword' ";
$results = mysql_query($sql,$con);
if(mysql_num_rows($results) == 0) {echo "<h1>No Record Has Been Found!!</h1> ";} else {
echo "<table id='borrowertable' >
<tr>
<th>ID</th>
<th>Name</th>
<th>Tel</th>
</tr>" ;
while($row = mysql_fetch_array($results)) {
$bid = $row[0];
$Names = $row[1];
$Tel = $row[2];
echo " <tr>
<td>$bid</td>
<td>$Names</td>
<td>$Tel</td>
</tr>";
}
}
mysql_close($con);
echo "<p> <a href='index'>Back Home</a> ";
?>
How to change it?
If I got you right, you need to be able to search one of the three table as per user's selection using a phone number. I am not sure if you want to use Javascript, hope this can be helpful
First you need to pass both the Select and textbox values to searchtitle.php
function get_User() {
var user_data = {};
user_data['Book'] = document.getElementById("DropDownID").value; // get dropdown selected value
user_data['phone'] = document.getElementById("inputkeywor").value; // get dropdown selected value
$.ajax({
type: "POST",
url: "searchtitle.php",
beforeSend: function () {
$( "#LoadingDiv" ).html("Searching User...");
},
data: user_data,
success: function (data) {
Here Data is the result of searchTtitle.php.....
}}});
Then on searchtitle.php you get the values from
$keyword = $_POST['phone'];
$TableToQuery = $_POST['Book'];
call get_User on submit
<input type="button" class="keyword" value="search" onclick="get_User()" />
I am trying to use php to make a simple option list for a form that can save the list in a database, the list are editable so you can add, rename or delete rows in it. I got the rename and the add to work from simple input boxes but i want to use a drop down list for the deletion sounds simple but i don´t manage to understand why it wont work so i will try to ask for help :)
This bit of code is suppose to delete the selected item from the database
<?php
$ukat_to_delete ="";
if (isset($_POST['delunderkat'])) {
$ukat_to_delete = $_GET['delunderkat'];
$sql = mysql_query("DELETE FROM listor WHERE underkategori = '$ukat_to_delete' LIMIT 1") or die (mysql_error());
header("location: lagtillsaker.php");
exit();
}
?>
and this is the code i use to make a form that shows the list
<form action="lagtillsaker.php" enctype="multipart/form-data" name="myForm3" id="myForm3" method="post">
<table width="100%" border="0">
<tr>
<td width="25%">Ta bort en Underkategori </td>
<td width="75%"><select name="delunderkat">
<option value=""></option>
<?php echo $grupplista ?>
</select>
<input name="delunderkatknap" type="submit" value="Ta bort Underkategorin" /></td>
</tr>
</table>
</form>
and i use this bit of code to generate the list
<?php
$grupplista="";
$sql=mysql_query("SELECT DISTINCT underkategori FROM listor");
$producktCont=mysql_num_rows($sql);
if ($producktCont>0){
while($row = mysql_fetch_array($sql)){
$underkategori = $row["underkategori"];
$grupplista .= "<option value='$underkategori'>$underkategori</option>";
}
}else{
echo "det finns inga underkategorier";
}
?>
i don´t know how i can get the form´s select bar into a working array so i can delete it in the database? I get the code to remove a string or option with no content as if the option value always is nothing in the string output.
You are doing POST and trying to get the data as GET
$ukat_to_delete = $_GET['delunderkat'];
should be
$ukat_to_delete = $_POST['delunderkat'];