1

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!

2
  • If you are new to website coding, it might help you to get a simple, functional solution working first, then move on to more challenging problems after that. Commented Aug 10, 2012 at 19:36
  • Yep, I totally agree. My solution for the news system works fine, yet now I'm trying to improve it and make it more user friendly by adding such features as this one. ;) Commented Aug 10, 2012 at 21:28

6 Answers 6

1

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);

?>
Sign up to request clarification or add additional context in comments.

8 Comments

Thank you very much! Your solution, although complex for me, works fine. Just one thing, if I'd like to insert the data in both one textarea (txtArea) and a textbox (e.g. txtTitle), how could I modify it?
@qalbiol You can modify .php file to generate echo depending on $_GET["field"] value. I'll add an example in my answer.
Hey, many thanks, but I think you've misunderstood my intention. :) I'd like to print both title and body in a textbox and textarea at the same time, from the given id. The < select > contains the news id's. Thanks again!!
@qalbiol Well, I'll answer you in about 10 hours. It's 2am in UK, gonna sleep now. :)
3am at Spain! Gonna get some sleep too! I'll be waiting for your answer! Thanks! ;)
|
0

Alright Ill give you a quick idea before my lunch... :)

  1. Setup an AJAX request to pass the selected dropdown box value to a PHP script.

  2. In this PHP script, fetch the data for the selected value from your database.

  3. Return the data and set the textbox's value to that.

Sending an AJAX Request

Comments

0

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

Comments

0

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/

Comments

0

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.

1 Comment

Thank you! A simple PHP / HTML solution will probably suit me better. I'll give it a try!
0

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.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.