I setup a little site for my roomate whose an artist, and I set it up where he could use an admin.php page to upload images to the site, and they are added to a MYSQL Database where the main site pulls them from and displays them.
He wants the option to remove images from the same page he adds images, so I wrote a little code to display them again and add a "remove" link to each one. I can't figure out what a good way would be to actually code the rest of it where it actually removes the image when he clicks it.
Can anyone possibly shed some light, urls, etc. that may help to get this finished? Here is what the admin.php looks like thus far...
<html>
<head><title>SethClem.com Image Management</title></head>
<body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
Image File: <input type="file" name="image" /><br />
Description: <input type="text" name ="description" ><br>
<input type="submit" value="upload" />
</form>
<?php
include("../database.php");
// Connects to your Database
mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error()) ;
mysql_select_db($dbname) or die(mysql_error()) ;
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM images") or die(mysql_error());
?>
<div style="width:100%; height:105px; border:0 ; padding:5px;">
<table><tr>
<?php
//Puts it into an array
while($info = mysql_fetch_array( $data ))
{
$image = "../images/".$info['image'];
?>
<td>
<img src="<?php echo $image ?>" style="width:191; height:124; border:0px ; float:left;" />
remove
</td>
<?php
}
?>
</tr>
</table>
</div>
$action = !empty($_GET['action'])?$_GET['action']:false;
$id = !empty($_GET['id'])?$_GET['id']:false;
switch ($action) {
case 'delete':
if ($id !== false)
{
mysql_query("delete from `images` where `id`='$id' limit 1;");
//unlink($path_to_image.'/'.$file_name);
}
break;
default:
echo 'No known action was passed through (Test Message, will be removed)';
}
replace
remove
with remove
now, put this php code imediatly after the db connection:
if( isset( $_GET['action'] ) && ( $_GET['action == 'delete' ) )
{
$id = $_GET['id'];
mysql_query("delete from `images` where `id`='$id' limit 1;");
unlink($path_to_image.'/'.$file_name);
}
Related
I have created a php script with a form that it should insert some data into database, it actually add the text and the ID but it does not add the file.
the database looks like this:
Database name: highmob_comenzi
table name: players
in table we got 3 rows:
ID (auto_increment)
name (the name that we insert from the form)
schite (where the files should be uploaded) Type: blob Colation: none , all none
this is the script what I have tried so far
<?php
include('connect-db.php');
?>
<?php
function renderForm($name, $schita, $error)
{
?>
<?php
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post" enctype="multipart/form-data" >
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<input type="hidden" name="name" value="<?php echo $name; ?>"/>
<input type="file" id="schita" name="schita" >
<button type="submit" name="submit">Add Data</button>
</form>
<?php
}
include('connect-db.php');
if (isset($_POST['submit']))
{
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$schita = mysql_real_escape_string(htmlspecialchars($_POST['schita']));
if ($name == '')
{
$error = 'Error !!';
renderForm($name, $schita, $error);
}
else
{
mysql_query("INSERT players SET name='$name', schita='$schita'")
or die(mysql_error());
header("Location: mobila.php");
}
}
else
{
renderForm('','','','','');
}
?>
This script creates a page for each ID when we insert data in the form
Like pagename.php?id=4
I want when i fill the form after he create the page when i open the page to see the uploaded file only on that page,
any idea why its not working?
Get the request file using $_FILES, also you need to confirm your mysql field (schita) is a blob type
You need to correct insert query. You are missing 'into' keyword. Change query to:
mysql_query("INSERT into players SET name='$name', schita='$schita'");
You need to convert image to base64 and then save it to Database.
// Select file type
$target_file = basename($_FILES["file"]["name"]);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Convert to base64
$image_base64 = base64_encode(file_get_contents($_FILES['schita']['tmp_name']) );
$image = 'data:image/'.$imageFileType.';base64,'.$image_base64;
// Insert record
$query = "INSERT into players(schita) values('".$image."')";
mysqli_query($con,$query);
I have managed to upload the file using this script
<?php
$dbh = new PDO("mysql:host=localhost;dbname=highmob_comenzi", "highmob", "PW");
if(isset($_POST['btns'])){
$name = $_FILES['myfile']['name'];
$type = $_FILES['myfile']['type'];
$data = file_get_contents($_FILES['myfile']['tmp_name']);
$stmt = $dbh->prepare("UPDATE players SET data='$myfile', name='$name', mime='$type' WHERE id='$id'");
$stmt->bindParam(1,$name);
$stmt->bindParam(2,$type);
$stmt->bindParam(3,$data);
$stmt->execute();
}
?>
<!-- form -->
<form method="post" enctype="multipart/form-data">
<input type="file" name="myfile"/>
<button name="btns"> Incarca Schita </button>
</form>
<!-- display data -->
<?php
$stat = $dbh->prepare("select * from players");
$stat->execute();
while($row = $stat->fetch()){
echo "<a target='_blank' href='viewschita.php?id=".$row['id']."'>".$row['name']."</a>";
}
?>
The problem is i got no idea how to make a link to the file, any idea how?
My problem is, when I upload a picture to a database, the upload is successful but the picture isn’t displayed. This is my code:
SQL file:
CREATE TABLE `images` (`id` int(11) NOT NULL auto_increment,`name` varchar(100) default NULL,`size` int(11) default NULL,`type` varchar(20) default NULL,`content` mediumblob,PRIMARY KEY (`id`)) ENGINE=MyISAM;
Index.php
<?php if (!empty($uploadOk)): ?>
<div>
<h3>Image Uploaded:</h3>
</div>
<div>
<img src="image.php?id=<?=$imageId ?>" width="150px">
<strong>Embed</strong>: <input size="25" value='<img src="image.php?id=<?=$imageId ?>">'><br>
</div>
<hr>
<? endif; ?>
<form action="index.php" method="post" enctype="multipart/form-data" >
<div>
<h3>Image Upload:</h3>
</div>
<div>
<label>Image</label>
<input type="hidden" name="MAX_FILE_SIZE" value="500000">
<input type="file" name="image" />
<input name="submit" type="submit" value="Upload"><br>
</div>
</form>
</tr>';}mysql_close();?>
image.php
<?php
// verify request id.
if (empty($_GET['id']) || !is_numeric($_GET['id'])) {
echo 'A valid image file id is required to display the image file.';
exit;
}
$imageId = $_GET['id'];
//connect to mysql database
if ($conn = mysqli_connect('localhost', 'username', 'pass', 'db_name')) {
$content = mysqli_real_escape_string($conn, $content);
$sql = "SELECT type, content FROM images where id = {$imageId}";
if ($rs = mysqli_query($conn, $sql)) {
$imageData = mysqli_fetch_array($rs, MYSQLI_ASSOC);
mysqli_free_result($rs);
} else {
echo "Error: Could not get data from mysql database. Please try again.";
}
//close mysqli connection
mysqli_close($conn);
} else {
echo "Error: Could not connect to mysql database. Please try again.";
}
if (!empty($imageData)) {
// show the image.
header("Content-type: {$imageData['type']}");
echo $imageData['content'];
} ?>
getImage.php
<?php
$id = $_GET['id'];
$link = mysql_connect("localhost", "username", "pass");
mysql_select_db("db_name");
$sql = "SELECT content FROM images WHERE id=$id";
$result = mysql_query("$sql");
$row = mysql_fetch_assoc($result);
mysql_close($link);
header("Content-type: image/jpeg");
echo $row['content'];
?>
This code worked. I think the SQL database is incorrect or has problems to display images.
In order to display the image, you should use AJAX from JavaScript.
I'm learning PHP and I've hit a wall.
When the user submits to the form, it adds to the database.
I am also trying to display all items in the database on the same page as the form.
However,this only works if the form has just been submitted. If the form has not been submitted (but there is still content in the database), nothing is shown.
How can I always show what is in the current database?
<form action="" method="post">
<input type="text" name="todo_content" id="">
<input type="submit" value="Submit">
</form>
<?php
if ( isset($_POST['todo_content'])) {
$latest_content = $_POST['todo_content'];
} else {
die();
}
$todo_db = mysqli_connect('localhost', 'root', 'root');
mysqli_select_db($todo_db, 'todo_list');
mysqli_query(
$todo_db,
"INSERT INTO todo_items (item_content) VALUES ('$latest_content')"
);
$all_todos = mysqli_query( $todo_db, "SELECT item_content FROM todo_items" );
$all_todos_result = mysqli_fetch_array($all_todos);
var_dump($all_todos_result); // these show nothing
var_dump($all_todos); // these show nothing
?>
The die() is your problem:
if ( isset($_POST['todo_content'])) {
echo 'is set';
$latest_content = $_POST['todo_content'];
} else {
die();
}
If $_POST is not set, you will never reach the part where you start printing your items. And since the form is not submitted, $_POST is empty.
EDIT
You could do it like this:
<form action="" method="post">
<input type="text" name="todo_content" id="">
<input type="submit" value="Submit">
</form>
<?php
$todo_db = mysqli_connect('localhost', 'root', 'root');
mysqli_select_db($todo_db, 'todo_list');
if ( isset($_POST['todo_content'])) {
$latest_content = $_POST['todo_content'];
mysqli_query($todo_db, "INSERT INTO todo_items (item_content) VALUES ('$latest_content')");
}
$all_todos = mysqli_query( $todo_db, "SELECT item_content FROM todo_items" );
$all_todos_result = mysqli_fetch_array($all_todos);
var_dump($all_todos_result); // these show nothing
var_dump($all_todos); // these show nothing
?>
You need to move your insert query inside your if condition and you will need not to die if the form is not submitted but print the form and your query results
$todo_db = mysqli_connect('localhost', 'root', 'root');
mysqli_select_db($todo_db, 'todo_list');
if ( isset($_POST['todo_content'])) {
echo 'is set';
$latest_content = $_POST['todo_content'];
mysqli_query($todo_db, "INSERT INTO todo_items (item_content) VALUES ('$latest_content')");
} else {
?>
<form action="" method="post">
<input type="text" name="todo_content" id="">
<input type="submit" value="Submit">
</form>
<?php
$all_todos = mysqli_query( $todo_db, "SELECT item_content FROM todo_items" );
$all_todos_result = mysqli_fetch_array($all_todos);
var_dump($all_todos_result);
var_dump($all_todos);
}
As side note i'd say you are at high risk of mysql injection. You should use prepaed statments and not inserting $_POST data inside your database directly
I am trying to implement a page where a user enters a comment and it gets displayed right in the same page. The problem i am having is that every time you go to the page there are no comments in the page(there are actually comments).
This is my sceneario i am having:
I go to the page and there are no comments, i enter a comment 'hello' and it gets displayed right away.
I go to a different page and then i come back to the comments page and there are no comments.(the comment "hello" should be already displayed)
I enter a comment "hi" and both comments "hello" and "hi" get displayed
I cant resolve this issue..
This is my code, its pretty long
<?php
session_start(); //starts or continues the session
require_once('functions.php'); //needed for some function calls
error_reporting(E_ALL ^ E_NOTICE);
?>
<!DOCTYPE html>
<html lang = "en">
<head>
<script type = "text/javascript" src = "functions.js"></script>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<?php
GetUserLayout($_SESSION['userId'], $_SESSION['superUser']);
?>
<div id = "shareyouridea_form" class = "post">
<h1> Share your post</h1>
<!-- used for the form -->
<form id = "idea_form" method = "post"
action = "<?php echo $PHP_SELF;?>"
onkeypress = "return DisableEnterKey(event);">
<table>
<caption>
<strong>
<br /> Share post form:
</strong>
</caption>
<tr class = "spacearound"> <!-- input for bright idea -->
<td> Post: </td>
<td>
<textarea form = "idea_form" name = "b_idea" rows = "12"
cols = "85" title = "Please describe your product idea"
id = "bright_idea" maxlength = "1000"
onkeypress =
"return InputLimiter(event, 'lettersSpacePunctuation');">
</textarea>
</td>
</tr>
</table>
<p>
<input type = "reset" value = "Reset" />
<input type = "submit" value = "Share Idea!"
title = "complete form first to submit"
id = "submit_button"
name = "add_comment"
onmousedown = "IsIdeaFormCompleted();" />
</p>
</form> <!-- end idea_form -->
</div>
</div> <!-- end of ShareYourIdea_middle -->
<script>
DisplayFooter();
</script>
<?php
if(isset($_POST['add_comment'])){ // if add comment was pressed
// get variables
$name = $_SESSION['firstName'];
$empId = $_SESSION['userId'];
$idea = $_POST['b_idea'];
// CONNECTING TO OUR DATABASE
$db = mysqli_connect(dbHost, dbUser, dbPassword, dbName);
if (mysqli_connect_errno()) { //if connection to the database failed
echo("<p id = 'greatideadescription'>
Connection to database failed: " .
mysqli_connect_error($db) . "</p>");
exit("goodbye");
} //by now we have connection to the database
// WE WRITE OUR QUERY TO INSERT POST INFO TO DATABASE
$query = "INSERT INTO posts(postId,empl_Id,post,postDate)
VALUES('','$empId','$idea',NOW())";
$result = mysqli_query($db, $query);
}
?>
<?php
// WE DO A QUERY TO SHOW ALL COMMENTS IN THE PAGE
$query = "SELECT firstName,lastName, post,
date_format((date_add(postDate,interval -7 hour)),'%a, %M, %d, %Y at %I:%i%p' ) as mydatefield
FROM users INNER JOIN posts ON userId = empl_Id
ORDER BY postDate DESC";
$result = mysqli_query($db,$query);
if (!$result) { //if the query failed
echo("<p id = 'greatideadescription'>
Error, the query could not be executed: " .
mysqli_error($db) . "</p>");
mysqli_close($db);}
if (mysqli_num_rows($result) == 0) { //if no rows returned
echo("<div id = 'blogs'>
<div id ='name'>
No posts detected
</div>
</div>
<div class='fb-like' data-href='http://jacobspayroll.zxq.net/index/blog.php' data-send='true' data-width='450' data-show-faces='true'></div>
");
mysqli_close($db); //close the database
exit("</table></div></form></div></div>
<script>DisplayFooter();</script></body></html>");
} //by now we know that we have some products purchases returned
$numRows = mysqli_num_rows($result); //gets number of rows
$numFields = mysqli_num_fields($result); //gets number of fields
//prints the data in the table
while($row = mysqli_fetch_assoc($result)){
$posted = $row['post'];
$message = wordwrap($posted,5);
echo
'<div id ="blogs">
<table id = "blog_id">
</br>
<div id = "name">
<strong>'.$row['firstName'] . ' ' .$row['lastName'].
'</strong>
: ' .$message .
'<br/>
</div>
<div id ="date">'.
$row['mydatefield'] . '
</div>
<div id ="delete_comment">
Delete this comment
</div>
<p>
</table>
</div>';
}
mysqli_close($db);
?>
</body>
</html>
You have the wrong Usage of PHP_SELF
//You must use Server and execution environment information `$_SERVER[]`
$_SERVER['PHP_SELF'];
// For your form action like this
action = "<?php echo $_SERVER['PHP_SELF'];?>"
as Kail mentioned you got it wrong but you might want to use $_SERVER['SCRIPT_NAME'] instead of $_SERVER['PHP_SELF'] then you might want to add some script to get GET parameters if you use them for your script(s). If you use PHP_SELF you might have a user link to script.php/%22%3E%3Cscript%3Ealert('xss')%3C/script%3E%3Cfoo might look like action="script.php/"><script>alert('xss')</script> or could be a redirect to collect cookies and the alike in other words XSS attack.
$_SERVER['PHP_SELF'] vs $_SERVER['SCRIPT_NAME'] vs $_SERVER['REQUEST_URI']
XSS Woes
What's the difference between $_SERVER['PHP_SELF'] and $_SERVER['SCRIPT_NAME']?
I have a php page that connects to a mysql database. I know that the connection to the database is good because I have a php code that displays info from the database onto the webpage. When I try to insert new data into the databse, the page refreshes and the data is not inserted. I have checked to insure that the insert into command has the correct values.
<?php
if (isset($_POST['User_Name']))
{
include "connect_to_mysql.php";
$name = mysql_real_escape_string($_POST["Name"]);
$sql = mysql_query("SELECT TestID FROM test WHERE Name='$name' LIMIT 1")or die (mysql_error());
$productMatch = mysql_num_rows($sql);
if ($productMatch > 0)
{
echo 'Sorry you tried to place a duplicate "User Account" into the system, click here';
exit();
}
else
{
$sql = mysql_query("INSERT INTO test (TestID,Name)
VALUES('', '$name')") or die (mysql_error());
$uid = mysql_insert_id();
header("location: index.php");
exit();
}
}
?>
<?php
include "connect_to_mysql.php";
$User_list = "";
$sql = mysql_query("SELECT * FROM test");
$UserCount = mysql_num_rows($sql);
if ($UserCount > 0)
{
while($row = mysql_fetch_array($sql))
{
$id = $row["TestID"];
$name = $row["Name"];
$User_list .= "Users ID: $id - <strong>$name</strong> <br />";
}
}
else
{
$User_list = "You have no users listed in the database.";
}
?>
<!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" />
<title>Untitled Document</title>
</head>
<body>
<div align="center" id="mainWrapper">
<div id="pageContent"><br />
<div align="right" style="margin-right:32px;">+ Add New User</div>
<div align="left" style="margin-left:24px;">
<h2>User list</h2>
<?php echo $User_list; ?>
</div>
<hr />
<a name="UserForm" id="UserForm"></a>
<h3>
↓ Add New User Form ↓
</h3>
<form action="index.php" enctype="multipart/form-data" name="myForm" id="myform" method="post">
<table width="90%" border="0" cellspacing="0" cellpadding="6">
<tr>
<td width="20%" align="right">Name</td>
<td width="80%"><label>
<input name="name" type="text" id="name" size="50" />
</label></td>
</tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="button" id="button" value="Add This Name Now" />
</label></td>
</tr>
</table>
</form>
<br />
<br />
</div>
</div>
</body>
</html>
I see two problems right away (there may be more). First, PHP array keys are case sensitive. You are accessing $_POST['Name'] but your form input is name. Second, you are testing for $_POST['User_Name'] which doesn't appear to exist anywhere:
// Look for name in the $_POST
if (isset($_POST['name']))
{
include "connect_to_mysql.php";
// name is case-sensitive
$name = mysql_real_escape_string($_POST["name"]);
Later, if your table has an AUTO_INCREMENT id on TestID, you should either omit it or insert NULL in the insert statment:
// Don't include TestID if it is AUTO_INCREMENT. That will happen automatically
$sql = mysql_query("INSERT INTO test (Name)
VALUES('$name')") or die (mysql_error());
I think it will work if you change
if (isset($_POST['User_Name']))
to
if (isset($_POST['Name']))
You check the existence of something which doesn't exists in your form.
Addition:
If TestID is autoincrement, change the below
"INSERT INTO test (TestID,Name) VALUES('', '$name')"
to
"INSERT INTO test (Name) VALUES('$name')"
If you do not get any errors that means you have an error in your MySQL syntax two ways to test it would be to copy the syntax into PHPMyAdmin or whatever your native MySQL command line is and see if you get an output error. Or another thing you can do is to modify all your mysql_query(); functions by adding mysql_query()or die(mysql_error());