MySQL database populated dropdown box and PHP search - php

I have question regarding search on webpage with textbox and dropdown box.
I have table with fields:
ID
First name
Last name
Company name
Occupation
Description
Now i need to make search form which will be populated from database (field Occupation) and textbox where I can put whatever I want, and then get results from database based on those on web page.
I am really sorry but i am totally begginer and only need some examples of such kind of code and much help :)
Thank you

You're going to want to use AJAX to call a php script from your page and then use the php script to query your database and to echo the results back to the page.
I'm going to use jQuery for this example because it saves a lot of lines, you should check it out if you haven't already.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
function searchOccupation () {
$.ajax({
url: "searchOccupation.php?search=" + $('#searchTxt').attr('value'),
success: function (data) {
alert(data);
}
});
}
</script>
</head>
<body>
<input type="text" id="searchTxt">
<input type="button" value="Search" id="searchBtn" onclick="searchOccupation()">
</body>
Then your php script (whose name should match that in the "url" field of the ajax call (in this case it should be named "searchOccupation.php") will look like this:
<?php
$searchTxt = $_GET['search'];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli('server', 'user', 'password', 'database');
$sql = "SELECT * FROM tableName WHERE occupation = ?";
$stmt = $con->prepare($sql);
$stmt->bind_param('s', $searchTxt);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
echo $row['firstName']; //This sends data back to the page
}
?>
The echo part of the php script is what sends data back into the "success: function (data)" of the javascript, so echo whichever field you want on the page as above.
Edit: Slightly misunderstood what you meant, ajon's above is probably what you need.

Related

filter Query data with from html value input

I have an HTML page with a filter that basically lists car names. When the user selects a value in the filter, I want to show the data associated to that value which comes from my PostgreSQL database. I have attached the code below. At the moment when the user is presented with the page and selects a value from the filter nothing is currently appearing not sure why. Any help welcome thank you
<html>
<select id="filter">
<option>All</option>
<option>BMW</option>
<option>Mercedes</option>
</select>
<?php
$db_connection = pg_connect("host=localhost dbname=postgres user=postgres password=postgres");
$feild_value = $_POST["filter"];
// you can use this $feild_value variable in query;
$result = pg_query($db_connection, "SELECT * from cars where car_name= $feild_value;");
//echo query result here
while($row = pg_fetch_array($result))
echo $result;
die;
?>
<script>
$(document).ready(function()
{
var value = $("#filter").val();
$.ajax({
type:"POST",
data:{"filter":value},
success:function(result){alert(result);}
})
});
</script>
</html>
I'm not sure about your code but your ajax function will not work on the filter change if you didn't call it in on change even, and make sure to put a submit URL to the ajax call and I hope your PHP script is in a separate file if not your script will not run after the die()
$('#filter').on('change',function(e){
//put your ajax submit here
});
There are couples of things with your code that you should be aware of.
Firstly, the die() function will stop the PHP code before the rest of the code is executed and outputted.
Secondly, $result = pg_query($db_connection, "SELECT * from cars where car_name=$feild_value;"); should be
$result = pg_query($db_connection, "SELECT * from cars where car_name='$feild_value;'");
Note the single quote around the $field_value in the SQL statement.

How to Insert an entry to MySQL DB from HTML Form

