PHP retrieve data from database and show in text area - php

I m trying to display retrieved data from the database in the earlier created text area. Code is supposed to get users nickname and input message, store both in database and retrieve it back to text area, smth similar to one man chat (whatever is typed after clicking 'Send message' should be stored to database and retrieved and shown in the text area). I am able to store into my database and display retrieved data anywhere outside the text area. Any help appreciated. Thank you!
Code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<form method="post" action="postmessage.php">
<center>
<br />
<label for="output">Chat history</label>
<br />
<textarea name="output" cols="100" rows="25" id="output"></textarea>
<br />
<label for="nickname" maxlength="16">Nickname</label>
<br />
<input type="text" name="nickname" id="nickname" />
<br />
<label for="message" >Type your message here:</label>
<br />
<input name="message" type="text" id="message" size="87" /><input type="submit" value="Send Message" />
</form>
<?php
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('messenger', $connection);
$query = mysql_query('select * from messages');
while ($entry = mysql_fetch_object($query))
{
printf("<p>%s <br />- <em>%s</em></p>",
htmlentities($entry->message),
htmlentities($entry->nickname)
);
}
?>
</body>
</html>
postmessage.php
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<?php
$nickname=$_POST['nickname'];
$message = $_POST['message'];
$nickname = mysql_real_escape_string($nickname);
$message = mysql_real_escape_string($message);
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('messenger', $connection);
if (!mysql_query(
"insert into messages (nickname, message) VALUES ('$nickname', '$message')"
)){
echo ("Could not process your send request");
};
?>
<body>
</body>
</html>
UPDATED:
<?php
session_start();
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<form method="post" action="postmessage1.php">
<div style="text-align: center;">
<br />
<label for="output">Chat history</label>
<br />
<textarea name="output" cols="100" rows="25" id="output"><?php if(isset($_SESSION['currentChat'])){ echo $_SESSION['currentChat']; }?></textarea>
<br />
<label for="nickname" maxlength="16">Nickname</label>
<br />
<input type="text" name="nickname" id="nickname" />
<br />
<label for="message" >Type your message here:</label>
<br />
<input name="message" type="text" id="message" size="87" /><input type="submit" value="Send Message" />
</div>
</form>
</body>
</html>
post..php:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<?php
session_start();
$nickname = isset($_POST['nickname'])?$_POST['nickname']:"";
$message = isset($_POST['message'])?$_POST['message']:"";
if(empty($nickname) || empty($message)){
// no data return to form
header("location: chatform.php");
}
$mysqli = new mysqli("localhost", "root", "", "messenger");
/* create a prepared statement */
if ($stmt = $mysqli->prepare("INSERT INTO messages (nickname, message) VALUES (?, ?)")) {
/* bind parameters for markers */
$stmt->bind_param("ss", $nickname, $message);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
// Update Session
$_SESSION['nickname'] .= htmlentities($nickname);
$_SESSION['currentChat'] .= htmlentities($message);
// Redirect back to display content
header("Location: chatform.php");
?>
</body>
</html>

For your form, I suggest the following:
<?php
session_start();
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<form method="post" action="postmessage.php">
<div style="text-align: center;">
<br />
<label for="output">Chat history</label>
<br />
<textarea name="output" cols="100" rows="25" id="output"><?php if(isset($_SESSION['currentChat'])){ echo $_SESSION['currentChat']; }</textarea>
<br />
<label for="nickname" maxlength="16">Nickname</label>
<br />
<input type="text" name="nickname" id="nickname" value="<?php echo $_SESSION['nickName']; ?>" />
<br />
<label for="message" >Type your message here:</label>
<br />
<input name="message" type="text" id="message" size="87" /><input type="submit" value="Send Message" />
</div>
</form>
</body>
</html>
Then in your Post handler, do this:
<?php
start_session();
$nickname = isset($_POST['nickname'])?$_POST['nickname']:"";
$message = isset($_POST['message'])?$_POST['message']:"";
if(empty($nickname) || empty($message)){
// no data return to form
header("location: chatform.php");
}
$mysqli = new mysqli("localhost", "root", "", "messenger");
/* create a prepared statement */
if ($stmt = $mysqli->prepare("INSERT INTO messages (nickname, message) VALUES (?, ?)")) {
/* bind parameters for markers */
$stmt->bind_param("ss", $nickname, message);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
// Update Session
$_SESSION['nickName'] = htmlentities($nickname);
$_SESSION['currentChat'] .= htmlentities($message);
// Redirect back to display content
header("Location: chatform.php");
?>
Taking this further, you can add TimeStamps via JS and you can use AJAX to post the data instead of using the form. Just drop the redirects and the session data. Also if the user closes the browser by accident, and returns, it should re-populate the data if the session is still alive.
Could also compile the chat and autosave it into DB every min or so instead of every chat action. Adding a leave button can kill the session and save everything to the DB at that time. Lots of ways to do it.
Code above is untested.
EDIT after comments
For your Chat page, I suggest changing the textarea to a div for better style control. Here is an example of the style: http://jsfiddle.net/Twisty/8frqcyyk/
<?php
session_start();
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<style>
.chatForm {
background: #ccc;
border: 1px solid #000;
width: 40em;
}
.chatForm ul {
padding: 0;
width: 30em;
margin: 5px auto;
}
.chatForm ul li {
list-style: none;
}
.chatForm ul li label {
display: block;
font: 1em Verdana, sans-serif;
}
.chatForm label.title {
background: #222;
border: 3px solid #222;
color: #FFF;
display: block;
font: 1em Verdana, sans-serif;
height: 1.5em;
margin: 0px auto;
width: 30em;
}
.center {
text-align: center;
}
.chatHistory {
background: #fff;
border: 1px inset #DDD;
display: block;
font: 1em Verdana, sans-serif;
height: 15em;
margin: 0px auto;
overflow-y: scroll;
padding: 2px;
text-align: left;
width: 30em;
}
.chatHistory p {
margin: 5px 0;
}
.chatHistory label {
display: inline-block;
font: bold 0.85em Arial, sans-serif;
width: 100px;
}
.chatHistory label.senderName {
color: blue;
}
.chatHistory label.nickName {
color: red;
}
.messageText {
width: 75%;
}
input[type='submit'] {
font: .85em Arial, sans-serif;
width: 20%;
}
</style>
</head>
<body>
<form method="post" action="postmessage.php">
<div class="chatForm">
<label for="output" class="center title">Chat History</label>
<div id="output" class="chatHistory">
<?php echo $_SESSION['currentChat']; ?>
</div>
<ul>
<li>
<label for="nickname">Nickname</label>
<input type="text" name="nickname" id="nickname" value="<?php echo $_SESSION['nickName']; ?>" />
</li>
<li>
<label for="message">Type your message here:</label>
<input name="message" type="text" id="message" class="messageText" /><input type="submit" value="Send" /></li>
</ul>
</div>
</form>
</body>
</html>
A few changes for your Post handler too (that should not be wrapped in HTML):
<?php
session_start();
$nickname = isset($_POST['nickname'])?$_POST['nickname']:"";
$message = isset($_POST['message'])?$_POST['message']:"";
if(empty($nickname) || empty($message)){
// no data return to form
header("location: chatform.php");
}
$mysqli = new mysqli("localhost", "root", "", "messenger");
/* create a prepared statement */
if ($stmt = $mysqli->prepare("INSERT INTO messages (nickname, message) VALUES (?, ?)")) {
/* bind parameters for markers */
$stmt->bind_param("ss", $nickname, $message);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
// Update Session
$_SESSION['nickname'] .= htmlentities($nickname);
$results = $mysqli->query("SELECT * FROM messages");
$updateChat = "";
while($row = $results->fetch_assoc()){
$updateChat .= "<p><label>". htmlentities($row['nickname'] .":</label>";
$updateChat .= htmlentities($row['message']) . "</p>\r\n";
}
$results->free();
$mysqli->close();
$_SESSION['currentChat'] = $updateChat;
// Redirect back to display content
header("Location: chatform.php");
?>
If it were me, I would improve me DB schema. The table could include more columns: ID, DateStamp, Sender, Recipient, Message. Hope that helps, and again, untested.

Related

change input box value according to variable php and html

I am making a PHP project and am trying to change an input boxes value according to a PHP variable, how would I do this? So far, when I try to change the input boxes value it just changes the value to the name of the variable.
Here's the html for that section:
echo '
<html>
<title>Ramen</title>
<body>
<h1>
<p>Welcome to NoteBook!</p>
<form method="post">
<p>File Name:<input type="text" name="fname"></p>
<p>Type Here:<input type="text" name="content" id="TextBox" value="<?php echo $value; ?>"><p>
<p>Save:<input type="submit" value="Save"></p>
</form>
<form method="post">
<p>File to Open: <input type="text" name="filename"></p>
<input type="submit" value="Open">
</form>
</h1>
</body>
<style>
body{
background-color:#66b3ff;
}
p{
margin-left:30px;
}
h1{
background-color:white;
height:600px;
border-radius:1px;
font-size:18px;
font:italic;
}
#TextBox{
height:500;
width:700;
}
{
</style>
</html>```
$value doesn't appear to be being set anywhere.
I'm also a little confused as to why you have two <form>s.
As a starter, you need to parse the values coming in from the form, for example:
<?php
if (isset($_POST["filename"]) { // The $_POST variables are set using the name element of the <input> tag
$value = $_POST["filename"]
}
?>
You would likely want to do some more validation on the content of $_POST["value"] before accepting it.
Perhaps take a look at this example to get you started.
I leave you a possible example with explanation.
Besides, I have adapted the HTML structure a bit, since it has serious formatting problems. I advise you to read the manual on how to use the labels.
I added the name attribute to the submit, in order to know if the form is defined:
<input type="submit" name="save_data" value="Save">
Example:
<?php
// reset ¡important! (avoid warning <b>Warning</b>: Undefined variable etc..)
$file_name = $content = $txt_content = '';
// Recomended to check if the form is define
if (isset($_POST['save_data'])) {
// Get the inputs data
$file_name = $_POST['fname'] ?? '';
$content = $_POST['content'] ?? '';
// You can use textarea
$txt_content = $_POST['txt_content'] ?? '';
// Data is true
if ($file_name && $content && $txt_content) :
// Do somenting (ex: save it in DB)
//
//
$success = "Save correctly: $file_name";
// Data is empty (optional)
else :
$error = 'Te fields are empty.';
endif;
}
?>
<html lang="en-EN">
<head>
<title>Ramen</title>
<style>
body{
background-color:#66b3ff;
}
p {
margin-left:30px;
}
.wrapper {
background-color:white;
height:600px;
border-radius:1px;
font-size: 1rem;
font:italic;
padding: 1rem;
}
textarea {
height:200px;
width:400px;
}
.error {
color: red;
}
.success {
color: green;
}
</style>
</head>
<body>
<div class="wrapper">
<h1>Welcome to NoteBook!</h1>
<form method="post">
<lable for="fname">File Name:</lable>
<input type="text" name="fname" id="fname" value="<?php echo $file_name; ?>"></p>
<label for="content">Type Here:</label>
<input type="text" name="content" id="content" value="<?php echo $content; ?>">
<!-- for the content you could use the textarea tag -->
<textarea name="txt_content"><?php echo $txt_content; ?></textarea>
<input type="submit" name="save_data" value="Save">
<?php if (isset($error)) echo '<p class="error">' . $error . '</p>'; ?>
<?php if (isset($success)) echo '<p class="success">' . $success . '</p>'; ?>
</form>
</div>
</body>
</html>

Contact Form Stopped working after adding implementing SSL, it's PHP based and was working fine before https was added

Contact Form on my website stopped working after adding implementing SSL, it's PHP based and was working fine for 5 years before when it was just http.
Now when the form is filled correctly the message *"Sorry! Unfortunately, your message could not be sent. The form as you filled it out is displayed below. Make sure each field completed, and please also address any issues listed below:" keeps appearing.
It might be a simple issue but I don't know PHP and found this on a tutorial - would really help if anyone point out the issue and how to resolve it.
I can provide more details if needed.
Thanks!!
<?php
// Information to be modified
$your_email = "mail#website.com"; // email address to which the form data will be sent
$subject = "Visitor Message from Website"; // subject of the email that is sent
$thanks_page = "thankyou.htm"; // path to the thank you page following successful form submission
$contact_page = "../contact.htm"; // path to the HTML contact page where the form appears
// Nothing needs to be modified below this line
if (!isset($_POST['submit'])) {
header( "Location: $contact_page" );
}
if (isset($_POST["submit"])) {
$nam = $_POST["name"];
$ema = trim($_POST["email"]);
$com = $_POST["comments"];
$spa = $_POST["spam"];
if (get_magic_quotes_gpc()) {
$nam = stripslashes($nam);
$ema = stripslashes($ema);
$com = stripslashes($com);
}
$error_msg=array();
if (empty($nam) || !preg_match("~^[a-z\-'\s]{1,60}$~i", $nam)) {
$error_msg[] = "The name field must contain only letters, spaces, dashes ( - ) and single quotes ( ' )";
}
if (empty($ema) || !filter_var($ema, FILTER_VALIDATE_EMAIL)) {
$error_msg[] = "Your email must have a valid format, such as name#mailhost.com";
}
$limit = 1000;
if (empty($com) || !preg_match("/^[0-9A-Za-z\/-\s'\(\)!\?\.,]+$/", $com) || (strlen($com) > $limit)) {
$error_msg[] = "The Comments field must contain only letters, digits, spaces and basic punctuation ( ' - , . ), and has a limit of 1000 characters";
}
if (!empty($spa) && !($spa == "4" || $spa == "four")) {
echo "You failed the spam test!";
exit ();
}
// Assuming there's an error, refresh the page with error list and repeat the form
if ($error_msg) {
echo '<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
<style>
body {background: #f7f7f7; font: 100%/1.375 georgia, serif;padding: 20px 40px;}
form div {margin-bottom: 10px;}
.content {width: 40%; margin: 0 auto;}
h1 {margin: 0 0 20px 0; font-size: 175%; font-family: calibri, arial, sans-serif;}
label {margin-bottom: 2px;}
input[type="text"], input[type="email"], textarea {font-size: 0.75em; width: 98%; font-family: arial; border: 1px solid #ebebeb; padding: 4px; display: block;}
input[type="radio"] {margin: 0 5px 0 0;}
textarea {overflow: auto;}
.hide {display: none;}
.err {color: red; font-size: 0.875em; margin: 1em 0; padding: 0 2em;}
</style>
</head>
<body>
<div class="content">
<h1>Sorry!</h1>
<p>Unfortunately, your message could not be sent. The form as you filled it out is displayed below. Make sure each field completed, and please also address any issues listed below:</p>
<ul class="err">';
foreach ($error_msg as $err) {
echo '<li>'.$err.'</li>';
}
echo '</ul>
<form method="post" action="', $_SERVER['PHP_SELF'], '">
<div>
<label for="name">Name</label>
<input name="name" type="text" size="40" maxlength="60" id="name" value="'; if (isset($_POST["name"])) {echo $nam;}; echo '">
</div>
<div>
<label for="email">Email Address</label>
<input name="email" type="email" size="40" maxlength="60" id="email" value="'; if (isset($_POST["email"])) {echo $ema;}; echo '">
</div>
<div>
<label for="comm">Comments</label>
<textarea name="comments" rows="10" cols="50" id="comm">'; if (isset($_POST["comments"])) {echo $com;}; echo '</textarea>
</div>
<div class="hide">
<label for="spam">What is two plus two?</label>
<input name="spam" type="text" size="4" id="spam">
</div>
<div>
<input type="submit" name="submit" value="Send">
</div>
</form>
</body>
</html>';
exit();
}
$email_body =
"Name of sender: $nam\n\n" .
"Email of sender: $ema\n\n" .
"COMMENTS:\n\n" .
"$com" ;
// Assuming there's no error, send the email and redirect to Thank You page
if (isset($_REQUEST['comments']) && !$error_msg) {
mail ($your_email, $subject, $email_body, "From: $nam <$ema>" . "\r\n" . "Reply-To: $nam <$ema>");
header ("Location: $thanks_page");
exit();
}
}

PHP Form not posting to a MySQL database

I'm creating a new booking system for my employer, in which a form is filled in and data enters a pre-built MySQL database.
I'm honestly unsure as to what I am doing wrong. Originally the data would not post into the database, but the form would appear to have submitted. Now, the form just submits to a white page. I will submit the full page code below as there's no comprimising data there, and hopefully somebody will be able to help.
<head>
<title> Moat Laptop Bookinge </title>
<?php
if (isset($_POST['submitted'])) {
include('booking_db.php');
$name = $_POST['name'];
$out = $_POST['out'];
$in = $_POST['in'];
$sqlinsert = "INSERT INTO Future (name, out, 'in') VALUES ('$name', '$out', '$in')";
if (!mysqli_query ($dbcon, $sqlinsert)) {
die('error inserting new record');
}
$newrecord = "Laptop has been successfully Booked!";
}
?>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
$("#datepicker").datepicker();
});
</script>
<script>
$(document).ready(function() {
$("#datepicker2").datepicker();
});
</script>
</head>
<body style="background-height: 100%;background-width: 100%;background: #141E30;background: -webkit-linear-gradient(to left, #141E30 , #243B55);background: linear-gradient(to left, #141E30 , #243B55);">
<div id="logo" style="font-family: Tw Cen MT; font-weight: Bold; position: fixed; color: white; left: 650px;top: 35px; font-size: 80px;text-shadow: 3px 3px #c7c7c7;">
Book a Laptop
</div>
<div id="content_box" style="background-color: white;position: fixed; left: 450px;top: 135px; width:60%; height: 70%; border-radius: 3px;">
<center>
<form method="post" action="book.php" style="font-family: Bodoni MT;">
<input type="hidden" name="submitted" value="true" />
<br />
<br />
<b><legend>First Name and First Letter of Surname</legend></b>
<input type="text" name="name" value="Ex. James T" />
<br/>
<br />
<b><legend>When will you need to collect the device?</legend></b>
<input id="datepicker2" name="out" />
<br/>
<br />
<b><legend>When will you return the device?</legend></b>
<input id="datepicker" name="in" />
<br />
<input type="submit" value="Confirm Booking" />
</center>
<?php
echo $newrecord
?>
</div>
</body>
If you need any more information, within reason, feel free to ask.
EDIT
This issue has been resolved, I cannot mark the answer as it was my answer and I have to wait 2 days. THank you for all of the answers.
There could be a problem in the line include('booking_db.php');. You should mention error_reporting(E_ALL); at the top of the page, and try debugging:
error_reporting(E_ALL);
if (isset($_POST['submitted'])) {
var_dump(file_exists('booking_db.php')); //check if you get true or false
require 'booking_db.php'; // Change include to required
echo "Test";
exit;
$name = $_POST['name'];
echo $name; // Check
$out = $_POST['out'];
$in = $_POST['in'];
$sqlinsert = "INSERT INTO Future (name, out, 'in') VALUES ('$name', '$out', '$in')";
var_dump($dbcon); // check
if (!mysqli_query ($dbcon, $sqlinsert)) {
die('error inserting new record');
}
$newrecord = "Laptop has been successfully Booked!";
}
Please check what you're getting after form submit.
Replace your insert query with :
INSERT INTO Future
(`name`,`out`,`in`) VALUES ('".$name."', '".$out."', '".$in."')
and
if (isset($_POST['submitted'])) with if (isset($_POST['Confirm Booking']))
because you have to put your value of submit button in POST
Turns out, my issue was with
if (!mysqli_query ($dbcon, $sqlinsert)) {
die('error inserting new record');
}
$newrecord = "Laptop has been successfully Booked!";
}
I changed this to
if (mysqli_query ($link, $sqlinsert)) {
echo "";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
And changed a few variables to match up with this, and it started working and posted to my DB. Thank you to anyone who answered.

Send mail using php and postfix

Thank you for taking the time to review my question.
I have postfix set up on Centos 6.4 I am not very familiar with E-mail servers or PHP, but I would like to set up a simple sight to send emails using postfix. I was told I should use php. My current. (not working) source code is this...
<!doctype html>
<html>
<head>
<style type="text/css">
#mainContainer
{
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
#adressContainer
{
width:100%;
height:3%;
}
#buttonContainer
{
width:100%;
height:5%;
}
#bodyContainer
{
width:100%;
height:90%;
}
#address
{
resize:none;
width:100%;
height:100%;
}
#bodyText
{
resize:none;
width:100%;
height:100%;
}
</style>
<script>
<?php
function sendMail()
{
$to = "someone#somewhere"
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
}
?>
</script>
<!--<link rel="stylesheet" type="text/css" href="email.css" />-->
</head>
<body>
<div id="mainContainer">
<div id="addressContainer">
<input id="adress" type="text" name="Adress: "></input>
</div>
<div id="buttonContainer">
<button type="submit" onclick="sendMail()">send</button>
</div>
<div id="bodyContainer">
<textarea id="bodyText">I love you whitney :) </textArea>
</div>
</div>
</body>
</html>
PHP runs on the server. onClick executes Javascript on the CLIENT machine. You can NOT directly invoke PHP functions via Javascript code, or vice versa.
What you're doing can be accomplished with a simple form:
<?php
if ($_SERVER["REQUEST_METHOD"] == 'POST') {
$to = $_POST['to'];
$text = $_POST['text'];
mail($to, .....);
}
?>
<form method="POST" action="">
<input type="text" name="to" />
<input type="text" name="text" />
<input type="submit" />
</form>
There is no need to use Javascript at all.

How to create a Dynamic Phonebook with Groups functionality

I want to create an online phone book where user can add as many contact as he want and he must be able to create and divide those contact into groups. For eg. Friends, Family etc. All the groups must be created or deleted by the user. Can anyone help me..
Any good tutorial or a book reference will do. I will be using PHP, MySQL and a little bit of AJAX and jQuery.
Thanks
http://learning-computer-programming.blogspot.com/2008/05/creating-simple-phone-book-in-php.html will give u general idea for creating phone book.
For categorizing ur book u would be needing another table storing the nature and id of the group(group_table) which u can thru a field in main phone_table
config.php
<?php
$dbname = "phonebook"; // name of database
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("phonebook") or die(mysql_error());
?>
add.php
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Phone book form</title>
<style type="text/css">
body {
margin: 0 12%;
width: 990px;
}
form {
width: 30em;
}
fieldset {
margin: 1em 0;
padding: 1em;
border-width : .1em ;
border-style: solid;
}
form div {
padding: 0.4em 0;
}
label {
display:block;
}
input {
width: 20em;
}
input.submit {
width: auto;
}
</style>
</head>
<body>
<p>Phone Book - Enter your contact's details</p>
<form method="post" action="index.php">
<p><label for="name">Name:</label><input type="text" name="username" maxlength="20" title="Enter Name"></p>
<p><label for="phonenumber">Phone Number</label><input type="text" maxlength="12" name="phone" title="Enter phone number"></p>
<p><label for="town">Town</label><input type="text" maxlength="25" title="Enter name of town" name="town"></p>
<input type="submit" name="save" value="Save Data">
</form>
</body>
</html><!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Phone book form</title>
<style type="text/css">
body {
margin: 0 12%;
width: 990px;
}
form {
width: 30em;
}
fieldset {
margin: 1em 0;
padding: 1em;
border-width : .1em ;
border-style: solid;
}
form div {
padding: 0.4em 0;
}
label {
display:block;
}
input {
width: 20em;
}
input.submit {
width: auto;
}
</style>
</head>
<body>
<p>Phone Book - Enter your contact's details</p>
<form method="post" action="index.php">
<p><label for="name">Name:</label><input type="text" name="username" maxlength="20" title="Enter Name"></p>
<p><label for="phonenumber">Phone Number</label><input type="text" maxlength="12" name="phone" title="Enter phone number"></p>
<p><label for="town">Town</label><input type="text" maxlength="25" title="Enter name of town" name="town"></p>
<input type="submit" name="save" value="Save Data">
</form>
</body>
</html>
index.php
<?php
include_once('config.php'); // call database login details page
if(isset($_POST['save'])) {
$name = strip_tags($_POST['username']);
$phone = strip_tags($_POST['phone']);
$town = strip_tags($_POST['town']);
$query = "INSERT INTO my_contacts(name,phonenumber,town) VALUES('$name', '$phone', '$town')";
$result = mysql_query($query);
if($result) {
echo "Data successfully stored!";
}
else {
echo "Data was NOT saved!";
echo "<p> Query: ' $query ' </p>";
}
}
$query = "SELECT * from my_contacts";
$result = mysql_query($query);
echo "<h3>My Contact's Data</h3>";
echo '<table border = "1">';
echo "<tr><td>Id</td><td>Name</td><td>Phone Number</td><td>Town</td></tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr><td>".$row['id']."</td><td><a href='index.php?ID=$row[id]'>".$row['name']."</a></td><td>".$row['phonenumber'].
"</td><td>".$row['town']."</td></tr>";
}
echo "</table>";
?>

Categories