Inserting SQL data into HTML textarea - php

I've been reading lots of questions at stackoverflow that have made my life easier, first time I ask something though.
Here is my problem. I need to be able to insert different values from my SQL database into a selected < textarea > field, depending on what option is selected in a < select > input on the same form.
The basic idea is that I want to edit news from the database, edit title and body. To do that, I want to show what (title / body) data contains my db to the user, by getting them from my SQL db. User may have multiple entries in the database, so when I select one entry at the < select > combobox, I'd like to change the contents to those from the selected entry from the db.
Its a simple idea difficult to express due to my poor English...
HTML form would be more or less as follows:
<form action="edit.php" method="post">
<select name="id">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<textarea name="newsBody"></textarea>
<input name="submit" type="submit" value="Edit" />
</form>
SQL database structure goes more or less as follows:
DB name: database
DB table: news (fields id, body, title, author, timestamp)
I'd like to be able to select news from my < select > getting their 'id' / 'option value', then get from the DB the corrrect value, and show it in the corresponding < textarea >.
I'm new into website coding, and do it just as a hobby, so my knowledge in PHP, MySQL is very basic. I dont provide any PHP code or options, simply because I have no idea how to resolve it... I can understand sql, php syntax though.
I thought using < select > event 'onchange' and javascript, but couldn't make it work... Neither could I using jQuery / ajax, probably because the lack of useful examples!!
Hope that someone understands and can provide a solution!
Many thanks in advance!

You can use Ajax.
Create the following .html page:
<html>
<head>
<script>
function showData(str)
{
if (str=="")
{
document.getElementById("ajax-content").innerHTML="";
return;
}
// Code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// Code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ajax-content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","showData.php?id="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="news" onchange="showData(this.value)">
<option value="">Select ID:</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
<div id="ajax-content"></div>
</body>
</html>
And the following .php script (showData.php in my example):
<?php
// Receive variable from URI
$id=$_GET["id"];
// Connect to your database
$con = mysql_connect('localhost', 'user1591005', 'stackOverflow');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Select your database
mysql_select_db("myDatabase", $con);
// Select all fields from your table
$sql="SELECT * FROM news WHERE id = '".$id."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo "<input type='text' value='" . $row['title'] . "'>";
echo "<textarea>" . $row['content'] . "</textarea>";
}
// Close the connection
mysql_close($con);
?>

Alright Ill give you a quick idea before my lunch... :)
Setup an AJAX request to pass the selected dropdown box value to a PHP script.
In this PHP script, fetch the data for the selected value from your database.
Return the data and set the textbox's value to that.
Sending an AJAX Request