So, I have a form with some field in my page. For example - auth.php. The data in fields of this form recieved by calling some php function, that gives this data from MySQL DB. The code:
<?php
include 'functions.php';
$result=array();
$result = GetEntries();
$json = json_encode($result);
?>
The data inserting in fields by this code:
<script type="text/javascript">
function nextFunc(){
var name2 = <?php echo $json;?>;
document.getElementById("rname").value = name2[currententry]['Name'];
}
</script>
But how to realize mechanism of insertion some entry to my MySQL DB. For example, user pressed the ADD button on my Form, fill the field "Name" by his own data and press SAVE button - i want to save this user data directly in my MySQL DB.
Please help!
To achieve this, you'll need to follow a few steps:
create the html form
form.html
<form action="submit.php" method="post">
<label>
Name <input type="text" name="name" />
</label>
<input type="submit" value="Save" />
</form>
create submit page
submit.php
<?php
$name = strip_tags($_POST['name']);
// connect to database
$con = new mysqli('localhost', 'db_username', 'db_password', 'db_name');
if ($con->connect_errno) {
printf("Failed to connect to mysql: %s", $con->connect_error);
}
// prepare the query
$sql = sprintf("INSERT INTO my_table SET name = '%s'", $name);
// insert into database
$query = $con->query($sql) or die($con->error);
// view ID of last inserted row in the database
print_r('Last inserted ID: '.$con->insert_id);
Now you should be able to have your data in database.
Please have a look at this example on how to connect to database http://docs.kisphp.net/database-connect/
Instead of mysqli you may/should use PDO.
P.S.
In your code:
include 'functions.php';
$result=array(); // this line should not be here
$result = GetEntries(); // is overwritten by this one
$json = json_encode($result);
Is always a good practice to follow some principles:
function names starts with lowercase
class names starts with uppercase
do not use ?> in php files that contains only PHP code
indentation of all code is not necessary.
and so on.
you may find here more details http://www.php-fig.org/psr/psr-2/
P.P.S.
This is basic usage. Once you understand the principle you can extend it to ajax. Create an ajax function that will submit the form data to submit.php file.

how to get the current added in the table without getting all the data

