I'm not familiar with ajax and I'm trying to submit a form using one PHP page and ajax so that after form is submitted/updated the page doesn't refresh completly. the php page is loaded on a div section of a parent page.
Can someone point me in the right direction how to submit the form without refreshing the entire page?
Below the code I have so far, and it is only all in one php file. Thank you
<?php
$servername = "data";
$username = "data";
$password = "data";
$database = "data";
$successAdd="";
$errorAdd="";
$connect = mysql_connect($servername, $username, $password) or die("Not Connected");
mysql_select_db($database) or die("not selected");
if (isset($_POST['Add'])) {
$venueName = $_POST['cname'];
$file = $_FILES['file'];
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array('png');
if (in_array($file_ext, $allowed)) {
if ($file_error == 0) {
$file_name_new = $venueName . '.' . $file_ext;
$file_destination = 'images/category/' . $file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$sql = "INSERT INTO `categorytable`(`category`) VALUES ('$venueName')";
$result = mysql_query($sql, $connect);
if ($result != 0) {
$successAdd = "Success fully done";
} else {
$errorAdd = "Not done ";
}
}
} else {
$errorAdd = "Something is wrong";
}
} else {
$errorAdd = "Only png file allowed";
}
}
if (isset($_POST['Update'])) {
$venueName = $_POST['cname'];
$file = $_FILES['file'];
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array('png');
if (in_array($file_ext, $allowed)) {
if ($file_error == 0) {
$file_name_new = $venueName . '.' . $file_ext;
$file_destination = 'images/category/' . $file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$successAdd = "Success fully done";
}else{
$errorAdd = "Not Updated";
}
} else {
$errorAdd = "Something is wrong";
}
} else {
$errorAdd = "Only png file allowed";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<h3 style="color: red"><?php echo $errorAdd; ?></h3>
<h3 style="color: green"><?php echo $successAdd; ?></h3>
<!--<div style="float: left;width: 50%">-->
<h1>Add Category</h1>
<form action="" method="POST" enctype="multipart/form-data" id="add-category" >
Category Name <input type="text" name="cname" value="" /><br/>
Category Image <input type="file" name="file" accept="image/x-png"/><br/>
<input type="submit" value="Add" name="Add"/>
</form>
<!--</div>-->
<!--<div style="float: left;width: 50%">-->
<h1>Update Category</h1>
<form action="addCategory.php" method="POST" enctype="multipart/form-data" >
Select Category<select name="cname">
<?php
$sql = "SELECT * FROM `categorytable`";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
?>
<option value="<?php echo $row[1]; ?>"><?php echo $row[1]; ?></option>
<?php } ?>
</select><br/>
Category Image <input type="file" name="file" accept="image/x-png"/><br/>
<input type="submit" value="Update" name="Update"/>
</form>
<!--</div>-->
<div style="width: 25%;margin: 20px auto;float: left">
<table border="1">
<tr>
<th>Category Name</th>
<th>Category Image</th>
</tr>
<?php
$sql = "SELECT * FROM `categorytable`";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
?>
<tr>
<td><?php echo $row[1]; ?></td>
<td>
<img src="images/category/<?php echo $row[1]; ?>.png" height="50"/>
</td>
</tr>
<?php
}
?>
</table>
</div>
</body>
First things first, swap to PDO, ASAP. This will save you TONS of time and can help with SQL execution time, when used correctly (You can find a quick PDO tutorial here). To answer question, I would recommend you start with importing the jQuery library. It allows near effortless manipulation of the DOM.
Then, just do something like
$('#your-form-id-here').submit(function(clickEvent){
$.ajax({
url: 'http://www.foo.com/',
data: $('#your-form-id-here').serialize(),
method: 'POST',
success: function(Response){
//If the request is successful, this code gets executed
},
error: function(){
//If the request failed, this code gets executed
}
});
return false; <----This prevents the page from refreshing
});
Now lets break it down a bit
data: $('#your-form-id-here).serialize() <-- This gets all of your form data ready
NOTE: There's way more to it than this. You'll need to do some server-side stuff to make this work right. For instance, if you want a JSON object back, you'll need to return it. In php, I like to do something like
if(My request succeeded){
echo(json_encode(array(
'status' => 'success',
'message' => 'Request description/whatever you want here'
)));
}
Related
I have a very weird problem in my system. I already create a system to upload the image to the database and display it. The problem is, the image is successfully uploaded but, it will return the message "Failed to upload!". Then, the picture that had been uploaded does not display. Below is my code:
<body>
<div class="wrapperDiv">
<form action="" method="post" id="form" enctype="multipart/form-data">
Upload image :
<input type="file" name="uploadFile" value="" />
<input type="submit" name="submitBtn" value="Upload" />
</form>
<?php
$last_insert_id = null;
include('db2.php');
if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn'])) {
if(isset($_FILES['uploadFile']['name']) && !empty($_FILES['uploadFile']['name'])) {
//Allowed file type
$allowed_extensions = array("jpg","jpeg","png","gif");
//File extension
$ext = strtolower(pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION));
//Check extension
if(in_array($ext, $allowed_extensions)) {
//Convert image to base64
$encoded_image = base64_encode(file_get_contents($_FILES['uploadFile']['tmp_name']));
$encoded_image = $encoded_image;
$query = "INSERT INTO tbl_images SET encoded_image = '".$encoded_image."'";
$sql = $conn->prepare($query);
$sql -> execute();
//$results = $sql -> fetchAll(PDO::FETCH_OBJ);
echo "File name : " . $_FILES['uploadFile']['name'];
echo "<br>";
if($sql->rowCount() > 1 ) {
echo "Status : Uploaded";
$last_insert_id = $conn-> lastInsertId();
} else {
echo "Status : Failed to upload!";
}
} else {
echo "File not allowed";
}
}
if($last_insert_id) {
$query = "SELECT encoded_image FROM tbl_images WHERE id= ". $last_insert_id;
$sql = $conn->prepare($query);
$sql -> execute();
if($sql->rowCount($sql) == 1 ) {
//$row = mysqli_fetch_object($result);
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
echo "<br><br>";
echo '<img src="'.$row->encoded_image.'" width="250">';
}
}
}
}
?>
</div>
</body>
Can someone help me? Thanks!
you doing some thing wrong first you encoded the image when store in database so you must decode it again, and the src in tag get a url not image content just echo the content like this:
header('Content-type: image/jpeg');
echo base64_decode($row->encoded_image);
or
<img src="data:image/png;base64,'.$row->encoded_image.'" width="250">
but at all, store images in database is not a good option, your database become too heavy and can't respond fast and get too memory you can just store the image name in database and move the file form special place in your server the you can show like this.
echo '<img src="specialRoot/'.$row->image_name.'" width="250">';
Store images in folder..
I have created uploads folder in root, you can create folder at anywhere and write your path while fetching the image..
<body>
<div class="wrapperDiv">
<form action="" method="post" id="form" enctype="multipart/form-data">
Upload image :
<input type="file" name="uploadFile" value="" />
<input type="submit" name="submitBtn" value="Upload" />
</form>
<?php
$last_insert_id = null;
include('db2.php');
if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn'])) {
if(isset($_FILES['uploadFile']['name']) && !empty($_FILES['uploadFile']['name'])) {
//Allowed file type
$allowed_extensions = array("jpg","jpeg","png","gif");
$name = $_FILES['uploadFile']['name'];
$target_dir = "uploads/"; //give path of your folder where images are stored.
$target_file = $target_dir . basename($_FILES["uploadFile"]["name"]);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
//Check extension
if( in_array($imageFileType,$allowed_extensions) ){
//Convert image to base64
$image_base64 = base64_encode(file_get_contents($_FILES['uploadFile']['tmp_name']) );
$encoded_image = 'data:image/'.$imageFileType.';base64,'.$image_base64;
//$encoded_image = base64_encode($_FILES['uploadFile']['tmp_name']);
//$encoded_image = $encoded_image;
$query = "INSERT INTO tbl_images SET encoded_image = '".$encoded_image."'";
$sql = $conn->prepare($query);
$result = $sql -> execute();
move_uploaded_file($_FILES['uploadFile']['tmp_name'],$target_dir.$name);
echo "File name : " . $_FILES['uploadFile']['name'];
echo "<br>";
if($result == 1) {
echo "Status : Uploaded";
$last_insert_id = $conn->insert_id;
} else {
echo "Status : Failed to upload!";
}
} else {
echo "File not allowed";
}
}
if($last_insert_id) {
$query = "SELECT encoded_image FROM tbl_images WHERE id= ". $last_insert_id;
$result = $conn->query($query);
while($row = $result->fetch_assoc()){
echo '<img src="'.$row['encoded_image'].'" width="250">';
}
}
}
?>
</div>
</body>
I have created a form and wanted to store all the information in PHPMyAdmin. I managed to store the other information but not the image file. It has nothing under the image column in PHPMyAdmin even though it states submitted when I submit the form.
form2.php
<!DOCTYPE html>
<html>
<head>
</head>
<h1>Found Items Handover</h1>
<br>
<div class="container">
<div class="row">
<h2>1. Details of Handover Personnel </h2>
</div>
<form action="insert2.php" method="post" enctype="multipart/form-data">
<div class="row input-container">
<div class="col-md-6 col-sm-12">
<div class="styled-input">
<input type="text" name="name"required />
<label>Staff Name</label>
</div>
</div>
<div class="col-md-6 col-sm-12">
<div class="styled-input" style="float:right;">
<input type="text" name="staffno" required />
<label>Staff Number</label>
</div>
</div> <br>
<div>
<label>Attachment:</label><input type='file' name='file'><br>
</div>
</div>
<br><input type="submit" name="submit" value="submit">
</form>
inser2.php
<?php
$con= mysqli_connect('127.0.0.1','root','','satsform1');
if(!$con)
{
echo 'Not Connected To Server';
}
if(!mysqli_select_db($con,'satsform1'))
{
echo 'Database Not Selected';
}
$name = $_POST['name'];
$staffno = $_POST['staffno'];
$sql = "INSERT INTO handover (name,staffno)
VALUES ('$name','$staffno')";
if(isset($_POST['submit'])){
$name = $_FILES['file']['name'];
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
// Select file type
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Valid file extensions
$extensions_arr = array("jpg","jpeg","png","gif");
// Check extension
if( in_array($imageFileType,$extensions_arr) ){
// Insert record
$query = "insert into images(name) values('".$name."')";
mysqli_query($con,$query);
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$name);
}
}
if(!mysqli_query($con,$sql))
{
echo 'Not Submitted';
}
else
{
echo 'Submitted';
}
?>
I expect the URL of the image to be stored in PHPMyAdmin when I submit the form.
please insert following code in insert2.php file with your respective variable and file names.
<?php
$con= mysqli_connect('localhost','root','','join');
if(!$con)
{
echo 'Not Connected To Server';
}
if(!mysqli_select_db($con,'join'))
{
echo 'Database Not Selected';
}
$target_dir = "uploads/";
echo "<br>";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
echo "<br>";
$name = $_POST['name'];
$staffno = $_POST['staffno'];
// get details of the uploaded file
$fileTmpPath = $_FILES['file']['tmp_name'];
$fileName = $_FILES['file']['name'];
$fileSize = $_FILES['file']['size'];
$fileType = $_FILES['file']['type'];
$fileNameCmps = explode(".", $fileName);
$fileExtension = strtolower(end($fileNameCmps));
$allowedfileExtensions = array('jpg', 'gif', 'png','jpeg');
if (in_array($fileExtension, $allowedfileExtensions)) {
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) {
echo "File uploaded successfully!";
$query = "INSERT INTO user (image)
VALUES ('$target_file')";
mysqli_query($con,$query);
if(!mysqli_query($con,$query))
{
echo 'Not Submitted';
}
else
{
echo 'Submitted';
}
} else{
echo "Sorry, file not uploaded, please try again!";
}
}
?>
I wrote the code thrice before coming here. Each time I got the same problem: The profile image does not change from the default placeholder to the new uploaded image. Here is the index.php file:
<?php
session_start();
$conn = mysqli_connect("localhost", "root", "", "imgupload");
?>
<!DOCTYPE html><html><head></head><body>
<?php
$sql_user = "SELECT * FROM user";
$result = mysqli_query($conn, $sql_user);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id']; //gets the id of the user just selected from the database
$sql_img = "SELECT * FROM profileimg WHERE userid='$id'"; //check if we actually have a profile image uploaded from this user
$resultImg = mysqli_query($conn, $sql_img); //check what the status is of this user in the image table
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
echo "<div class='user-container'>"; //check image status: uploaded or not uploaded
if ($rowImg['status'] == 0) {
echo "<img src='uploads/profile".$id.".jpg'>";
} else {
echo "<img src='uploads/profiledefault.jpg'>";
}
echo "<p>".$row['username']."</p>";
echo "</div>";
}
}
} else {
echo "There are no users yet!";
}
if (isset($_SESSION['id'])) {
if ($_SESSION['id'] == 1) {
echo "You are logged in as user #1";
}
echo "<form action='upload.php' method='POST' enctype='multipart/form-data'>
<input type='file' name='file'>
<button type='submit' name='submit'>UPLOAD</button>
</form>";
} else {
echo "You are not logged in!";
echo "<form action='signup.php' method='POST'>
<input type='text' name='first' placeholder='First name'>
<input type='text' name='last' placeholder='Last name'>
<input type='text' name='uid' placeholder='Username'>
<input type='password' name='pwd' placeholder='Password'>
<button type='submit' name='submitSignup'>Signup</button>
</form>";
}
?>
<p>Login as Admin</p><form action="login.php" method="POST"><button type="submit" name="submitLogin">Login</button></form><p>Logout</p>
<form action="logout.php" method="POST"><button type="submit" name="submitLogout">Logout</button></form></body></html>
And here is the upload.php file:
<?php
session_start();
$conn = mysqli_connect("localhost", "root", "", "imgupload");
$id = $_SESSION['id'];
if (isset($_POST['submit'])) {
$file = $_FILES['file'];
$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];
$fileExt = explode('.', $fileName); //returns an array of data
$fileActualExt = strtolower(end($fileExt)); //returns the last item in the array then lowercases it
$allowed = array('jpg', 'jpeg', 'png', 'pdf');
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if ($fileSize < 1000000) {
$fileNameNew = "profile".$id.".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
$sql = "UPDATE profileimg SET status=0 WHERE userid='$id';";
$result = mysqli_query($conn, $sql);
header("Location: index.php?uploadsuccess");
} else {
echo "Your file is too big!";
}
} else {
echo "There was an error uploading your file!";
}
} else {
echo "You cannot upload files of this type!";
}
}
I doubt there's anything wrong in the signup.php file. Why won't the profile image change when I upload?
I don't see you set $_SESSION ["id"] . I think $ _SESSION ["id"] duplicate and
$fileNameNew = "profile".$id.".".$fileActualExt;
$fileNameNew can be as "profile1.jpg", if profile1.jpg already exists then you cannot add file profile1.jpg to upload folder
I am new to PHP and MySQL and in 2 chapters of Kevin Yank's book - PHP & MySQL Novice to Ninja there are mistakes in the code. The only one I haven't figured out lies in chapter 12, and having tried suggestions from multiple posts on this and other fora, nothing works. Thanks to in advance for your help
Problem: Blob gives problem to load:
The image "http://localhost/chapter12/filestore5/index.php?action=view&id=5" cannot be displayed because it contains errors
All other functions: upload, description, delete works perfectly.
index.php file
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/magicquotes.inc.php';
if (isset($_POST['action']) and $_POST['action'] == 'upload') {
// Bail out if the file isn't really an upload
if (!is_uploaded_file($_FILES['upload']['tmp_name'])) {
$error = 'There was no file uploaded!';
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();
}
$uploadfile = $_FILES['upload']['tmp_name'];
$uploadname = $_FILES['upload']['name'];
$uploadtype = $_FILES['upload']['type'];
$uploaddesc = $_POST['desc'];
$uploaddata = file_get_contents($uploadfile);
include 'db.inc.php';
try {
$sql = 'INSERT INTO filestore SET
filename = :filename,
mimetype = :mimetype,
description = :description,
filedata = :filedata';
$s = $pdo->prepare($sql);
$s->bindValue(':filename', $uploadname);
$s->bindValue(':mimetype', $uploadtype);
$s->bindValue(':description', $uploaddesc);
$s->bindValue(':filedata', $uploaddata);
$s->execute();
}
catch(PDOException $e) {
$error = 'Database error storing file!';
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();
}
header('Location: .');
exit();
}
if (isset($_GET['action']) and ($_GET['action'] == 'view' or $_GET['action'] == 'download') and isset($_GET['id'])) {
include 'db.inc.php';
try {
$sql = 'SELECT filename, mimetype, filedata
FROM filestore
WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_GET['id']);
$s->execute();
}
catch(PDOException $e) {
$error = 'Database error fetching requested file.';
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();
}
$file = $s->fetch();
if (!$file) {
$error = 'File with specified ID not found in the database!';
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();
}
$filename = $file['filename'];
$mimetype = $file['mimetype'];
$filedata = $file['filedata'];
$disposition = 'inline';
if ($_GET['action'] == 'download') {
$mimetype = 'application/octet-stream';
$disposition = 'attachment';
}
// Content-type must come before Content-disposition
header('Content-length: ' . strlen($filedata));
header("Content-type: $mimetype");
header("Content-disposition: $disposition; filename=$filename");
echo $filedata;
exit();
}
if (isset($_POST['action']) and $_POST['action'] == 'delete' and isset($_POST['id'])) {
include 'db.inc.php';
try {
$sql = 'DELETE FROM filestore
WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
}
catch(PDOException $e) {
$error = 'Database error deleting requested file.';
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();
}
header('Location: .');
exit();
}
include 'db.inc.php';
try {
$result = $pdo->query('SELECT id, filename, mimetype, description
FROM filestore');
}
catch(PDOException $e) {
$error = 'Database error fetching stored files.';
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();
}
$files = array();
foreach($result as $row) {
$files[] = array(
'id' => $row['id'],
'filename' => $row['filename'],
'mimetype' => $row['mimetype'],
'description' => $row['description']
);
}
include 'files.html.php';
?>
HTML file
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/helpers.inc.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP/MySQL File Repository</title>
</head>
<body>
<h1>PHP/MySQL File Repository</h1>
<form action="" method="post" enctype="multipart/form-data">
<div>
<label for="upload">Upload File:
<input type="file" id="upload" name="upload"></label>
</div>
<div>
<label for="desc">File Description:
<input type="text" id="desc" name="desc"
maxlength="255"></label>
</div>
<div>
<input type="hidden" name="action" value="upload">
<input type="submit" value="Upload">
</div>
</form>
<?php if (count($files) > 0): ?>
<p>The following files are stored in the database:</p>
<table>
<thead>
<tr>
<th>Filename</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<?php foreach($files as $f): ?>
<tr>
<td>
<a href="?action=view&id=<?php htmlout($f['id']); ?>
"><?php htmlout($f['filename']); ?></a>
</td>
<td><?php htmlout($f['mimetype']); ?></td>
<td><?php htmlout($f['description']); ?></td>
<td>
<form action="" method="get">
<div>
<input type="hidden" name="action"
value="download"/>
<input type="hidden" name="id"
value="<?php htmlout($f['id']); ?>"/>
<input type="submit" value="Download"/>
</div>
</form>
</td>
<td>
<form action="" method="post">
<div>
<input type="hidden" name="action" value="delete"/>
<input type="hidden" name="id"
value="<?php htmlout($f['id']); ?>"/>
<input type="submit" value="Delete"/>
</div>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</body>
</html>
Finally got back to fixing the code and found a workable solution here:
https://www.sitepoint.com/community/t/problem-using-php-to-pull-binary-files-from-a-blob-field-in-mysql/6431/16
I added in "while (#ob_end_clean());" after the magicquotes in index.php and all works well.
According to what this person found in another forum, if server has output buffering on, then it won't send the image data correctly.
I found a code from one of the questions here on SO. I wonder where I will put this code on my upload function so it will insert this line:
<?xml-stylesheet type="text/xsl" href="foreach_template.xsl"?>
before it would be uploaded on the database.
*note: I have this table on the database which has the following columns:
id - int(3)
title - varchar(50)
name - varchar(50)
type - varchar(25)
size - int(10)
content - mediumblob
*note: Also I have a folder where the xml files are uploaded
uploadprocess.php
<?php
include 'connection.php';
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$title = $_POST['title'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
//$fileName = $_FILES['userfile']['name'];
$xml = strip_tags(mysql_real_escape_string($_FILES['userfile']['name']));
$filename = strip_tags(mysql_real_escape_string(pathinfo($xml, PATHINFO_FILENAME)));
$ext = strip_tags(mysql_real_escape_string(".xml"));
$file = strip_tags(mysql_real_escape_string($filename.$ext));
$full_local_path = strip_tags(mysql_real_escape_string('../xml/images/'.$filename.$ext));
$extension = end(explode(".", $_FILES["userfile"]["name"]));
$loc = strip_tags(mysql_real_escape_string('xml/images/'));
if ($_FILES["userfile"]["type"] == "text/xml")
{
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
$query = "INSERT INTO xmltable (title, name, size, type, content) ".
"VALUES ('$title','$file', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
move_uploaded_file($_FILES["userfile"]["tmp_name"], $full_local_path);
echo "<script> alert ('upload successful'); location.href='upload.php';</script>";
}
else
{
echo "<script> alert('Invalid File Type'); history.back(); </script>";
}
}
?>
upload.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css">
<title>XML Upload</title>
</head>
<body>
<div style="font-family:verdana;padding:50px 10px 0px 0px;border:5px solid #4D4D4D;">
<form action="uploadprocess.php" enctype="multipart/form-data" method="post">
<center>
<p>
TITLE OF THE ARTICLE <input name="title" type="text" id="title" /><br /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile" />
<input name="upload" type="submit" class="box" id="upload" value=" Upload ">
</p>
</center>
</div>
<br />
<div>
<table border="1" align="center">
<tr>
<td align="center" width="100px">ID</td>
<td align="center" width="100px">TITLE</td>
<td align="center" width="100px">LINK</td>
</tr>
<?php
include ('connection.php');
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$resultsPerPage = 5;
$startResults = ($page - 1) * $resultsPerPage;
$numberOfRows = mysql_num_rows(mysql_query('SELECT id FROM xmltable'));
$totalPages = ceil($numberOfRows / $resultsPerPage);
$query = mysql_query("SELECT * FROM xmltable LIMIT $startResults, $resultsPerPage");
while ($output = mysql_fetch_assoc($query))
{
echo "<tr><td>".$output['id']."</td>";
echo "<td>".$output['title']."</td>";
echo "<td>";
?>
<a class="del" href="/xml/images/<?php echo $output['name']; ?>" class="del">View Article</a>
</td></tr>
<?php
}
?>
</div>
<div id="pagination">
<div id="pagiCount">
<center>
<?php
echo '<span id="prev"> | First |</span>';
if ($page > 1)
{
echo '<span id="prev"> <a href="?page='.($page - 1).'">| Prev |';
}
for($i = 1; $i <= $totalPages; $i++)
{
if($i == $page)
echo '<strong>'.$i.'</strong>';
else
echo ''.$i.'';
}
if ($page < $totalPages)
echo '<span id="next"> | Next |</span>';
echo '| Last |';
?>
</center>
</div>
</div>
</table>
</form>
</body>
and view.php
<?php
include 'connection.php';
$name=$_GET['name'];
$sql="SELECT * FROM xmltable WHERE name = '$name'";
$rs=mysql_query($sql);
if (!$rs)
{
echo "failed to connect";
}
else
{
while($row = mysql_fetch_array($rs))
{
show_source("images/".$row['name']);
}
}
?>
Where can I put this code? And is it correct?
$dom = new DOMDocument();
$dom->loadXml('<?xml version="1.0" encoding="UTF-8" ?><root/>');
$dom->insertBefore($dom->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="foreach_template.xsl"'), $dom->documentElement);
echo $dom->saveXml();
Sorry if you find it long to read. Please help. Thank You!
<?php
include 'connection.php';
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
//$fileName = $_FILES['userfile']['name'];
if ($_FILES['userfile']['type'] == 'text/xsl')
{
echo "<script> alert('Invalid File Type'); history.back(); </script>";
}
else if($_FILES['userfile']['type'] != 'text/xml')
{
echo "<script> alert('Invalid File Type'); history.back(); </script>";
}
else
{
$userfile = strip_tags(mysql_real_escape_string($_FILES['userfile']['name']));
$filename = strip_tags(mysql_real_escape_string(pathinfo($userfile, PATHINFO_FILENAME)));
$ext = strip_tags(mysql_real_escape_string(".xml"));
$extension = end(explode(".", $_FILES["userfile"]["name"]));
$loc = strip_tags(mysql_real_escape_string('xml/images/'));
$xslt = strip_tags(mysql_real_escape_string($filename.$ext));
$xml = new DOMDocument('1.0', 'utf-8');
$xml->load($tmpName);
$xml->insertBefore($xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="xsl/foreach_template.xsl"'), $xml->documentElement);
$xml->formatOutput = true;
$xml->saveXml();
$xml->save($tmpName);
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
print_r($tmpName);
var_dump($tmpName);
$full_local_path = strip_tags(mysql_real_escape_string('../xml/images/'.$filename.$ext));
move_uploaded_file($tmpName, $full_local_path);
$query = "INSERT INTO xmltable (name, size, type, content) "."VALUES ('$xslt', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
echo "<script> alert ('upload successful'); location.href='upload.php';</script>";
}
}
?>