It seems that you need to use AJAX and Mysql+PHP for this. The first thing is to collect data from the table.
for example $result = mysql_query('SELECT * FROM new_table WHERE author = author's id')
The second thing is to output the html code with the results from the table you could use
you can do this by using foreach() loop. Then you need to use ajax (from the jQuery framework) and to pull data from the database again on user selection.
Hope this helps

To get the data from the database, you'll have to use a server-side language, such as PHP. To react to the change in the <select> element, you'll have to use JavaScript. AJAX is what will bridge the gap between the two languages.
Firstly write some JavaScript to make the query. If you're using jQuery, this is very straightforward.
<script>
var selector = $("#mySelectorID"); // first select the <select> elm
selector.change(function(e) { // attach a function to it's change event
jQuery.get("getContents.php", // when it changes, make an AJAX call
{id:selector.val()}, // passing the value of the <select> as data
function(returnVal) { // after a successful AJAX ...
$("#myTextAreaID").val(returnVal); // ... set the textarea to the correct value
});
});
</script>
Then create a new php file (slightly simplified, but this would work):
<?php
$id = $_GET['id']; // get the id that was passed through the URL
$connection = mysql_connect("hostname","username","password"); // connect to db
mysql_select_db("database", $connection ); // select the db
$result = mysql_query("SELECT * FROM news WHERE ID = $id"); // make SQL query
if ($row = mysql_fetch_array($result)) { // fetch the first row
echo $row['body']; // output the contents of the row
}
connection mysql_close($connection ); // close the connection
?>
More info on AJAX with jQuery: http://api.jquery.com/jQuery.get/

I am imagining you want to work on a simple html/PHP solution before branching out to Ajax ...
<?php
$title = "" ; // set the variables
$body = "" ;
$action = "" ;
$submit = "Edit";
if(isset($_POST['id']) && (int) $_POST['id'] > 0 ){
// a positive integer was sent to your form
// so now construct your sql statement: ie
// "select title, body from new where id= " . $_POST['id'] ;
// assign your rows to your variables
// $title = $row['title'] ;
// $body = $row['body'] ;
// now re-use your empty form to display the variables
// re-assign the form variables
// $action = "save.php" ;
// $submit = "Save changes";
}
?>
// have the form submit to itself by default
<form action="<?php echo $action; ?>" method="post">
<select name="id">
<option value="1" <?php if($_POST['id'] == 1 ) echo "selected=selected; ?>>Option 1</option>
<option value="2" <?php if($_POST['id'] == 1 ) echo "selected=selected; ?>>Option 2</option>
</select>
// have your html form values the same name as your db table columns
<input type="text" name="title" value="<?php echo $title; ?>"/>
<textarea name="body"><?php echo $body; ?></textarea>
<input name="submit" type="submit" value="<?php echo $submit; ?>" />
</form>
save.php then stores the new values in your database and perhaps redirects back to this page...
I am really paring this down, you'd likely generate your ids from a select from the database, and they'd probably be id, title in alphabetical order:
A big story
Big story
etc
There is lots else to take into consideration, but this is one way to go about it.

If you are using php with SQL to retrieve data from a database you can insert the database field using the following code.
echo '<textarea name="MyText" id="MyText" rows="8" cols="80" >' . $MySelectedText . '</textarea></p>';
Where MySelectedText is the data base field name of your SQL text you have selected from the database.

Related

Integrating href with $_GET value into a select option

I am trying to get some data of a certain item selected in a select option and automatically display it on the textfield as shown in this image:
But it is not working. Is there a remedy for this or such type of coding is not workable at all? Hopefully someone can help me on this.
Here is the code I made:
$credit_accounts = $db->query("SELECT * FROM credits");
echo'<select id="customer_order_id" name = "customer_order_id">
<option value = "">SELECT ACCOUNT</option>';
foreach($credit_accounts as $key){
$id = $key['purchase_order_id'];
$name = $key['customer_firstName']."\t\t".$key['customer_lastName'];
echo'<option value = "'.$id.'">'.$name.'</option>';
}
echo'
</select>';
Note: The link will execute a query that will retrieve certain data of the selected item. If link is declared outside the loop without the <option></option> tag, it works accordingly. But if it is place within the loop of course with the <option></option> tag, it is not working like a link at all. Please help me out.
Sorry for my english , I will write some long answer hopefully it will also help others,so i am giving solution for doing following.
Please not : this solution is written and use SIMPLE MYSQL,AJAX and PHP function If you further want DATA SECURITY refer [PHP MySQLI Prevent SQL Injection
Objective : To get/display DATA from DATABASE related to a particular(ly 1) user/product and then fetch/display it in HTML page (additionally: without page refresh ) IN A FORM.
CODE :
<?php
//php-database connection script
$db_config = mysqli_connect("localhost", "username", "pass", "database_name");
// Evaluate the connection
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
}
?>
<?php
//this pHP SCRIP FIRES when you select a USERNAME (if u want not to SELECT but type then change ONCHANGE to ONKEYUP function & change username input type to text)
if(isset($_POST['uname'])){
$u = $_POST['uname'];
$sql = "SELECT email , gender FROM credits WHERE username='$u' LIMIT 1";
$query= mysqli_query($db_config,$sql);
while($row2 = mysqli_fetch_array($query)){
//Here we form a STRING SEPRATED BY QUAMMAS and ECHO IT TO PAGE
//later on we will fill this data in input fields
echo $row2['email'].",".$row2['gender'];
exit();
}exit();}
?>
<!-- HERE is your form where user will select or type his username-->
<form >
Select username :<br/>
<select id="user_name" onchange="load_data()">
<option value=""> select an ouser</option>
<option value="v1111"> v111</option>
</select><br/>
Email<br/>
<input type ="text" id="email" value=""><br/>
Gender :
<select id="gender">
<option value='m'>male</option>
<option value='f'>female</option>
</select>
</form>
<span id='status' ></span>
<script>
//AJAX OBJECT CREATION script it works as get or post mechanism
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState === 4 && x.status === 200){
return true;
}
}
//here is function which fires when username is selected
function load_data(){
var value = document.getElementById('user_name').value;
//declare ajax obj, and name(url) of same page you are coding.
var ajax = ajaxObj("POST", "url.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var str = ajax.responseText;
//split STRING and extract individual data
var res = str.split(',');
//here we fetch his username into input field BINGO!do same for gender.
_('email').value = res[0];
//res[1] will have gender related data.
}
}
//Declaration to send URL encoded variable (username in this case)
ajax.send("uname="+value);
}
</script>
If you want further resources and info about data security see BRAD's comments in comments section