guys im trying to make a simple commenting system, that when i click the submit the fields will automatically save in the database then fetch it using ajax. but im getting all the data repeatedly instead of getting the recently added data in the database here is the code:
<div id="wrap-body">
<form action="" method="post">
<input type="text" name="username" id="username">
<input type="text" name="msg" id="msg">
<input type="button" id="submit" value="Send">
</form>
<div id="info">
</div>
</div>
<script>
$(document).ready(function (){
$('#submit').click(function (){
var username = $('#username').val();
var msg = $('#msg').val();
if(username != "" && msg != ""){
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:{ 'username' : username , 'msg' : msg},
success: function (data){
var ilan=data[0].counter;
var i = 0;
for(i=0;i<=ilan;i++){
$('#info').append("<p> you are:"+data[i].username+"</p> <p> your message is:"+data[i].mesg);
}
}
});
}
else{
alert("some fields are required");
}
});
});
</script>
PHP:
<?php
$host='localhost';
$username='root';
$password='12345';
$db = 'feeds';
$connect = mysql_connect($host,$username,$password) or die("cant connect");
mysql_select_db($db) or die("cant select the".$db);
$username = $_POST['username'];
$msg = $_POST['msg'];
$insert = "INSERT INTO info(user_name,message) VALUES('$username','$msg')";
if(#!mysql_query($insert)){
die('error insertion'.mysql_error());
}
$get = "SELECT * FROM info ";
$result=mysql_query($get)or die(mysql_error());
$inside_counter = mysql_num_rows($result);
$data=array();
while ($row = mysql_fetch_array($result))
{
$data[] = array(
'username'=>$row['user_name'],
'mesg'=>$row['message'],
'counter'=>$inside_counter
);
}
echo json_encode($data);
?>
SELECT *
FROM "table_name"
ORDER BY "id" desc
LIMIT 1
This is a SQL query to get last record from table. It return last inserted according to id. id should be a auto increment field. I think this will be helpful for you.
Its because you are returning all the row in the table again to the ajax call via
$get = "SELECT * FROM info ";
if you do return all of them again you will have to test if they are not already there before appending them with the jQuery
Perhaps only return the newly inserted row.
or
The jQuery already knows the data it sent to the server, just return success true or false, and then append it if true with the jQuery, no need to return the data back again to the client side
EDIT
I'm not going to write code for you but perhaps these suggestions may help
mysql_query($insert)
link here for reference - http://php.net/manual/en/function.mysql-query.php
will return true of false depending on if the insert statement was successful
you could potentially also check that it acutally inserted a row by calling
mysql_affected_rows()
link here for reference - http://php.net/manual/en/function.mysql-affected-rows.php
then assuming that the insert was successful (i.e. true from mysql_query($insert) or mysql_affected_rows() > 0) simply return successful (i.e. something like
echo json_encode(true);
then on the client side you could do something like the following:
(jQuery Ajax success function only:)
success: function (data){
if (data) {
$('#info').append("<p> you are:"+username +"</p> <p> your message is:"+msg);
}
else
{
alert('There has been an error saving your message');
}
}
using the variables that you just used to send the request
(Please note code samples provided here are only for example, not intended to be used verbatim)
Couple of points though. Is your intention to post the data via ajax only? (i.e. no page refresh) as if that is the case, you will need to return false from you form submit event handler to stop the page full posting. Also you do not appear to have any logic, or are not worried about complete duplicates being entered (i.e. same username, same message) - not sure if you want to worry about this.
I would also potentially look at tracking all the messages via ids (although I don't know your DB structure), perhaps using
mysql_insert_id()
link here FYI - http://php.net/manual/en/function.mysql-insert-id.php
That way each message can have a unique id, may be easier to establish duplicates, even if the username and message are identical
There are numerous ways to deal with this.
Anyway hope that helps
PS - using the mysql_ - group of commands is generally discouraged these days, use the mysqli_ range of function instead

Javascript/PHP interaction only appears on second click

Have searched for the answer but no joy, so here goes...
I'm working on a mobile hybrid app. I want the user to fill in their id number, which is then submitted to a javascript function for basic validation, then kicks in a jQuery.getJSON request to my serverside PHP which returns the data and then my jQuery will repopulate the form div with the data.
Currently it doesn't really work at all in Firefox, and only works correctly in Safari after I press the submit button for a second time. It returns the correct data, so the link is ok.
My problem is: Why does the div not get repopulated after the first click?
HTML:
<div id="login540div">
<form id="login540form" onSubmit="login540()">
Enter Student ID number<input type="text" name="login540id" id="login540id"/>
<input type="submit" value="Submit" />
</form>
</div>
Javascript:
function login540(){
// validates the data entered is an integer.
var loginNo = document.getElementById("login540id").value;
//if(!isNaN(loginNo))
if((parseFloat(loginNo) == parseInt(loginNo)) && !isNaN(loginNo))
{
//jSonCaller(loginNo);
$.getJSON('http://localhost:8888/c05673160/login540.php?q='+loginNo, function(data){
//alert(data);
$('#login540div').html("<p>First Name ="+
data.firstName+
"</p> Last Name ="+data.lastName+" </p>Module No.1 ="+
data.moduleNo1+"</p> Module No.2 ="+
data.moduleNo2+"<p> Course ID="+
data.courseID+"</p>");
})
}
else
{
// alert(loginNo); CHECKED
alert("Please make sure to insert only a whole number");
}
Then the PHP goes like this...
<?php
include ("config.php");
/*
require_once('FirePHPCore/FirePHP.class.php');
ob_start();
$firephp = FirePHP::getInstance(true);
$var = array('i'=>10, 'j'=>20);
$firephp->log($var, 'Iterators');
*/
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'collegeData';
$q=$_GET["q"];
$table = "studentTable";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn)
die('Could not connect: ' . mysql_error());
if (!mysql_select_db($dbname))
die("Can't select database");
$result = mysql_query("SELECT * FROM {$table} WHERE studentID = '".$q."'");
if (!$result)
die("Query to show fields from table failed!" . mysql_error());
$json = array();
while($row = mysql_fetch_array ($result))
{
$json = array(
'firstName' => $row['firstName'],
'lastName' => $row['lastName'],
'moduleNo1' => $row['moduleNo1'],
'moduleNo2' => $row['moduleNo2'],
'courseID' => $row['courseID']
);
}
$jsonstring = json_encode($json);
echo $jsonstring;
mysql_close($conn);
?>
I can't figure out what's wrong, and I've been messing around with various things for the last few days trying to fix it, but no joy, so I'd really appreciate any help you can give.
#Robbie had a good point that you don't appear to be stopping the default behavior of the form submission. To do this you need to change a couple things:
onSubmit="login540()" needs to change to onSubmit="return login540()" otherwise whatever you return from the login540() function will be ignored.
At the end of the login540() function you need to return false; to stop the form from submitting normally. You can also pass in the event object as the first argument and use event.preventDefault() instead: function login540(event){event.preventDefault();...}.
To do yourself a favor however, you can use jQuery to bind the submit event handler to the form rather than using inline JS (tisk, tisk, :) )
$('#login540form').on('submit', login540);
This way you can keep all of your JS in one place rather than spread-out all over your HTML.
The bottom of Function login540() is missing, but this needs to kill the default "submit" action: this can be done with "return false;" at the end. As I can't see the end, not sure if this happens or not, but the form probably "submits" while the AJAX is running.
This is compounded as the form doesn't have an action, which probably explains the different browser behaviour. I suggest setting action to "#" and then, if you see "#" added in the URL then the form has submitted and not been stopped by your function.

Dependant menus in php using java script method?

I am work on HTML and PHP on my project , but I have a problem :
I have a drop down list with countries and I want a nother drop down list to appear with (cities of this country) when user choose a country
I have the countries data base and cities data base ( sql )
I try to use a java script method to do that but it didnt work
this is my code
First : this is the countries drop down list it is work good :
<select name="SelectCountry" id="SelectCountry" onchange="showCity()" >
<?php
$Con= mysql_connect("localhost","root","");
if(!$Con) { die('Could not connect'.mysql_error());}
if(!mysql_selectdb("MyDB",$Con)){die(mysql_error());}
$sql = "SELECT * FROM countries";
$result = mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo ("<option value=\"".$row['CountryID']."\">".$row['Name']."</option>");
}
mysql_close($Con);
Second , this is the java script function showCity() // didnt work any way !!
<script>
function showCity()
{
alert("in the function !!");
Document.write(" <?php echo "<select 'SelectCity' ,'SelectCity'";
echo "</select>";
$theCountry=$_GET['SelectCountry']; // get the country ID
$Con= mysql_connect("localhost","root","");
if(!$Con) { die('Could not connect'.mysql_error());}
if(!mysql_selectdb("MyDB",$Con)){die(mysql_error());}
$sql = "SELECT * FROM cities WHERE cities.Fips=(SELECT Fips FROM countries WHERE CountryID='$theCountry')"; // retrive the cities for the spicific country (work when I enter the ID manully in the sql query e.g CountryID='43')
$result = mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo ("<option value=\"".$row['Fips']."\">".$row['Fullname']."</option>"); // print all the cities in a menu (work when I enter the ID manully in the sql query e.g CountryID='43')
}
mysql_close($Con);
");"; ?> ");
}
</script>
this method is to create a new dropdown list for the spicific country cities when the user change the country by using Onchange Event
I hope you will help me
if there any Questions or misanderstod I am ready to answer or explain
thaaaanks all :)
For your level of experience it would probably be best if all you do by onchange is to submit the form:
<select name="SelectCountry" id="SelectCountry" onchange="this.form.submit();" >
This is equivalent to pressing the submit button after selecting a country. (You are missing </select> in your excerpt by the way, although I expect you just didn't copy that here.)
Then in PHP have something like... (note this code bit needs to be before the dropdown boxes so that the variable is there when you want to echo it)
if ( isset($_GET['SelectCountry']) )
{
$country = $_GET['SelectCountry'];
$citySelect = "<select name='SelectCity'>";
//query DB for cities of that country
...
//now add the options from the query just like you did for the countries, except now use the cities
...
$citySelect .= "</select>";
}
else
{
$citySelect = ""; //to make sure the variable isn't undefined
}
Now you can just add underneath your CountrySelect:
<? echo $citySelect; ?>
If a country was chosen before, the city menu will show.
Note that this does not include even the lowest level of security, fool proofing and it can be very complicated to get a large form to work like this.
$_GET['SelectCountry'] only works when you have the selects in a form tag and you click the submit button to reload the page (which creates the $_GET variable. A simple way to do this would be to add the country to your address URL and that will give you a $_GET too.
So inside the showCity() function, write this:
var i = document.getElementById("SelectCountry").selectedIndex;
var countryValue = document.getElementById("SelectCountry").options[i].text;
window.location.href = '/?SelectCountry='+countryValue;
This will redirect your web page to mysite.com/?SelectCountry=USA or something like that. Then your code will work. This isn't the best way to do it, but it should give you some results.
This doesn't work because $_GET['SelectCountry'] is always going to be null. You're confused about the difference between client side and server side scripting. Once you load the page for the first time, there is no GET variable yet, and so your Javascript is sitting on the browser with no cities. Changing the country doesn't make the getCity() go back to the server. It just looks at what it has already, which is nothing. You need an AJAX function, which has the job of sending GET requests to the server and bringing back the results. Once it gets the list of cities, its going to want to know what you want it to do with that list. You give it a function that makes a dropdown out of them. This is known as a callback. There are a lot of tutorials out there telling you how to make an AJAX function and where to put the callback.

Categories