PDO insert with $_POST? - php

I am trying to insert data from a simple html form with $_POST into the database with PHP and PDO. I am not getting any errors, there is just nothing going into the database. If I type the values manually in the code it works but nothing happens when typing into the html form. At some point I had "Array" typed out.
UPDATE:
The error I am getting is:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null' in ...
Why is Column title null?
The database is just a table with 4 fields (id, title, message and time/timestamp field.
The id field is primary AI and the timestamp field is picking up the time automatically.
Here is the connect.inc.php file:
<?php
class DB extends PDO
{
public function __construct($dbname = "blogdata")
{
try {
parent::__construct("mysql:host=localhost;dbname=$dbname;charset=utf8",
"root", "");
} catch (Exception $e) {
var_dump($e);
}
}
}
?>
And here is the post.php file:
<?php
require 'connect.inc.php';
$db = new DB('blogdata');
$stmt = $db->prepare("INSERT INTO blogposts (title, message, time) VALUES (:title, :message, :time)");
$stmt->bindParam(':title', $_POST['title']);
$stmt->bindParam(':message', $_POST['message']);
$stmt->bindParam(':time', $time);
$title = $_POST['title'];
$message = $_POST['message'];
$stmt->execute();
?>
<!DOCTYPE html>
<html>
<head>
<title>Create blog post</title>
<meta charset="utf-8" />
</head>
<body>
<!--- Add blog post --->
<div class="add_form">
<form id="add_post" method="post" action="index.php" enctype="text/plain">
<fieldset>
<legend>Create post</legend>
<label for="post_title">Title:
<input id="title" type="text" name="title" value="<?php if (isset($title)) { echo htmlentities ($title); } ?>" >
</label>
<label for="message">Message:
<textarea id="message" name="message" rows="20" cols="30" maxlength="50" value="<?php if (isset($message)) { echo htmlentities ($message); } ?>" ></textarea>
</label>
</fieldset>
<input id="send" type="submit" value="Send">
</form>
</div>
</body>
</html>
ANSWER
You need to wrap everything up and check if $_POST is not empty. Also the problem was action="index.php" in the form. It needed to be set to post.php.
Here is the correct code in post.php:
<?php
if (!empty($_POST)) {
require 'connect.inc.php';
$db = new DB('blogdata');
$stmt = $db->prepare("INSERT INTO blogposts (title, message) VALUES (:title, :message)");
$stmt->bindParam(':title', $_POST['title']);
$stmt->bindParam(':message', $_POST['message']);
$title = $_POST['title'];
$message = $_POST['message'];
$stmt->execute();
header ('Location: index.php');
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Create blog post</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="reset.css" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<!--- Add blog post --->
<div class="add_form">
<form id="add_post" method="post" action="post.php">
<fieldset>
<legend>Create post</legend>
<label for="post_title">Title:
<input id="title" type="text" name="title" value="<?php if (isset($title)) { echo htmlentities ($title); } ?>" >
</label>
<label for="message">Message:
<textarea id="message" name="message" rows="20" cols="30" maxlength="50" value="<?php if (isset($message)) { echo htmlentities ($message); } ?>" ></textarea>
</label>
</fieldset>
<input id="send" type="submit" value="Send">
</form>
</div>
</body>
</html>

Here is the proper connect.inc.php file:
<?php
class DB extends PDO
{
public function __construct($dbname = "blogdata")
{
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$dsn = "mysql:host=localhost;dbname=$dbname;charset=utf8";
parent::__construct($dsn, "root", "", $opt);
}
}
Dunno if it caused error but
And here is the post.php file:
<form id="add_post" method="post" action="index.php"
Anyway, the real cause of the problem is similar to that. Some silly typo somewhere

Awser for your last comment :
#Corum Hi, I´m calling index.php in the form because index.php are
displaying all the posts and after sending the form the user should be
directed to index.php and be able to see the results... I really can´t
seem to solve this:(
If you call index.php with <form action="index.php"> your form data will never be processed.
You have to call post.php instead and after redirect to index.php.
Corrected code (replace top PHP block in your file post.php) :
<?php
if (!empty($_POST) {
// Only process if form is submitted (when page is launched, it use GET method)
require 'connect.inc.php';
$db = new DB('blogdata');
$stmt = $db->prepare("INSERT INTO blogposts (title, message, time) VALUES (:title, :message, :time)");
$stmt->bindParam(':title', $_POST['title']);
$stmt->bindParam(':message', $_POST['message']);
$stmt->bindParam(':time', $time);
$title = $_POST['title'];
$message = $_POST['message'];
$stmt->execute();
// Redirect to index.php
header('Location : index.php');
exit;
}
?>
And change your html form for : <form action="post.php" ...>

Related

How to import two values from html to my SQL table

I need to import the values of emailaddress and fullname from html into my SQL table.
Here is my HTML:
<!DOCTYPE html>
<head>
<title>Julian's Newsletter</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link href="newsletter.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
</head>
<body>
<h1>Newsletter</h1>
<form action="formsubmit.php" method="post">
<div class="container">
<h2>Subscribe to my Newsletter</h2>
<p>Subscribe to my newsletter to recieve recent news, a specialy curated product list, and the Product of the Month.</p>
</div>
<div class="container" style="background-color:white">
<input type="text" placeholder="Name" name="fullname" required>
<input type="text" placeholder="Email address" name="emailaddress" required>
<label>
<input type="checkbox" checked="checked" name="subscribe"> Monthly Newsletter
</label>
</div>
<div class="container">
<input type="submit" value="Subscribe">
</div>
</form>
</body>
And here is my PHP so far. I am a beginner and I have very little knowledge of PHP.
<?php
$servername = "localhost";
$emailaddress = "emailaddress";
$fullname = "fullname";
$dbname = "email_windowsisslow_com";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $fullname, $emailaddress);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO emaillist (emailaddress, fullname)
VALUES ('', '')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
I am new to Stack Overflow and I do not assume that anyone will actually write the code for me. I need help understanding what is written, and how to write the code to perform the action I require of it.
I would suggest you must use prepared statements to avoid SQL injection.
$stmt = $conn->prepare("INSERT INTO emaillist (emailaddress, fullname)
VALUES (:emailaddress , :fullname)");
$stmt->bindParam(':emailaddress ', $emailaddress );
$stmt->bindParam(':fullname ', $fullname );
$stmt->execute();
In your PHP file change the two lines:
$emailaddress = "emailaddress";
$fullname = "fullname";
To
$emailaddress = $_POST["emailaddress"];
$fullname = $_POST["fullname"];
And add to your insert statement
$sql = "INSERT INTO emaillist (emailaddress, fullname) VALUES ({$emailaddress}, {$fullname})";

How to insert a record in MySQL with PHP with an HTML form

I have created a form in html and I would like that the dataentered in the form is sent to a mysql database in XAMMP. I created the database, the table and the connectivity.php file that manages the connection to the database and data entry, but when I try I get the following error:
"Fatal error: Uncaught Error: Call to undefined function mysql_connect() in C:\xampp\htdocs\example\connectivity.php:8 Stack trace: #0 {main} thrown in C:\xampp\htdocs\example\connectivity.php on line 8"
I post all the code that I wrote. Does anyone know where I'm wrong?
here is the form index.html
<!DOCTYPE HTML>
<html>
<head>
<title>Contact Us</title>
<link rel="stylesheet" type="text/css" href="style.css">
<?php include("connectivity.php"); ?>
</head>
<body>
<div id="contact">
<h3>Contact Us For Any Query</h3>
<form method="POST" action="connectivity.php">
Name
<br>
<input type="text" name="name">
<br> Email
<br>
<input type="text" name="email">
<br> Message
<br>
<textarea rows="10" cols="50" maxlength="100" name="message"></textarea>
<br>
<input type="submit" value="Send Message">
</form>
</div>
</body>
</html>
Then the code used to define database and the table:
CREATE DATABASE practice;
USE practice;
CREATE TABLE contact
(
contactID INT(9) NOT NULL auto_increment,
contactName VARCHAR(40) NOT NULL,
contactEmail VARCHAR(40) NOT NULL,
message VARCHAR(250) NOT NULL,
PRIMARY KEY(contactID)
);
Finally the connectivity.php file:
<?php
//connecting to the database
define('DB_HOST', 'localhost');
define('DB_NAME', 'practice');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
//inserting Record to the database
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$query = "INSERT INTO contact(contactName,contactEmail,message)VALUES('$name','$email','$message')";
$result = mysql_query($query);
if($result)
{
echo "Successfully updated database";
}
else
{
die('Error: '.mysql_error($con));
}
mysql_close($con);
?>
P.S: I installed the latest version of XAMMP (5.6.15)
$con=mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD,##TABLE NAME##) or die("Failed to connect to MySQL: " . mysql_error());
$query = "INSERT INTO contact(contactName,contactEmail,message)VALUES('$name','$email','$message')";
$result = mysqli_query($con,$query);
If you are using one of the latest version of xampp therefore you have to use PDO or MySQLi .
Your have to change your codes to something like this.
Your connectivity page
<?php
$db = new PDO('mysql:host=localhost;dbname=practice;charset=utf8',
'root',
'',
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
?>
<?php
if (isset($_POST['name'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$stmt = $db->prepare("INSERT INTO `contact` (contactName,contactEmail,message)
VALUES (:name, :email, :message)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':message', $message);
$stmt->execute();
echo 'added';
}
?>
Your home page
<!DOCTYPE HTML>
<html>
<head>
<title>Contact Us</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="contact">
<h3>Contact Us For Any Query</h3>
<form method="POST" action="connectivity.php">
Name
<br>
<input type="text" name="name">
<br> Email
<br>
<input type="text" name="email">
<br> Message
<br>
<textarea rows="10" cols="50" maxlength="100" name="message"></textarea>
<br>
<input type="submit" value="Send Message">
</form>
</div>
</body>
</html>
Hope this helps
Firts you see your phpinfo:
<?php
phpinfo();
?>
Then see in here , php_mysql is enabled or disabled?
If there not php_mysql, change php.ini file:
Uncomment extension=php_mysql.dll

When user hits the submit button, index.php does not catch the action and update database

I have 3 files here, index.php, authors.html.php and form.html.php, index.php is my controller script that then calls authors.html.php to display the authors and finally form.html.php when a user wants to edit an author or add an author in a MySQL database.
The problem I run into is that when the user hits the update button, the database does not get update the author details... it seems my controller script is not catching the 'editform' action? I'm no entirely sure why it's slipping. Here are excerpts from the files:
index.php (controller):
<?php
include $_SERVER['DOCUMENT_ROOT'] . '/includes/magicquotes.inc.php';
if ((isset($_POST['action'])) and ($_POST['action'] == 'Edit'))
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php'; //connect to mysql
try
{
$sql = 'SELECT id, name, email FROM author WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error fetching author details...';
include 'error.html.php';
exit();
}
$row = $s->fetch();
$pageTitle = 'Edit Author';
$action = 'editform';
$name = $row['name'];
$email = $row['email'];
$id = $row['id'];
$button = 'Update Author';
include 'form.html.php';
header('Location: .');
exit();
}
if (isset($_GET['editform']))
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php'; //connect to mysql
try
{
$sql = 'UPDATE author SET name = :name, email = :email WHERE id = :id';
$s->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->bindValue(':name', $_POST['name']);
$s->bindValue(':email', $_POST['email']);
$s->execute();
}
catch (PDOException $e)
{
$error = "Error updating selected author.";
include 'error.html.php';
exit();
}
header('Location: .');
exit();
}
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
try
{
$result = $pdo->query('SELECT id, name FROM author');
}
catch (PDOException $e)
{
$error = 'Error fetching authors from the database: ';
include 'error.html.php';
exit();
}
foreach($result as $row)
{
$authors[] = array('id' => $row['id'], 'name' => $row['name']);
}
include 'authors.html.php';
?>
authors.html.php
<?php include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/helpers.inc.php' ?>
// When I call "htmlout()" is the same as "echo htmlspecialchars()"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Manage Authors</title>
</head>
<body>
<p>
<h1>Manage Authors</h1>
<p>
Add New Author
</p>
<ul>
<?php foreach ($authors as $author): ?>
<li>
<form action="?<?php $action ?>" method="post">
<div>
<?php htmlout($author['name']); ?>
<input type="hidden" name="id" value="<?php echo $author['id']; ?>">
<input type="submit" name="action" value="Edit">
<input type="submit" name="action" value="Delete">
</div>
</form>
</li>
<?php endforeach; ?>
</ul>
<p>
Return to JMS Home
</p>
</p>
</body>
</html>
form.html.php
<?php include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/helpers.inc.php' ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php htmlout($pageTitle); ?></title>
</head>
<body>
<h1><?php htmlout($pageTitle); ?></h1>
<form action="?<?php $action ?>" method="post">
<div>
<label for="name">Name:
<input type="text" name="name" id="name" value="<?php htmlout($name); ?>">
</label>
</div>
<div>
<label for="email">Email:
<input type="text" name="email" id="email" value="<?php htmlout($email); ?>">
</label>
</div>
<div>
<input type="hidden" name="id" value="<?php htmlout($id); ?>">
<input type="submit" name="action" value="<?php htmlout($button) ?>">
</div>
</form>
</body>
</html>
I found out what I did wrong! Phew...
I screwed up on this line
$s->prepare($sql);
it should have been
$s = $pdo->prepare($sql);
and as #MamaWalter pointed out, I was looking at $_GET for a $_POST variable, so I changed that it it's now working great!
#linus72982 Your suggestion to use var_dump() was a tremendous help, I am new to PHP and thus did not know about it... thanks again for everything!

INSERT with PDO $_POST not working

SOLVED - ANSWER ADDED AT THE BOTTOM OF THE POST
Please can someone help me out as I can´t understand what the heck I am doing wrong.
I have a html form with 2 fields "title" and "message". I´m trying to get this to go into the database with PDO and $_POST but I am just getting this error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null' in
I´m doing everything by the book but it´s not working and I going to throw my computer out the window soon. So please anyone have any idea what is wrong? Why is title turning "NULL"?
The database is a 4 column table (id, title, message and timestamp). The id field is primary and auto intent
ANY help is really appreciated!!! And I´m a beginner...
Here is post.php file:
<?php
require 'connect.inc.php';
$db = new DB('blogdata');
$stmt = $db->prepare("INSERT INTO blogposts (title, message, time) VALUES (:title, :message, :time)");
$stmt->bindParam(':title', $_POST['title']);
$stmt->bindParam(':message', $_POST['message']);
$stmt->bindParam(':time', $time);
$title = $_POST['title'];
$message = $_POST['message'];
$stmt->execute();
?>
<!DOCTYPE html>
<html>
<head>
<title>Create blog post</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="reset.css" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<!--- Add blog post --->
<div class="add_form">
<form id="add_post" method="post" action="post.php" enctype="text/plain">
<fieldset>
<legend>Create post</legend>
<label for="post_title">Title:
<input id="title" type="text" name="title" value="<?php if (isset($title)) { echo htmlentities ($title); } ?>" >
</label>
<label for="message">Message:
<textarea id="message" name="message" rows="20" cols="30" maxlength="50" value="<?php if (isset($message)) { echo htmlentities ($message); } ?>" ></textarea>
</label>
</fieldset>
<input id="send" type="submit" value="Send">
</form>
</div>
</body>
</html>
And here is the connect.inc.php file:
<?php
class DB extends PDO
{
public function __construct($dbname = "blogdata")
{
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$dsn = "mysql:host=localhost;dbname=$dbname;charset=utf8";
parent::__construct($dsn, "root", "", $opt);
}
}
?>
ANSWER:
This issue was finally solved. The problem is you need to check if $_POST is empty or not. And right after the if (!empty($_POST)) { set the require 'connect.inc.php';. Also to minimize code do like Dave Just said, change :
$stmt->bindParam(':title', $_POST['title']);
$stmt->bindParam(':message', $_POST['message']);
To:
$stmt->execute(array(':title' => $_POST['title'], ':message' => $_POST['message']));
Here is the working code in post.php:
<?php
if (!empty($_POST)) {
require 'connect.inc.php';
$db = new DB('blogdata');
$stmt = $db->prepare("INSERT INTO blogposts (title, message) VALUES (:title, :message)");
$stmt->execute(array(':title' => $_POST['title'], ':message' => $_POST['message']));
$title = $_POST['title'];
$message = $_POST['message'];
// Redirect to index.php
header ('Location: index.php');
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Create blog post</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="reset.css" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<!--- Add blog post --->
<div class="add_form">
<form id="add_post" method="post">
<fieldset>
<legend>Create post</legend>
<label for="post_title">Title:
<input id="title" type="text" name="title" value="<?php if (isset($title)) { echo htmlentities ($title); } ?>" >
</label>
<label for="message">Message:
<textarea id="message" name="message" rows="20" cols="30" maxlength="50" value="<?php if (isset($message)) { echo htmlentities ($message); } ?>" ></textarea>
</label>
</fieldset>
<input id="send" type="submit" value="Send">
</form>
</div>
</body>
</html>
If you haven't thrown the computer out the window already, you should've checked whether $_POST vars were set or not before passing them to a PDO execute statement.
<?php
require 'connect.inc.php';
if( isset($_POST['title'], $_POST['message']) ) {
$db = new DB('blogdata');
$stmt = $db->prepare("INSERT INTO blogposts (title, message, time) VALUES (:title, :message, :time)");
$stmt->bindParam(':title', $_POST['title']);
$stmt->bindParam(':message', $_POST['message']);
$stmt->bindParam(':time', $time);
$title = $_POST['title'];
$message = $_POST['message'];
$stmt->execute();
}
?>
PS
I have no idea what $time would do there.

Am I proceeding with coding an edit and delete feature correctly in php/mysql, phpMyAdmin

I am working on adding a edit and delete feature to my basic blog app. I am struggling with having the my edit.php code and delete.php code process correctly.
When a person clicks on the delete or edit button the code in the correlating php file does not process.
Main PHP file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div id="container">
<h1>Lay Down Your Thoughts</h1>
<div id="boxtop"></div>
<div id="content">
<!-- form to leave a message -->
<form action="<?php $self ?>" method="post">
<h2>Post your thought!</h2>
<div class="fname"><label for="name"><p>Name:</p></label><input name="name" type="text" cols="20" /></div>
<div class="femail"><label for="email"><p>Email:</p></label><input name="email" type="text" cols="20" /></div>
<label for="message"><p>Message:</p></label>
<textarea name="post" rows="5" cols="40"></textarea>
<input name="send" type="hidden" />
<p><input type="submit" value="send" /></p>
</form>
<?php
$self = $_SERVER['PHP_SELF']; //the $self variable equals this file
$ipaddress = ("$_SERVER[REMOTE_ADDR]"); //the $ipaddress var equals users IP
include ('db.php');
// checks the POST to see if something has been submitted
if(isset($_POST['send']))
if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['post'])) {
echo('<p class="error">You did not fill in a required field.</p>');
} else {
// if there are no empty fields, insert into the database:
//validate through htmlspecialchars()
// eliminates the user from submitting harmful html
// also runs through mysql_real_escape_string()
// stops users sending SQL code to infiltrate the db
$name = htmlspecialchars(mysql_real_escape_string($_POST['name']));
$email = htmlspecialchars(mysql_real_escape_string($_POST['email']));
$post = htmlspecialchars(mysql_real_escape_string($_POST['post']));
// this is our SQL string to insert shouts into db
$sql = "INSERT INTO messages SET name='$name', email='$email', post='$post', ipaddress='$ipaddress';";
// run the SQL string
// if it succeeds, display message
if (#mysql_query($sql)) {
echo('<p class="success">message has been posted</p>');
} else {
// if error, send message
echo('<p class="error">There was an unexpected error when posting your message.</p>');
}
}
// display 8 latest messages
$query = "SELECT * FROM messages ORDER BY `id` DESC LIMIT 8;";
// run query if it fails display fail
$result = #mysql_query("$query") or die('<p class="error">There was an unexpected error collecting messages.</p>');
?><ul><?
// display the rows from the post
while ($row = mysql_fetch_array($result)) {
$ename = stripslashes($row['name']);
$eemail = stripslashes($row['email']);
$epost = stripslashes($row['post']);
// gravatar image
$grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5(strtolower($eemail))."&size=70";
echo('<li><div class="meta"><img src="'.$grav_url.'" alt="Gravatar" /><p>'.$ename.'</p></div><div class="message"><p>'.$epost.'</p></div></li>');
echo ('<form action="messageME_final_delete.php" method="post"><input name="delete" type="hidden" /> <p><input type="submit" value="delete" /></p></form>');
echo('<form action="messageME_final_update.php" method="post"><input name="edit" type="hidden" /> <p><input type="submit" value="edit" /></p></form>');
}
?></ul><?
?>
</div><!--/content-->
<div id="boxbot"></div>
</div><!--/container-->
</body>
</html>
Here is the Edit php file:
<form action="messageME_final_update.php" method="post">
<h2>Edit this Thought!</h2>
<div class="fname"><label for="name"><p>Name:</p></label><input name="name" type="text" cols="20" /></div>
<div class="femail"><label for="email"><p>Email:</p></label><input name="email" type="text" cols="20" /></div>
<label for="message"><p>Message:</p></label>
<textarea name="post" rows="5" cols="40"></textarea>
<input name="send" type="hidden" />
<p><input type="submit" value="send" /></p>
</form>
<?
include ('db.php');
$query="UPDATE messages SET name='name', email='email', post='post' WHERE id='ID'";
mysql_query($query);
echo "Record Updated";
mysql_close();
?>
finally here is the delete php code:
<?php
include ('db.php');
$sql = "DELETE FROM `messages` WHERE `ID` =" ." mysql_real_escape_string ( $_GET['ID'] )";
mysql_select_db ( $database, $connect );
if ( #mysql_query ( $sql ) )
{
echo 'Article ID = ' . $_POST['ID'];
echo ' was deleted successfully';
}
else {
die ( mysql_error () );
}
?>
Your update page has no code related to identifying what post the user wants to edit at all. It just presents a new form and tries to update a row with an ID of the string 'ID'.
Your delete page tries to access both $_GET['ID'] and $_POST['ID'], which won't ever both be set since an HTTP request is always of a single method (GET, or POST, or HEAD, etc). You also fail to concatenate the string with a function correctly, instead sending the literal text "mysql_real_escape_string(..." as part of the query, which will not run.
$sql = "DELETE FROM messages WHERE ID = " . (int)$_POST['ID'];
...is closer to what you want, except that your form on the post list does not contain an element named ID. You should create one, and populate it with the ID of the post that row corresponds to.
<input type="hidden" name="ID" value="<?php echo $row['ID']; ?>" />
Do the same for the form pointing to the edit page, and use $_POST['ID'] to look up the post and populate the form fields for editing.
Suggested reading, which will walk you through building all aspects of a CMS in PHP/MySQL:
http://www.amazon.com/Build-Database-Driven-Using-MySQL/dp/0980576814/ref=dp_ob_title_bk

Categories