How to get in a variable the value of the selection of a Select/Drop Down Menu PHP or HTML

I'm trying to connect 2 drop-downs so in the first I show a list of countries and based on the selection of the country I show a list of the cities for the country selected.
I have my index.php file which load all the countries correctly as seen in this image:
Code to load my countries
<select name="country" id="country">
<?php
$db = pg_connect("$db_host $db_name $db_username $db_password");
$query = "SELECT country FROM countries";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
printf ("<option value=Select>Select a Country</option>");
while($myrow = pg_fetch_assoc($result)) {
printf ("<option value=$myrow[country]>$myrow[country]</option>");
}
?>
</select>
Now I'm trying to do the same based on the selection from the previous "Select" but it is not working. The issue I'm having is getting the value selected in the country select because if I hard-type a value of a country like: $query = "SELECT city FROM cities where country = Albania"; then it works. Also I tried to print the value of the country selected: (echo $selectedCountry;) and it not printing anything so I'm guessing neither $selectedCountry = $_GET['country']; or $selectedCountry = $_POST['country']; are getting the value of the country selected.
<select name="city" id="city">
<?php
$db = pg_connect("$db_host $db_name $db_username $db_password");
$selectedCountry = $_GET['country'];
$selectedCountry = $_POST['country'];
echo $selectedCountry;
$query = "SELECT city FROM cities where country = ' $selectedCountry '";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
printf ("<option value=Select>Select a City</option>");
while($myrow = pg_fetch_assoc($result)) {
printf ("<option value=$myrow[city]>$myrow[city]</option>");
}
?>
</select>
Thank you very much in advance
UPDATE
This is what I see in the first Load. Where the country Select is loaded with all the values as per the image above and the city Select is empty (Only the "Select a city" value) waiting to be loaded with the values depending on the country selection.
LAST UPDATE - From Borna Suggestion
Borna,
I've tried your suggestion, below the exact code that I'm using. Using two countries as example. However, the cities are empty the first load and when I select a country nothing loads in the city Select and I get the following screen. It seams that it is actually not calling/running the getCities.php:
Index.html
<!DOCTYPE html>
<html>
<head>
<script>
function populateCities(citiesSelectBoxOptions){
document.getElementById("city").innerHTML = citiesSelectBoxOptions;
}
function httpGetAsync(theUrl, callback)
{
alert(theUrl);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
</script>
</head>
<body>
<select name="country" id="country" onchange="httpGetAsync('http://localhost/FillCity/getCities?country=' + this.value, populateCities)">
<option value="Angola">Angola</option>
<option value="Spain">Spain</option>
</select>
<select name="city" id="city">
</select>
</body>
</html>
getCities.php
<?php
include("config.php");
$db = pg_connect("$db_host $db_name $db_username $db_password");
$selectedCountry = $_GET['country'];
echo "country: " .$country;
$query = "SELECT city FROM cities where country = ' $selectedCountry '";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
printf ("<option value='Select'>Select a City</option>");
while($myrow = pg_fetch_assoc($result)) {
printf ("<option value='$myrow[city]'>$myrow[city]</option>");
}
?>
UPDATE
If I run http://localhost/FillCity/getCities?country=Spain this is what I get
If I run just http://localhost/FillCity/getCities.php I get: (I'm getting the word country because I place and echo $country in the code to see the country selected)
This is my FillCity folder under my localhost (var/www/html)
And here is what I see when running the Index.html for the first time with Angola as default country.
If I select any country, Spain, as example this is what I get
LAST UPDATE
When I open the .html file and I select a country this is what I get (Still printing out that message on the screen):
Once I click Ok then it works and I can see all the cities for the country (But of course I would like not to have that message popping up)
Thanks again
Well, what you really need is AJAX call which allows you to communicate with server without reloading a page. All you have to do is basically send a new HTTP request with a country parameter to get the list of cities in it. The correct way would be to send (HTTP response) only the data(cities) in JSON or similar format, and not its presentation also (html), but for simplicity, you can continue to work like you started (return data with html).
Start by separating the code that generates HTML selectBoxOptions of cities in another script.
You will use that script to get the list of cities in particular country by using AJAX (XMLHttpRequest library).
Have a look at this, it's a working solution of your problem. HTTP request is sent whenever user changes the countrySelectBox option, that way your cities select box gets updated every time it needs.
All you have to do is change the url in the onchange attribute that points to your script (I previously said that you should move 2nd block of code into separate script).
<!DOCTYPE html>
<html>
<head>
<script>
function populateCities(citiesSelectBoxOptions){
document.getElementById("city").innerHTML = citiesSelectBoxOptions;
}
function httpGetAsync(theUrl, callback)
{
alert(theUrl);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
</script>
</head>
<body>
<select name="country" id="country" onchange="httpGetAsync('www.yourdomain.com/getCities.php?country=' + this.options[this.selectedIndex].value, populateCities)">
<option value="Country1">Country 1</option>
<option value="Country2">Country 2</option>
</select>
<select name="city" id="city">
</select>
</body>
</html>
getCities.php
<?php
$db = pg_connect("$db_host $db_name $db_username $db_password");
$selectedCountry = $_GET['country'];
$query = "SELECT city FROM cities where country = ' $selectedCountry '";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
printf ("<option value='Select'>Select a City</option>");
while($myrow = pg_fetch_assoc($result)) {
printf ("<option value='$myrow[city]'>$myrow[city]</option>");
}
?>
EDIT:
httpGetAsync is native (only pure/vanilla javascript is used. No other libraries are used) javascript function that enables you to send HTTP request without reloading a page. I see you are using jQuery, which hides this function's complexity, same as form->submit, but I recommend you to learn how httpGetAsync works, because using a jQuery for such a simple task is overkill.
You don't need this javascript function
function getCity(countryId)
Instead, you should put your code that communicates with database in a .php file, not in javascript (remember, javascript is a client side, it executes on client machine, e.g. browser, while php executes on server). Your SQL should never be written in javascript. Client side code cannot communicate with a database directly, only through server side coding. To accomplish that, you must return a value of PHP script getCities.php back to the client(javascript) as a HTTP response.
When you send a HTTP request to some .php file, that scripts executes on a server, and everything that you said "echo" or "print", on the end of script, is automaticaly sent as HTTP response. You don't actualy have to write any code to send a HTTP response. Its done automaticaly. You just have to echo/print whatever you need on the client side. In your case, you need to print options for particular country.
How the script knows for which country it needs to select cities from database?
Well, you send HTTP request with a parameter "country". That is what you Form is doing automaticaly when you submit it. All HTML tags that are inside Form, and have a name attribute set, are gonna be send in HTTP request as parameters. But, since you cannot use submit, you must do this manualy.
To send a parameter inside HTTP GET request is very simple.
Have a look at the following url:
localhost/getCities?country=countryX&someOtherParam=something&myThirdParam=something3
On server side, the following variables are gonna be populated:
$_GET["country"] // value is 'countryX'
$_GET["someOtherParam"] // value is 'something'
$_GET["myThirdParam"] // value is 'something3'
To learn more about how GET and POST works, and what is the difference, check this
Get started by creating a getCities.php file, and copy paste the code that communicates with database and generates city options. It's basically what you already did, you just have to put that code in separate .php file. So, when a client (browser) asks for a list of cities in particular country, you are going to send a HTTP request (using httpGetAsync() function) to get that list from the server.
In your index.php copy paste this script
<script>
function populateCities(citiesSelectBoxOptions){
document.getElementById("city").innerHTML = citiesSelectBoxOptions;
}
function httpGetAsync(theUrl, callback)
{
alert(theUrl);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
</script>
Next, put onchange attribute on select box, remember, its all lower case, not onChange.
<select name="country" id="country" onchange="httpGetAsync('localhost/getCities?country=' + this.value, populateCities)">
For any question just ask... :)
Well, I suppose one way to do it would be with jQuery.
There's probably a few different ways to do this, but what you could do, is load all the cities into the city drop-down, regardless of country, but change the printf for the city options like this.
$query = "SELECT city, country FROM cities";
....
while($myrow = pg_fetch_assoc($result)) {
printf ("<option class="$myrow[country] city_select" value=$myrow[city]>$myrow[city]</option>");
}
And then in the javascript for the page, have something like
$('#country').bind('change', function(){
var country = $(this).val();
$('#city option.city_select').hide();
$('#city option.'+country+'').show();
});
It's not necessarily the most elegant solution, though.
You are missing the quotes inside your option, it should be something like
<option value=$myrow['city']>$myrow['city']</option>
try that

Using the result of a select clause for a where clause to MySQL

I have a MySQL database containing 12 columns. I created a dropdown from it using distinct values of the column named 'activity' and the column named 'logdate' which is a datetime.
Like this..
<form action="define_activity" id="activityform" method="post"> <!-- Form to select an activity -->
<select name="activities" id="select1"> <!-- List of activities -->
<option value="" selected="">Select One</option>
<option value="NewActivity" id="newactivity" onclick="newactivity();">New Activity</option>
<?php
foreach($db_found->query("SELECT DISTINCT activity, logdate FROM NetLog ORDER BY activity") as $act) {
echo ("<option value='$act[activity]'>$act[activity] of $act[logdate]</option>");
}
?>
</select>
<input type="submit" name = "Submit" />
</form>
This all works great. what I want to do is use the results of the selected option to do another query against the same database that pulls all of the records associated with the selected activity and logdate values. I know how to write the query but I don't know how to find and then use the selected values.
Can someone please show me how to get the selected value from the
Thanks in advance for your consideration.
I make some changes in your code, I didn't test it, but I think that's going to help you:
<?php
//Returns an associative array with the query result:
function select($yourSQLQuery){
//Array with result:
$result = array();
//Database conection
$db = new PDO($dsn,$username,$password);
$stmt = $db->query($yourSQLQuery);
//This going to save an array with your data:
$result = $stmt->fetchAll(PDO::FETCH_NUM);
$db = null;
return $result;
}
//*********************************************************************************************
//Do here your query:
$result = select("SELECT DISTINCT activity, logdate FROM NetLog ORDER BY activity");
//*********************************************************************************************
//Form handler:
if($_SERVER[REQUEST_METHOD] == "POST"){
//If the form was submited:
//Get selected activity
if ( isset($_POST['activities']) ) {
/*Instead of sending your activity you can send the number of the submitted record in $records, then extract activity and logdate and make your query:*/
$rowNumber = $_POST['activities'];
//Get your log date:
$act = $result[$rowNumber]; //if doesn't work try '$rowNumber'
$activity = $act['activity'];
$logdate = $act['logdate'];
//Pull records asocciated with submitted activity:
$sql = "SELECT * FROM putHereYourTable WHERE activity = '$activity' AND logdate='$logdate'";
$records = select($sql);
//Pulled activities are now in $records
//do something with the records that you want. e.g.:
print_r($records);
}
}
?>
<!-- Your HTML: -->
<form action="define_activity" id="activityform" method="post"> <!-- Form to select an activity -->
<select name="activities" id="select1"> <!-- List of activities -->
<option value="" selected="">Select One</option>
<option value="NewActivity" id="newactivity" onclick="newactivity();">New Activity</option>
<?php
foreach($result as $key => $act) {
//Send the number of register instead of $act[activity]:
echo ("<option value='$key'>$act[activity] of $act[logdate]</option>");
}
?>
</select>
<input type="submit" name = "Submit" />
</form>
You need to submit the form first.
<form action="define_activity" id="activityform" method="post">
You need to submit to a valid page in your action param. So if 'define_activity' is not a valid URL (ie: not handled by htaccess) then you need to either A) use the same script/file your using or B) create another page to handle the data.
I would do this:
<form action="process.php" id="activityform" method="post">
process.php
<?php
if ( isset($_POST['activities']) ) {
// do something with the submitted data
$selectedValue = $_POST['activities'];
}
Now you have the selected value. You have also any other value that is submitted in the form, $_POST['othervalue'].
For a clear view of what is sent, dump it.
die('<pre>' . print_r($_POST, true) . '</pre>');
or you could use var_dump: die( var_dump($_POST) );
Keith,
You have to remember that web applications work in a client server environment over the HTTP protocol.
After your page is done loading the first time, the php script is basically done executing. In order for more code to run, another request needs to be sent to the server. This happens when you either:
a) submit a form or click a link that sends a new http request to the page
b) make some javascript send a new HTTP request to the page.
Since you're just getting started, lets assume you just want that form to send the new request off to the page.
So at the top of your php script, just add this statement:
print_r($_REQUEST);
As you visit the page that is running the script both with and without clicking the submit post button, you will be able to see the various request parameters show up based on your form post. One of those params will be 'activity' .. just throw an if statement checking to see if that parameter is present, then run your query inside that if statement, using the value of 'activity'
if(isset($_REQUEST['activities'])) {
//do your query here..
}

