Im trying to create a way to upload images to a page but when i load the page i get the following result: Result
Why arent the images showing up? im cofused.
I have been hours trying to find the solution but i end up in the same place.
Code:
<?php
// Create database connection
include ('config.php');
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = $_FILES['IMG_Link']['IMG_Name'];
// Get text
$image_text = mysqli_real_escape_string($link, $_POST['IMG_Name']);
// image file directory
$target = "GenFeed/".basename($image);
$sql = "INSERT INTO GenFeed (IMG_Link, IMG_Name) VALUES ('$image', '$image_text')";
// execute query
mysqli_query($link, $sql);
if (move_uploaded_file($_FILES['IMG_Link']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
$result = mysqli_query($link, "SELECT * FROM GenFeed");
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
<style type="text/css">
#content{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}
</style>
</head>
<body>
<div id="content">
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
echo "<img src='GenFeed/".$row['IMG_Link']."' >";
echo "<p>".$row['IMG_Name']."</p>";
echo "</div>";
}
?>
<form method="POST" action="ImageUpload.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="IMG_Link">
</div>
<div>
<textarea
id="text"
cols="40"
rows="4"
name="IMG_Name"
placeholder="Say something about this image..."></textarea>
</div>
<div>
<button type="submit" name="upload">POST</button>
</div>
</form>
</div>
</body>
</html>
Hope you guys can help me out on this one
PD: im aware the im using superglobal variables
Related
I have a simple chat website, and I'm trying to add a profile-picture feature. This is my code:
<?php
function loginForm(){
echo
'<div id="loginform">
<p>Please enter your name to continue!</p>
<form action="index.php" method="post">
<label for="name">Display Name: </label>
<input style="font-family: Sans-serif;" type="text" name="name" id="name" />
<label for="name">Profile picture: </label>
<input style="font-family: Sans-serif;" type="text" name="pfp" id="name" />
<input style="font-family: Sans-serif;" type="submit" name="enter" id="enter" value="Enter" />
</form>
</div>
<center><h2>Upload profile picture: </h2><br><?php error_reporting(0); ?> <?php $msg = ""; if (isset($_POST[\'uploadfile\'])) { $filename = $_FILES["choosefile"]["name"]; $tempname = $_FILES["choosefile"]["tmp_name"]; $folder = "image/".$filename; $_SESSION[\'pfp\'] = $folder; $db = mysqli_connect("localhost", "root", "", "Image_upload"); $sql = "INSERT INTO image (filename) VALUES (\'$filename\')"; ($db, $sql); if (move_uploaded_file($tempname, $folder)) { $msg = "Image uploaded successfully"; }else{ $msg = "Failed to upload image"; } } $result = mysqli_query($db, "SELECT * FROM image"); ?> <!DOCTYPE html> <html> <!DOCTYPE html> <html> <head> <title>Image Upload in PHP</title> <! link the css file to style the form > <style type="text/css"> #wrapper{ width: 50%; margin: 20px auto; } form{ width: 50%; margin: 20px auto; } form div{ margin-top: 5px; } img{ float: left; margin: 5px; width: 280px; height: 120px; } #img_div{ width: 70%; padding: 5px; margin: 15px auto; border: 1px solid #dad7d7; } #img_div:after{ content: ""; display: block; clear: both; } button, input, span { background: #41d18e; border: none; color: white; padding: 4px 10px; font-weight: bold; border-radius: 20px; } </style> </head> <body> <div id="wrapper"> <! specify the encoding type of the form using the enctype attribute > <form method="POST" action="" enctype="multipart/form-data"> <input type="file" name="choosefile" value="" /> <div> <button type="submit" name="uploadfile">Use as new profile pic</button> </div> </form> </div></center>';
}
?>
<div id="menu">
<?php echo "<img style=\"width: 20px; border-radius: 9999px;\" src=".$_SESSION['pfp'].">"; ?>
<p class="welcome"> Welcome, <b><?php echo $_SESSION['name']; ?></b></p>
<p class="logout"><a id="exit" href="#">Rename</a></p>
</div>
For some reason <p class="welcome"></p> works perfectly fine, but the image just doesn't show. I looked in my image folder but could not find the image that I uploaded earlier.
Thanks for all the support.
replace the line and see
"<img style="width:20px;",src=<?php echo $_SESSION['pfp'];?>"
his maybe the issue: Change so the image link/location is properly surrounded in quotes in the outputted html.
I have written a PHP code to upload files from the azure web app (using an upload button from a browser) to azure blob container. I am successfully able to upload the files to the blob container, however, once uploaded the file sits in azure blob as 0 bytes without any extension. I am unable to view the file as well and the following message is shown 'The file '1721405003' may not render correctly as it contains an unrecognized extension'.
Below is my php code to upload files to blob -
<?php
error_reporting(0);
?>
<?php
require_once "vendor/autoload.php";
use MicrosoftAzure\Storage\Blob\BlobRestProxy;
use MicrosoftAzure\Storage\Common\ServiceException;
use WindowsAzure\Common\ServicesBuilder;
// If upload button is clicked ...
if (isset($_POST['upload'])) {
//upload to azure blob container
$connectionString = "conn key"; //Enter deployment key
$containerName = 'sidblobcontainer';
$blobClient = BlobRestProxy::createBlobService($connectionString);
$file_name = $_FILES['myFile']['name'];
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$content = fopen($file_name, "r");
$blob_name = "myblob".'.'.$ext;
try {
//Upload blob
$blobClient->createBlockBlob($containerName, $blob_name, $content);
echo "successfull";
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message.PHP_EOL;
}
//upload to azure mysql database server
$filename = $_FILES["myFile"]["name"];
$tempname = $_FILES["myFile"]["tmp_name"];
$folder = "image/".$filename;
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = mysqli_connect("demoserversid.mysql.database.azure.com",
"siddarth#demoserversid", "****", "images");
// Get all the submitted data from the form
$sql = "INSERT INTO demo (siddemo) VALUES ('$filename')";
// Execute query
mysqli_query($db, $sql);
// Now let's move the uploaded image into the folder: image
if (move_uploaded_file($tempname, $folder)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
$result = mysqli_query($db, "SELECT * FROM demo");
?>
<!DOCTYPE html>
<html>
<head>
<style> #content{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}</style>
<title>Image Upload</title>
<body>Upload to azure</body>
<link rel="stylesheet" type= "text/css" href ="style.css"/>
<div id="content">
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="uploadfile" value=""/>
<div>
<button type="submit" name="upload">UPLOAD</button>
</div>
</form>
</div>
</body>
</html>
Here is the message that I see in blob container
I removed the part that related to mysql and the code below works for me:
<?php
error_reporting(0);
?>
<?php
require_once "vendor/autoload.php";
use MicrosoftAzure\Storage\Blob\BlobRestProxy;
use MicrosoftAzure\Storage\Common\ServiceException;
use WindowsAzure\Common\ServicesBuilder;
// If upload button is clicked ...
if (isset($_POST['upload'])) {
$connectionString = "<conn str>"; //Enter deployment key
$containerName = '<container name>';
$blobClient = BlobRestProxy::createBlobService($connectionString);
$file_name = $_FILES['fileToUpload']['name'];
error_log($file_name);
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$content = fopen($_FILES['fileToUpload']["tmp_name"], "r");
$blob_name = "myblob".'.'.$ext;
try {
//Upload blob
$blobClient->createBlockBlob($containerName, $blob_name, $content);
echo "successfull";
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message.PHP_EOL;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<style> #content{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}</style>
<title>Image Upload</title>
<body>Upload to azure</body>
<link rel="stylesheet" type= "text/css" href ="style.css"/>
<div id="content">
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload"/>
<div>
<button type="submit" name="upload">UPLOAD</button>
</div>
</form>
</div>
</body>
</html>
Result:
I am trying to make image show permanent on refreshing.
The image should be constant. We can add images and text permanent and we can add more posts.
A database called image_upload and create a table called images with fields:
id - int(11)
image - varchar(100)
image_text - text
index.php
<?php
// Create database connection
$db = mysqli_connect("localhost", "root", "", "image_upload");
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = $_FILES['image']['name'];
// Get text
$image_text = mysqli_real_escape_string($db, $_POST['image_text']);
// image file directory
$target = "images/".basename($image);
$sql = "INSERT INTO images (image, image_text) VALUES ('$image', '$image_text')";
// execute query
mysqli_query($db, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
$result = mysqli_query($db, "SELECT * FROM images");
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
<style type="text/css">
#content{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}
</style>
</head>
<body>
<div id="content">
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
echo "<img src='images/".$row['image']."' >";
echo "<p>".$row['image_text']."</p>";
echo "</div>";
}
?>
<form method="POST" action="index.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea
id="text"
cols="40"
rows="4"
name="image_text"
placeholder="Say something about this image..."></textarea>
</div>
<div>
<button type="submit" name="upload">POST</button>
</div>
</form>
</div>
</body>
</html>
Help me How to solve this problem. I have created database and uploading images and text. while refreshing page. The posts is repeating after and after.
It now works. Tested. For over two hours I was baffled why the page could not redirect after successful upload. Undoing some indentations at the top of the page solved the problem.
<?php
session_start();
// Create database connection
$db = mysqli_connect("localhost", "root", "", "image_upload");
if(isset($_POST['image_text'])){
// Get text
$image_text = mysqli_real_escape_string($db, $_POST['image_text']);
}
if(isset($_FILES['image'])){
// Get image name
$image = $_FILES['image']['name'];
$tempath = $_FILES['image']['tmp_name'];
}
// If upload button is clicked ...
if(isset($_POST['upload'])){
if(isset($image) && isset($tempath) && !empty($image)){
$image = time()."_".$image;
$image_folder = "images/";
if(is_uploaded_file($tempath)){
if(move_uploaded_file($tempath, $image_folder.$image)) {
$image_uploaded = true;
}
}
}else{
$msg = "Failed to upload image";
}
if(isset($image_uploaded) && ($image_uploaded == true)){
$sql = "INSERT INTO images (image, image_text) VALUES('$image', '$image_text')";
// execute query
mysqli_query($db, $sql);
$sent = true;
$_SESSION['sent'] = "Image uploaded successfully";
}
}
if(isset($sent) && ($sent == true)){
header("Location: index.php");
exit();
}
$result = mysqli_query($db, "SELECT * FROM images");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Image Upload</title>
<style type="text/css">
#content{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}
</style>
</head>
<body>
<div id="content">
<?php
if(isset($_SESSION['sent'])){
echo "<p style='color:#006400;font-weight:bold;'>" . $_SESSION['sent'] . "</p>";
unset($_SESSION["sent"]);
}
if(isset($msg)){
echo "<p style='color:#ff0000;font-weight:bold;'>" . $msg . "</p>";
}
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
echo "<div id='img_div'>";
echo "<img src='images/".$row['image']."' >";
echo "<p>".$row['image_text']."</p>";
echo "</div>";
}
}else{
echo "<h4>No data has been uploaded</h4>";
}
?>
<form method="POST" action="index.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea
id="text"
cols="40"
rows="4"
name="image_text"
placeholder="Say something about this image..."></textarea>
</div>
<div>
<button type="submit" name="upload">POST</button>
</div>
</form>
</div>
</body>
</html>
Hopefully the following will provide guidance ~ fully working but the paths used to store images is relevant to my laptop so you'll need to edit that portion slightly.
<?php
session_start();
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$msg='Failed to upload image';
/* utility to find error if something goes wrong */
function uploaderror( $error ){
switch( $error ) {
case UPLOAD_ERR_INI_SIZE: return "The uploaded file exceeds the upload_max_filesize directive in php.ini";
case UPLOAD_ERR_FORM_SIZE: return "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
case UPLOAD_ERR_PARTIAL: return "The uploaded file was only partially uploaded";
case UPLOAD_ERR_NO_FILE: return "No file was uploaded";
case UPLOAD_ERR_NO_TMP_DIR: return "Missing a temporary folder";
case UPLOAD_ERR_CANT_WRITE: return "Failed to write file to disk";
case UPLOAD_ERR_EXTENSION: return "File upload stopped by extension";
default: return "Unknown upload error";
}
}
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_FILES['image'] ) && isset( $_POST['image_text'] ) ){
try{
/* try to filter input of bad characters though using a prepared statement should help */
$text=filter_input( INPUT_POST, 'image_text', FILTER_SANITIZE_STRING );
/* get a reference to the uploaded FILE object*/
$obj=(object)$_FILES['image'];
$name=$obj->name;
$tmp=$obj->tmp_name;
$size=$obj->size;
$error=$obj->error;
$type=$obj->type;
/* proceed to save file and log to db */
if( is_uploaded_file( $tmp ) && $error==UPLOAD_ERR_OK ){
#$destination = 'images/' . $name;
$root='c:/wwwroot';
$path='/images/tmp/';
$filepath = $path. $name;
$destination=$root . $filepath;
$status=move_uploaded_file( $tmp, $destination );
if( $status ){ /* moved/saved the file OK */
/* create a prepared statement */
$sql='insert into `images` ( `image`, `image_text`) values (?,?)';
$stmt=$db->prepare( $sql );
if( $stmt ){/* bind variables to placecholders ~ store path to image rather than just image name */
$stmt->bind_param('ss', $filepath, $text );
$status = $stmt->execute();
$stmt->close();
$msg = $status ? 'Image uploaded successfully' : 'Failed to log image to database';
}
} else {
throw new Exception('unable to move file');
}
} else {
throw new Exception( sprintf( 'error: possible file upload attack - %s',uploaderror( $error ) ) );
}
}catch( Exception $e ){
$msg = $e->getMessage();
}
}
/* fetch all image details from db */
$sql='select `image`,`image_text` from `images`;';
$result=$db->query( $sql );
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
<style>
#content{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}
</style>
</head>
<body>
<div id="content">
<?php
$i=0;
while( $row = $result->fetch_object() ) {
$i++;
/* an ID MUST be unique! */
echo "
<div class='img_div' id='img_div__$i'>
<img src='{$row->image}' />
<p>{$row->image_text}</p>
</div>";
}
?>
<form method='POST' enctype='multipart/form-data'>
<input type='hidden' name='MAX_FILE_SIZE' value='1000000' />
<div>
<input type='file' name='image' />
</div>
<div>
<textarea
id='text'
cols='40'
rows='4'
name='image_text'
placeholder='Say something about this image...'></textarea>
</div>
<div>
<button type='submit' name='upload'>POST</button>
<?php
if( !empty( $msg ) && $_SERVER['REQUEST_METHOD']=='POST' ) echo $msg;
?>
</div>
</form>
</div>
</body>
</html>
whenever i try to create a new txtfile using create button although the file get create but the data is not written into the file. i just het a blank file. what is the error ?
<?php
error_reporting(0);
if(isset($_POST['sub']))
{
$fname=$_POST["txtfile"];
$cont=$_POST['txtarea'];
if($_POST['sub']=="create")
{
fopen($fname,"w");
fwrite($fname, $cont);
}
else if($_POST['sub']=="read")
{
echo file_get_contents($fname);
}
else if($_POST['sub']=="delete")
{
unlink($fname);
}
else if($_POST['sub']=="append")
{
$cont=$_POST['txtarea'];
$fp=fopen($fname,"a");
fwrite($fp,$cont);
}
}
?>
here is the html code of above program. should i insert the php code for reading the file into the textarea code in html.?
<!DOCTYPE html>
<html>
<h3>file handling concept</h3>
<style type="text/css">
#form{
height: 200px;
width: 400px;
margin: 10px;
}
label {
float: left;
margin-right: 10px;
width: 70px;
padding-top: 5px;
font-size: 15px;
}
#form input, #form textarea{
padding: 5px;
width: 306px;
font-family: Helvetica, sans-serif;
font-size: 15px;
margin: 0px 0px 0px 0px;
border: 2px solid #ccc;
}
#button input{
float: right;
margin: 5px;
width: 60px;
padding: 5px;
border: 1px solid #ccc;
}
</style>
<div id="form">
<form method="POST" action="filehandling.php">
<label for="name">Filename:</label>
<input type="text" name="txtfile" placeholder="file-name.txt" />
<label for="name">content:</label>
<textarea name="txtarea" placeholder="write some content">
</textarea>
<div id="button">
<input type='submit' name='sub' value='create'>
<input type='submit' name='sub' value='delete'>
<input type='submit' name='sub' value='append'>
<input type='submit' name='sub' value='read'>
</div>
</form>
</div>
</html>
Your file creation and writing method should be as follows:
if($_POST['sub']=="create")
{
$fp = fopen($fname,"wb");
fwrite($fp,$cont);
fclose($fp);
}
I think you should use handle while creating the file too like below.
if($_POST['sub']=="create")
{
$fh = fopen($fname,"w");
fwrite($fh, $cont);
fclose($fh);
}
Also in else if($_POST['sub']=="append") there is no need to define $cont again as its already define with the same value.
so
else if($_POST['sub']=="append")
{
$cont=$_POST['txtarea'];
$fp=fopen($fname,"a");
fwrite($fp,$cont);
}
becomes
else if($_POST['sub']=="append")
{
$fp=fopen($fname,"a");
fwrite($fp,$cont);
fclose($fp);
}
It's my first day here, I thought you guys could help me. So, I'm working on this kind of chatting service for a friend. I want it to auto update anything inside the div tags that has an id of messages. I tried adding some javascript and stuff from other posts, but they just made it worse. So, if anyone could fix it and comment, or give me suggestions. I want it as soon as someone posted something, it updates the posts in the div tags with the id of messages.
<?php
session_start();
if(!isset($_SESSION['username']))
{
header("Location: /index.php");
}
?>
<html>
<head>
<title>
House Email System
</title>
<style>
body
{
background: #383838;
font-family: Arial;
color: #444444;
position: absolute;
top: 50%;
left: 50%;
margin-top: -75px;
margin-left: -150px;
}
form
{
background: #ffffff;
width: 270px;
border-radius: 15px;
box-shadow: 3px 3px 6px 1px #303030;
}
input
{
margin-left: 15px;
}
p
{
margin-left: 15px;
}
error
{
padding:2px 4px;
margin:0px;
border:solid 1px #FBD3C6;
background:#FDE4E1;
color:#CB4721;
font-size:14px;
font-weight:bold;
}
div
{
background: #f0f0f0;
}
hr
{
color: #d0d0d0;
background-color: #d0d0d0;
height: 3px;
border: 0px;
}
username
{
margin-left: 5px;
}
message
{
margin-left: 10px;
}
</style>
</head>
<body>
<?php
$connect = mysql_connect("localhost", "root", "*******");
mysql_select_db("*******");
$username = $_SESSION['username'];
$message = $_POST['message'];
$submit = $_POST['submit'];
if($submit)
{
if($message)
{
mysql_query("INSERT INTO messages VALUES('', '$username', '$message')");
}
else
{
?>
<center>
<error>Please enter a message to send.</error> <br />
</center>
<br />
<?php
}
}
?>
<form action="active.php" method="POST">
<br />
<p>Message</p>
<input type="text" name="message" /> <br />
<br />
<input type="submit" name="submit" value="Submit" /> <br />
<br />
<?php
$query = mysql_query("SELECT * FROM messages ORDER BY id DESC");
$num_rows = mysql_num_rows($query);
if($num_rows > 0)
{
while($row = mysql_fetch_assoc($query))
{
$username = $row['username'];
$message = $row['message'];
?>
<div id="messages">
<br /> <username><b><?php echo $username; ?></b></username>
<hr />
<message><?php echo $message; ?></message> <br />
<br /> </div> <br />
<?php
}
}
else
{
?>
<center>
<error>There are no messages to display.</error> <br />
</center>
<br />
<?php
}
?>
</form>
</body>
</html>
I hope you guys can help me, thank you.
First create a page message.php as:
<?php
session_start();
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#submit').click(function()
{
//alert("hello");
// ss=document.getElementById("message").value;
$.ajax({
type : 'POST',
url : 'active.php',
data: {
messages :$('#message').val()
},
success : function(data){
$('#messages').html(data);
}
});
});
});
</script>
<title>
House Email System
</title>
<style>
body
{
background: #383838;
font-family: Arial;
color: #444444;
position: absolute;
top: 50%;
left: 50%;
margin-top: -75px;
margin-left: -150px;
}
form
{
background: #ffffff;
width: 270px;
border-radius: 15px;
box-shadow: 3px 3px 6px 1px #303030;
}
input
{
margin-left: 15px;
}
p
{
margin-left: 15px;
}
error
{
padding:2px 4px;
margin:0px;
border:solid 1px #FBD3C6;
background:#FDE4E1;
color:#CB4721;
font-size:14px;
font-weight:bold;
}
div
{
background: #f0f0f0;
}
hr
{
color: #d0d0d0;
background-color: #d0d0d0;
height: 3px;
border: 0px;
}
username
{
margin-left: 5px;
}
message
{
margin-left: 10px;
}
</style>
</head>
<body>
<center>
<error>Please enter a message to send.</error> <br />
</center>
<br />
<form action="active.php" method="POST">
<br />
<p>Message</p>
<input type="text" name="message" id="message" /> <br />
<br />
<input type="button" id="submit" name="submit" value="Submit" /> <br />
</form>
<br />
<div id="messages">
</div>
</body>
</html>
<script language="JavaScript"><!--
// v3 compatible:
function doSomething() {
// do something here...
$.ajax({
type : 'POST',
url : 'active.php',
data: {
messages :$('#message').val()
},
success : function(data){
$('#messages').html(data);
}
});
setTimeout('doSomething()',3000);
}
setInterval('doSomething()',3000);
//--></script>
Then Create a page active.php as
<?php
session_start();
$connect = mysql_connect("localhost", "root", "");
mysql_select_db("test");
$username=$_SESSION['username'];
$message=$_POST['messages'];
if($message!="")
{
mysql_query("INSERT INTO messages VALUES('', '$username', '$message')");
}
$query = mysql_query("SELECT * FROM messages ORDER BY id DESC limit 1,0");
$num_rows = mysql_num_rows($query);
if($num_rows > 0)
{
while($row = mysql_fetch_assoc($query))
{
$username = $row['username'];
$message = $row['message'];
?>
<div>
<br /> <username><b><?php echo $username; ?></b></username>
<hr />
<message><?php echo $message; ?></message> <br />
<br /> </div>
<br />
<?php
}
}
else
{
echo"No message to show";
}
?>
This is very general chat.Now you need to change it according to your requirements.
I want it as soon as someone posted something, it updates the posts in the div tags with the id of messages.
You will have to use javacript for that part. Everything else can be done with PHP and MySQL.
I watched great youtube tutorial the other day on how to do this. Its is a "quick and dirty" solution but should give you something to build on. http://www.youtube.com/watch?v=FyXeOX-uYMc