Form Inside Div, Show Result In a Different Div - php

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...

Related

Run two completely different sqli queries inside one script

I'm new to php.
I have this page:
<?php
function renderForm($id, $StaffFullName, $StaffJobPosition, $error)
{
?>
<!doctype html>
<html>
<head><title></title></head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div>'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p>ID: <?php echo $id; ?></p>
Name: * <input type="text" name="StaffFullName" value="<?php echo $StaffFullName; ?>"/><br/>
Job Position: * <select name="JobPosition">
<?php
$query = "SELECT * FROM LUT_JOBPOS";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
if ($StaffJobPosition == $row['JobposID'])
{
echo "<option value='{$row['JobposID']}' selected='selected'>{$row['JobposTitle']}</option>";
}
else {
echo "<option value='{$row['JobposID']}'>{$row['JobposTitle']}</option>";
}
}
$result->close();
?>
</select><br/>
<input type="submit" name="submit" value="Update">
<input type="button" onClick="parent.location='view.php'" value="Back">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
require_once('../../authenticate.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// do some funky stuff
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checking that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$query = "SELECT * FROM STAFF WHERE StaffID=$id";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$result->close();
// check that the 'id' matches up with a row in the database
if($row)
{
// get data
$StaffFullName = $row['StaffFullName'];
$StaffJobPosition = $row['StaffJobPosition'];
// show form
renderForm($id, $StaffFullName, $StaffJobPosition, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
So, what happens here is this:
When you open the page like edit.php?id=1, it fetches the data of the associated record from STAFF table and shows them on page for the user to edit them.
This part of the code works fine.
I also want the user to be able to select "Job Position" possible values from a drop down box. The drop down box should get its data from another table in database, LUT_JOBPOS.
This is the part of the code that doesn't work.
I was using mysql_query commands before on this page and it worked perfectly. However I was told to switch on mysqli_query instead.
Since I did the conversion I can't find how to run these two queries on the same script.
I messed a little bit with the require_once command and depending on where I call it I can run one query or another, but never both of them.
Looking at the logs of my web host the only thing I can see that may be relevant to my issue is:
"mod_fcgid: stderr: PHP Notice: Undefined variable: connection in /var/www/vhosts/myhostdomain.com/httpdocs/prod15/admin/staff/edit.php on line 24"
The connection variable comes from authenticate.php and it holds the connection parameters to the database. I'm sure it's set otherwise the first query (that gets the user data) wouldn't work.
I read somewhere that you can't run two sqli queries on the same script.
Then how I'm supposed to use a LUT table (lookup table)?
PS: I know that for showing the data I can use a UNION and that's what I do.
But when I edit the data I want the user to be able to select only from the possible values that exist on the LUT table (drop down select box)
Any help?
You have a lot of issues in your code. You really need to review it before use it in some real application, but for your specific problem, here is my guess.
You are calling the line $result = mysqli_query($connection, $query); in the line 24 and only after taht you call require_once('../../authenticate.php');.
As you said, the $connection var is defined in the authenticate.php, so in the line 24 is undefined.
Try to use require in the first line of your php script.

Open new page with table Data from previous page

I'm building a website for the company I work for that is going to eventually replace the CRM we are using. Right now I have created a simple php file that creates a table of simple/basic values (I'm trying to test the concept before I scale it up to the read deal). I am using a WHILE loop to generate the table by pulling data from the server. I was able to make the first column in each row into a clickable link that will open to a new page. On this page, I want to post more detailed data that can be edited. For example, in the display.php file that shows the table created with the while loop I will have a property address, a city name and a person who is working to either buy or sell that property. When the user clicks on the first address, I want it to open into a page that will display information like bedrooms, bathrooms, square footage, subdivision, asking price, etc. It would be nice to have each of those fields editable too, but that's a different thing to tackle. Right now, I'm concerned with being able to click on one property and have it open up with the correct data in the next page. Right now, it successfully opens the page but it only shows the data from the first row no matter which row I click on in the table.
Here is the code that I have for the page that displays the table:
<?php
session_start();
if(isset($_SESSION['id'])) {
$username = $_SESSION['username'];
$userId = $_SESSION['id'];
} else {
header('Location: index.php');
die();
}
$dbCon = mysqli_connect("localhost", "##", "##", "##");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect: " . mysqli_connect_error();
}
$sql="SELECT * FROM leads";
$records=mysqli_query($dbCon,$sql);
?>
<html>
<head>
<title>Display Data</title>
<body>
<table action="" method="post" class="table" id="example">
<tr>
<th>Address</th>
<th>City</th>
<tr>
<?php
while($leads=mysqli_fetch_assoc($records)){
echo "<tr>";
//I'm trying to figure out how to pass the record's ID as a way of keeping track of which record I want to look at when I open it in the next page. I don't know how to put the id in the link so that it carries through to the next page.
echo "<td><a href='showstuff.php?leadid=$leadid'>".$leads['address']."</a></td>";
echo "<td>".$leads['city']."</td>";
echo "</tr>";
}
?>
</tr>
</table>
</body>
</head>
</html>
Here is my code for the page that should open up with a more detailed "profile view" of the data:
<?php
//connect to db
$dbCon = mysqli_connect("localhost", "##", "##", "##");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect: " . mysqli_connect_error();
}
//I tried to incorperate "WHERE leadid = '$_GET['leadid']'" in line 10 to define the lead id that is associated with the record that was selected in display.php and shoould be opened/shared to this page
$sql="SELECT * FROM leads";
$records=mysqli_query($dbCon,$sql);
$leads=mysqli_fetch_assoc($records);
//I tried to create a $_GET variable that calls on the record id that I am trying to pass from the display.php file to this page
$leadid=$_GET['leadid'];
?>
<html>
<head>
<title>Show Stuff</title>
<body>
<h1>Show Stuff Here</h1><br>
<?php
echo "<p>Test</p><br>";
//I only have one piece of information here to test if it works in the first place. Once it does, I'll add the rest of the fields to display
echo "Is ".$leadid=$leads['leadid']." your ID number?";
?>
</body>
</head>
</html>
Lastly, I am using sessions on here since eventually there will be various users with different levels of access to view and edit things. For now, it's really not too functional other than to log in and log out. It's also not very secure. But I'm more focused on figuring out the mechanics of one thing at a time as I build. It's no where near ready to be used. But I'm hopeful that I'll get there soon. You'll have to excuse my simple code, I'm just learning and teaching myself on my spare time since our company refuses to hire someone to actually do this...
You're putting $leadid in the URL parameters in the table, but you never set this variable.
<?php
while($leads=mysqli_fetch_assoc($records)){
echo "<tr>";
$leadid = $leads['leadid'];
echo "<td><a href='showstuff.php?leadid=$leadid'>".$leads['address']."</a></td>";
echo "<td>".$leads['city']."</td>";
echo "</tr>";
}
?>
Then you should be able to use $_GET['leadid'] in showstuff.php to show the information for the lead that they clicked on.
$leadid = intval($_GET['leadid']);
$sql="SELECT * FROM leads WHERE leadid = $leadid";
First, in your table, you have to put like this:
while($leads=mysqli_fetch_assoc($records)){
echo '<tr>';
echo '<td><a href="showstuff.php?leadid='.$leads['id'].'" >'.$leads['address'].'</a></td>';
echo '<td>'.$leads['city'].'</td>';
echo '</tr>';
}
Like this your link leadid will have a value.
Use simple quote ' ' for html value, it's faster and better for PHP. ;)
In your second file, make like this:
$leadid=$_GET['leadid'];
$sql="SELECT * FROM `leads` WHERE `id`='$leadid' ";
$records=mysqli_query($dbCon,$sql);
$leads=mysqli_fetch_assoc($records);
It's better to put for the table and columns names and ' ' for values.
In $leads array, you 'll have all data.
You can "print" it like this:
echo 'The ID is '.$leads['id'].' and the name is '$leads['name'];
I hope it's useful!

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..
}