Form Inside Div, Show Result In a Different Div

I have a div statement with two nested divs inside. The first nested div is a form that contains a drop down menu that allows the person to select a basic school subject:
<form id="request" action="<?php echo $_SERVER['PHP_SELF']?> method="post">
<div id='d2'>
<p id='p2'>Subject:
<select id="s" name="subject">
<option value="English">English</option>
<option value="Social Studies">Social Studies</option>
<option value="Math">Math</option>
<option value="Science">Science</option>
</select>
</p>
<input type="button" value="Find"/>
</div>
</form>
The second nested div will print out, using PHP, a previously initialized array of tutors that can help the student user, along with a link allowing the person to choose a specific tutor. Please forgive me for the less-than-stellar formatting, I'm still a beginner:
<div id='div3'>
for ($i=0; $i<count($tutors); $i++)
{
echo "<div>'".$tutors[$i]."'</div><br/>"
. 'Choose me' . "<br/>";
}
</div>
The array is initialized at the very beginning of the php class by connecting to MySQL and then pulling out tutors from the database that are tutor users and tutor in the subject the student user has selected. Again, please forgive me for any bugs, I'm still learning:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST')
{
$sub = $_POST['subject'];
$con = mysqli_connect("127.0.0.1", "root", "//removed", "mydb");
$msg = "";
if (mysqli_connect_errno())
{
$msg = "Failed to connect to MySQL: " . mysqli_connect_error();
echo $msg;
}
$query = mysqli_query($con, "SELECT * FROM User WHERE Role = tutor AND Subject ='".$sub."'");
$tutors = array();
while ($row = mysqli_fetch_assoc($query))
{
$tutors[] = $row["Username"];
}
}
else
{
echo "Failed form.";
}
?>
The problem pressing me the most right now is that failed form is always shown on the screen. I suspect this is because the form has been nested inside a div. Is there any way around this? Or is it a different problem(s)?
I'm also wondering if the code will indeed show what I want in the second nested div, or if there are bugs in that too (I'll style it later).
I am basing my solution. on the following assumption. According too these lines from your post. The second nested div will print out, using PHP, a previously initialized array of tutors that can help the student user, along with a link allowing the person to choose a specific tutor. Please forgive me for the less-than-stellar formatting, I'm still a beginner:>>>>>> those line were from your post.
Please read the comment in the code carefull. There i explain what i change and suggestions.
This the code
<!--
<form id="request" action="<?php //echo $_SERVER['PHP_SELF']?> method="post">-->
/*
* The line above is wrong and as you may understand by the comments of other user,
you dont need to give anything in the action as you are posting it on the same
* page. so you can delete it. and add this line below one.
*/
<form action="" method="post">
<div id='d2'>
<p id='p2'>Subject:
<select id="s" name="subject">
<option value="English">English</option>
<option value="Social Studies">Social Studies</option>
<option value="Math">Math</option>
<option value="Science">Science</option>
</select>
</p>
<!--<input type="button" value="Find"/>--->
<input type="submit" value="Find"/>
</div>
</form>
<div id='div3'>
<?php
//I am leaving these php tag for the reference only that you used it in your original code.
//You dont need those lines
?>
</div>
<?php
if ($_SERVER['REQUEST_METHOD']=='POST')
{
$sub = $_POST['subject'];
//$con = mysqli_connect("127.0.0.1", "root", "//removed", "mydb");
$con = mysqli_connect("127.0.0.1", "root", "", "mydb");
$msg = "";
if (mysqli_connect_errno())
{
$msg = "Failed to connect to MySQL: " . mysqli_connect_error();
echo $msg;
}
$query = mysqli_query($con, "SELECT * FROM User WHERE Role = 'tutor' AND Subject ='".$sub."'")or die(mysqli_error($con));
// $tutors = array(); You dont need that line either.
while ($row = mysqli_fetch_assoc($query))
{
$tutors = $row["username"];
echo "<div>'".$tutors."'</div><br/>"
. 'Choose me' . "<br/>";
/*
* **Here is the suggestion**. The link you are giving to
* the user is always going to be SelectedTutor.php.
* I dont think this what you want. you may want to
* show tutor profile or wanna do some thing else when
* somebody click on the link. Lets say you want show
* the tutor profile. Than you have to run another query.
* and should be able to generate link accordingly.
* I am giving you hint how you can do it in case you want to do it.
*/
/*
* you should change that line to this line link one to this
* echo "<div>'".$tutors."'</div><br/>"
* . 'Choose me' . "<br/>";
* If you notcie i added this parth after SelectedTutor.php, this one ?tutor='.$tutors.'
* Than your url will be different when ever user click on the link.
* Hope i did not confused you
*/
}
}
else
{
echo "Failed form.";
}
?>
And you ask why you are getting message of Failed form. In short why your else statement is running. to understand see the expanation below.
if ($_SERVER['REQUEST_METHOD']=='POST')
{
//I removed the code just left the basic shell so you can understand
}
else
{
echo "Failed form.";
}
If you read the above code you will understand why you are getting Failed form message each time when you run the code. You will not get this message when you click on submit.
Reason: Reason is this, in those lines your saying that if Request method is post, than run this bit of code. and Else echo this message out. means whenever your request method is not post run this else statement.
but the thing is that you only sending post request after clicking on the button. before that, there is no post request. so thats why you are getting this message each time you run your script and than it disappear when you click on submit. cause you send the post request.
English is not the first language if i confused you let me know i will explain it again.
Although you have asked for help with PHP/HTML, this is really a job for jQuery/AJAX. Don't worry, though -- it's much simpler than you might think.
The advantage to using AJAX is that you stay on the same page, and the page does not refresh -- but the dropdown selection is sent to a PHP file (that you specify), the MySQL database is consulted, and a response (in HTML) is returned.
Inside the AJAX success function, (did you hear that? Inside the success function!) you receive the HTML returned by the other PHP file and you then plunk the returned HTML into an existing DIV.
Here are some simple examples:
AJAX request callback using jQuery
(1) You would not need to put DIV d2 into <form> tags. Not necessary with AJAX
(2) Your jQuery code would look like this:
<script type="text/javascript">
$('#s').change(function(){
var sub = $(this).val();
$.ajax({
type: 'post',
url: 'my_php_file.php',
data: 'subj=' +sub,
success: function(resp){
$('#div3').html(resp);
}
});
});
</script>
The above script can be placed anywhere in the document, or in the head tags, or included in a separate document.
(3) You must reference the jQuery library, as per the first example in the "AJAX request callback..." link.
(4) There will be no need for the Find button, because the code will fire as soon as the dropdown value is changed. It takes microseconds to communicate with the server and stick the list of tutors in the div3 div.
(5) The div3 div must already exist on the page (but it can be empty).
(6) The PHP file (called my_php_file.php in the code above) would be exactly as you wrote, except that it would create an output variable containing the HTML to be plunked into the div3 div. For example:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST'){
$sub = $_POST['subj'];
$con = mysqli_connect("127.0.0.1", "root", "//removed", "mydb");
$msg = "";
if (mysqli_connect_errno()){
$msg = "Failed to connect to MySQL: " . mysqli_connect_error();
echo $msg;
}
$query = mysqli_query($con, "SELECT * FROM User WHERE Role = tutor AND Subject ='".$sub."'");
$tutors = array();
while ($row = mysqli_fetch_assoc($query)) {
$tutors[] = $row["Username"];
}
$out = '';
for ($i=0; $i<count($tutors); $i++) {
$out .= '<div>' .$tutors[$i]. '</div><br/>
Choose me<br/>
';
}
}else{
$out = "Failed form.";
}
echo $out;
?>
All above code is untested, but could work...

