Thursday, July 30, 2009

PHP 5 and HTML: How can I fill a textbox with the value contained in a database field?

I have database called "blogs" with three fields: blog_title, blog_author, and blog_body.





I am working on the section of my webpage where users will be able to alter existing blogs. When the user opens the edit_blog.php page, I want a textbox to be displayed, and, inside the textbox, I'd like the information stored in blog_body to be printed.





How should I do this? I'm having trouble combining the HTML and PHP.





Specific code examples would be appreciated!

PHP 5 and HTML: How can I fill a textbox with the value contained in a database field?
Lets suppose that $strValue contains the value which you want to show in text field. You can do this like:





%26lt;input type="text" id="strName" name="strName" value="%26lt;?php echo $strValue;?%26gt;" /%26gt;





In case of textarea, you can do this





%26lt;textarea id="strSomething" name="strSomething"%26gt;%26lt;?php echo $strValue;?%26gt;%26lt;/textarea%26gt;
Reply:This is not something for a newb to be doing, it is quite involved.





First create you connection to the DB:





$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')


or die('Could not connect: ' . mysql_error());


echo 'Connected successfully';


mysql_select_db('my_database') or die('Could not select database');





next query your data:


$query = 'SELECT * FROM my_table';


$result = mysql_query($query) or die('Query failed: ' . mysql_error());





now fill in your HTML


set the value="$result[index][name]





If you need more help hit me up on my blog at utahcon.efx2.com
Reply:To keep this answer relatively short and simple, I'm going to ignore error checking and assume you've already got a database connection...





$blog_author = mysql_real_escape_string('Joe Smith');


$query = "


 SELECT * FROM blogs


 WHERE blog_author = '$blog_author'


";


$result = mysql_query($query);


$data = mysql_fetch_assoc($result);








Then, in your form, do something like this...








%26lt;textarea name="blog_body"%26gt;


%26lt;?php echo($data['blog_body']) ?%26gt;


%26lt;/textarea%26gt;
Reply:For future reference, these links in addition to php.net already mentioned may be helpful:





http://www.php-mysql-tutorial.com/


http://www.freewebmasterhelp.com/tutoria...


http://www.webmonkey.com/programming/php...


http://www.phpfreaks.com/





A good book for reference is Web Database Application with PHP %26amp; MySQL from O'Reilly


No comments:

Post a Comment