Inserting SQL data into HTML textarea

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.

Selecting PHP Combo Box and Button

I am currently using PHP 5 with a MysSQL database with 2 tables. So far my PHP Combo Box is working however I need to access the values selected from the combo box. it goes like this:
1) I select a value from the Combo Box.
2) I click on the Submit button
3) The Submit button brings me to another webpage.
The problem that my program is facing now is during step 3 when I click the submit button there is no webpage generated. I think the problem is due to the sequencing of the Combo Box Codes and Button Codes.
My codes are as shown:
<?php
include "db_connect.php";
{
?>
<td valign=top><strong>Name:</strong></td>
<td>
<?php
echo '<select name="table_choice">';
echo "<option size =30 selected>Select</option>";
$result = mysql_query("show tables");
if(!$result) trigger_error("Query Failed: ". mysql_error($db), E_USER_ERROR);
if(mysql_num_rows($result))
{
while($table_array = mysql_fetch_array($result))
{
echo "<option>$table_array[0]</option>";
}
$array_value = $_POST['table_choice'];
if(!$_POST['submit'])
{
?>
<input type="submit" name="submit" value="Submit">
<?php
}
else
{
echo '<script type="text/javascript">
alert("Redirecting you to the site main page");
window.location="echo.php"</script>';
}
}
else
{
echo "<option>No Names Present</option>";
}
}
?>
Everything seems fine to me.
Where is the <form> tag?
Anyway, consider writing your web applications using some web framework or at least templates to separate the program logic (PHP code) from the presentation (HTML code). Else it will be a big unmaintainable mess soon (or maybe it already is).
<?php
include "db_connect.php";
{
?>
what's with the random bracket?
Never Mind got the answer. The answer is just to simply add an echo '</select>' above the $array_value = $_POST['table_choice'];. The answer is simply to end select with /select.
Thanks for the extra tips guys.

Categories