How to populate dependant select menus dynamically using jQuery, PHP and MySQL?

I have searched quite a bit on here about this topic. But I could not find a solution for my problem. I'd appreciate it a lot if you could help me, this is for a school project I am working on.
I have a database with a table ("Main_table") and columns including "sector" and "sub_sector". I want to have two select boxes, first one will load all the records from database in "sector" column and the second one will load all the records from database in "sub_sector" column depending on the selection value of the first select box. (For example: If I select "plastics" on the first select box, then second select box should be updated with sub_sector values where sector value is equal to "plastics").
I have managed to load the options values from database for the first select box but when I click on any selection, it does not load any option to the second select box. You can find the codes below. I did not put "sector_options.php" below, as it seems to work just fine.
index.html shown below:
<script>
$(document).ready(function() {
$('#filter_sector')
.load('/php/sector_options.php'); //This part works fine - uploads options to the first select box
$('#filter_sector').change(function() {
$('#filter_subsector').load('/php/subsector_options.php?filter_sector=' + $("#filter_sector").val()
} //This part does not work - no options on the second select box
);
});
</script>
<body>
<div id="sectors"><p>Sector:</p>
<select id="filter_sector" name="select_sector" multiple="multiple" size="5"> </select>
</div>
<div id="subsectors"><p>Sub Sector:</p>
<select id="filter_subsector" name="select_subsector" multiple="multiple" size="5"> <option value="" data-filter-type="" selected="selected">
-- Make a choice --</option>
</select>
</div>
</body>
</html>
sector_options.php shown below:
<?php
$link = mysqli_connect("*******", "*******","******","********") or die (mysql_error());
$query = "SELECT sector FROM Main_table ";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_assoc($result)) {
$options .= "<option value=\"".$row['sector']."\">".$row['sector']."</option>\n ";
}
echo $options;
?>
subsector_options.php shown below:
<?php
$link = mysqli_connect("********", "*****,"*******", "********") or die (mysql_error());
$Sectors = $_REQUEST['filter_sector'];
$query = "SELECT sub_sector FROM Main_table WHERE sector='$Sectors'";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_assoc($result)) {$options .= "<option value=\"".$row['sub_sector']."\">".$row['sub_sector']."</option>\n ";
}
echo $options;
?>
For completeness, the solutions were:
Check how AJAX operations are doing using a browser network monitor
Load AJAX fetcher scripts in a browser tag - in many cases they will render quite happily there, allowing them to be more easily debugged
AJAX scripts that return HTML for injection should only return that HTML, and not a full HTML document.

Categories