How to Get the table name in database with select box? - php

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()" />

Related

Editing data in multiple columns from front-end

I have a table in the database, I can edit a column of particular row at a time. but, i want to edit multiple columns of a single row at a time with an option of edit and then save it to the database ,we can do it from back-end by editing in the database itself. But, i want to do it from front-end .Now i am able to display the data in the table. I am new to coding , so can anyone help me where to start for this particular task of editing multiple columns at the same time.
Here is the code for displaying the data..
<?php
include('db.php');
include 'header.php';
include 'gobacktomenu.php';
$TND_ID = $_GET['TND_ID'];
$sql = "SELECT * FROM new_tnds WHERE TND_ID = ('".$TND_ID."')";
$result = $link->query($sql);
echo "<div style='overflow-x:auto;'><table border = '1'><font size = '2' face='verdana'>
<th>TND ID</th><th>Site name S1</th><th>Site name S2</th><th>Call sign S1</th><th>Idea ID S1</th><th>Call sign S2</th><th>Idea ID S2</th><th>Site to integrate</th><th>True azimuth (°) S1</th><th>True azimuth (°) S2</th><th>Pathlength (km)</th><th>TR Antenna diameter (m)</th><th>TR Antenna height (m) S1</th><th>TR Antenna height (m) S2</th><th>Channel ID S1</th><th>Channel ID S2</th><th>Design frequency S1</th><th>Design frequency S2</th><th>Polarization</th><th>Radio model</th><th>TX power (dBm)</th><th>Receive signal (dBm)</th><th>Planning Remarks</th><th>Projects Remarks Uploaded by</th><th>O & M Remarks Uploaded by</th><th>Planning Remarks Uploaded by</th><th>TXN NOC Remarks Uploaded by</th></tr>";
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
echo "<tr><td>".$row["TND_ID"]."</td><td>".$row["Site_name_S1"]."</td><td>".$row["Site_name_S2"]."</td><td>".$row["Call_sign_S1"]."</td><td>".$row["Idea_ID_S1"]."</td><td>".$row["Call_sign_S2"]."</td><td>".$row["Idea_ID_S2"]."</td><td>".$row["Site_to_integrate"]."</td><td>".$row["True_azimuth_S1"]."</td><td>".$row["True_azimuth_S2"]."</td><td>".$row["Path_length_(km)"]."</td><td>".$row["TR_Antenna_diameter_(m)_S1"]."</td><td>".$row["TR_Antenna_height_(m)_S1"]."</td><td>".$row["TR_Antenna_height_(m)_S2"]."</td><td>".$row["#1_Channel_ID_S1"]."</td><td>".$row["#1_Channel_ID_S2"]."</td><td>".$row["#1_Design_frequency_S1"]."</td><td>".$row["#1_Design_frequency_S2"]."</td><td>".$row["Polarization"]."</td><td>".$row["Radio_model_S1"]."</td><td>".$row["TX_power_(dBm)_S1"]."</td><td>".$row["Receive_signal_(dBm)_S1"]."</td><td>".$row["Planning_Remarks"]."</td><td>".$row["Projects_remarksupdated_user_name"]."</td><td>".$row["O_M_remarksupdated_user_name"]."</td><td>".$row["Planning_remarksupdated_user_name"]."</td><td>".$row["txn_noc_remarksupdated_user_name"]."</td></tr>";
}
echo "</table></div>";
$link->close();
?>
you can use this structure ,this can be used for editing 2 tables and multiple columns table a has columns (aid,a1,a2) table b has columns (bid,b1,b2) i know code looks little rough but just wrote it in 5 min to give you an idea
<?php
//this only executes when button is clicked
if (isset($_POST["submit"] && $_POST["submit"]!=""){
$counta=$_POST["aid"];
//loops through the posts inside here do your query with the set command
//like "update a set a1='$a1',a2='$a2" where aid ='$_POST["aid'][$i]"
for($i=0;$i<$count;$i++){
$a1[$i]=$_POST["a1"][$i];
$a2[$i]=$_POST["a2"][$i];
//your query here
}
$countb=$_POST["bid"];
//loops through the posts inside here do your query with the set command
//like "update b set b1='$b1',b2='$b2" where aid ='$_POST["bid'][$i]"
for($i=0;$i<$count;$i++){
$a1[$i]=$_POST["a1"][$i];
$a2[$i]=$_POST["a2"][$i];
}
//now the part before the button gets clicked
//do your query to select data from database
?>
<html>
<body>
//creating loop inside html
<?php
$a=0;
while($rowa = mysql_fetch_assoc($resulta){
?>
//getting the input data
<input type="checkbox" name="aid[]" value="<?php echo $row["aid"]; ?>>
<label>a1</label>
<input type="text" name="a1[]" value="<?php echo $row["a1"]; ?>>
<label>a2</label>
<input type="text" name="a2[]" value="<?php echo $row["a2"]; ?>>
//ending the loop
<?php
$a++;
}
//b works the same as a
$b=0;
while($rowb = mysql_fetch_assoc($resultb){
?>
<input type="checkbox" name="bid[]" value="<?php echo $row["bid"]; ?>>
<label>b1</label>
<input type="text" name="b1[]" value="<?php echo $row["b1"]; ?>>
<label>b2</label>
<input type="text" name="b2[]" value="<?php echo $row["b2"]; ?>>
<?php
$b++;
}
?>
<input type="submit" name="submit" value="submit">
</body>
</html>
You need use form instead of table while editing and pass the fetched values on input of form and write update query on form submit.
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
}
if(isset($_POST['submit']))
{
$query = "update details set Site_name_S1='$_POST['submit']',Site_name_S2='$_POST['Site_name_S2']',Call_sign_S1='$_POST['Call_sign_S1']',Idea_ID_S1='$_POST['Idea_ID_S1'] where TND_ID=$_POST['TND_ID']";
$res = mysql_query($query);
}
<form method="post">
<input type="text" name="id" value="<?php echo $row['TND_ID'] ;?>" >
<input type="text" name="Site_name_S1" value="<?php echo $row['Site_name_S1'] ;?>" >
<input type="text" name="Site_name_S2" value="<?php echo $row['Site_name_S2'] ;?>" >
<input type="text" name="Call_sign_S1" value="<?php echo $row['Call_sign_S1'] ;?>" >
<input type="text" name="Idea_ID_S1" value="<?php echo $row['Idea_ID_S1'] ;?>" >
<input type="submit" name="submit">
</form>
Just check the quotes while writing update query.
You can use Ajax
Just a fragment of code:
.............
<td><input type="text" row_id=".$some_row_num_from_table."
col-name=".$some_col_name_from_table." disabled class="some-val" value=".$some_from_base."></td>
.............
than little Ajax
$('.some-val').dblclick(function() {
$(this).attr('disabled', false);
});
$('.some-val').blur(function() {
$(this).attr('disabled', true);
var send_data = { 'row_id':$(this).attr('row_id'),
'col-name':$(this).attr('col-name'),
'myval':$(this).val()
};
$.ajax({
url:'your_url.php',
data:send_data,
method: 'post',
success: function(data){...}
});
});
your_url.php
if(isset($_POST['row_id'])){
$sql = "UPDATE mytablename SET `".$_POST['col-name']."` = ".$_POST['myval']." WHERE `row_id` = ".$_POST['row_id'];
$link->query($sql); // it s bad query without protect of sql injection JUST DEMO
}

How to make search form where user has three columns to search.Using PHP AND SQL AND HTML

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

How retrieve specific data from database mysql

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.

Change Textbox from Dropdown List through AJAX, PHP and MYSQL

I have a table which consists of 2 columns, ContactName and Usertype. I have a dropdown list which consists of data from ContactName. When I select any value in the dropdown, its Usertype should be shown according to what was selected. Please help me. I have done this much so far. When I select any value in the dropdown, the same value is shown but I want the user type.
<?php
if(!isset($_SESSION)) {
session_start();
}
$dingo=$_SESSION['dingo'];
$query11="Select ISO3,Notify,Dingoid from rahul_tbl_users where Dingoid=$dingo";
$query123=mysql_query($query11);
$query1234=mysql_fetch_array($query123);
$fetch=mysql_query("SELECT tdd.Dingoid,tc.Dingoid,tc.A_End,tbidd.OpportunityNumber, tbidd.Status,tbidd.Country,tbidd.OpportunityName,tbidd.Allocatedto,tbidd.Email,tbidd.Customer,tbidd.Country,tbidd.ContactName,tc.Usertype,tbidd.G1_OPPID
FROM scott123.rahul_tbl_users tdd inner join scott123.rahul_user_opps tc on
tdd.Dingoid=tc.Dingoid Inner Join scott123.rahul_tbl_opportunities tbidd
on tc.A_End=tbidd.OpportunityNumber
WHERE tc.Dingoid =$dingo");
$fetch_result=mysql_fetch_array($fetch);
?>
<form method="post" action="">
<?php
$SQLString="SELECT distinct(G1_OPPID),ContactName from rahul_tbl_opportunities where G1_OPPID IS NOT NULL and ContactName!='' ";
$result1 = mysql_query($SQLString);
$select_box='<select name="select1" id="select1" onchange="javascript:load_value(this.value);">';
$input="";
while($rows1 = mysql_fetch_array($result1)) {
$select_box .='<option id="user_name" value="'.$rows1["ContactName"].'">'.$rows1['ContactName'].'</option>';
}
$input ='<input type="text" name="test" id="test" value="" />';
echo $select_box."</select>";
echo $input;
?>
<input type="submit" name="submit_name11" value="Add Permission"/>
<input type="submit" name="submit_name12" value="Edit Permission"/>
</form>
What I gather is you just want the textbox to display what is currently selected in the select box?
Change your onchange event in the select box to be:
onchange="transferValue();"
And add this script tag:
<script type="text/javascript">
function transferValue(){
var selectBox = document.getElementById("select1");
var selectedOption = selectBox.options[selectBox.selectedIndex].value;
var textBox = document.getElementById("test");
textBox.value = selectedOption;
}
window.onload = function(){
transferValue();
};
</script>

populate values of a row from the id selected

I'm using PHP to populate names into an option list based on values from a database.
Once a name is selected I want to populate the values of a row based on whatever name has been selected.
I had no problem populating the option list with the name values, but once I select a name the records of that row will not display in the input boxes.
Here is the code I'm working with:
$query = "SELECT name, id
FROM artists
ORDER BY name";
$mysql_stuff = mysql_query($query, $mysql_link);
while($row = mysql_fetch_row($mysql_stuff)) {
$artists_name = htmlspecialchars(stripslashes($row[0]));
$artists_id = stripslashes($row[1]);
// we compare the id of the record returned and the one we have selected
if ($artists_id) {
$selected = $artists_id;
} else {
$selected = "";
}
print("<option value=\"$artists_id\">$artists_name</option>
");
}
print("</select>
<input type=\"Submit\" name=\"submit\" value=\"Update\">
<input type=\"Submit\" name=\"delete\" value=\"Delete\">
<br >
<br />
Edit Biography:
</td>
</tr>
");
if (isset($_POST['submit'])) {
print("<tr valign=\"top\">
<td valign=\"top\" width=\"150\">Name</td>
<td valign=\"top\">Artist Biography</td>
</tr>
");
print("<tr valign=\"top\" bgcolor=\"$colour\">
<td valign=\"top\">
<input type=\"text\" name=\"artists_name[$selected]\" value=\"$artists_name\" size=\"40\" />
</td>
<td valign=\"top\">
<textarea name=\"artists_Biography[$selected]\" cols=\"40\" rows=\"10\">$artists_Biography</textarea>
</td>
</tr>
");
}
print("</table>
</form>
");
Can I please get some assistance with populating the values of the selected name into the input boxes.
So your submitting artist ID to the post. The post would then refresh or change the page. Assuming the action is that page you have the ID in your post. How do you get Artist Name from the ID? Do you run another sql query on the id to find the name? Might need some clarification on the order of your code to help. Thanks
I'm not sure how to interpret this code. Use Ajax. Use Jquery on change() method to take the value of the select and send it via ajax() to a php script that gets the info from the DB and returns what you want. Then use the Success part of the .ajax() method to put that data into you input on the form.
$(function(){
$("select#artist").change(function()
{
var artist = $("select#artist").val();
$.ajax({
type: "POST",
url: "ajax-find-artist.php",
data: "artistID=" + artist,
cache: false,
success: function(html){
var newElems = html;
$("input#artistRestult").html(newElems);
}
});
});
});

Categories