Cannot store picture in database(no error messages appear) - php

Hello I am here yet again with another problem.
As I followed a tutorial I tried to save images to my database. It all worked fine and dandy with no error messages but for some reason the image refuse the get stored. Nothing show up at all!
<html>
<body>
<form action="test.php" method="POST" enctype="multipart/form-data">
<input type="file" name="image"><input type="submit" name="submit" value="Upload" />
</form>
<?php
if(isset($_POST['submit'])) {
mysql_connect("localhost","root","") or die("Could not find database!");
mysql_select_db("Image") or die("Could not find database!");
$imageName = mysql_real_escape_string($_FILES["image"]["name"]);
$imageData = mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["image"]["type"]);
if(substr($imageType,0,5) == "image") {
mysql_query("INSERT INTO 'blob' VALUES ('','$imageName','$imageData')");
echo "File uploaded!";
}
else
{
echo "Only images are allowed!";
}
}
?>
</body>
</html>
Database:
id, name, image:
int(Auto increment), varchar(40), mediumblob(because of the size)
The only odd thing about this is that "file_get_contents" is blacked out(I use notepad++).
Otherwise I don't see whats wrong, I have checked guides and whatnot but the thing is that I need to use this method in another form that have a large amount of information stored(15 fields including a description). I am still very new to this and its hard to know what to keep and how to write the best way. But anyway if you can help me it would be awesome.
If you have any questions regardning anything or just some tips just comment.

Your table name blob should be surrounded by back-ticks, not apostrophes.
However, I recommend that you change the name of this table to something that is not a reserved word in MySQL.

Related

How to pass POST parameters in a url

Is it possible to upload images/files by sending the POST or REQUEST, parameters in the URL without HTML content?
I created a PHP file that gets a image from my someone, stores that file into the database, and a in a folder on my computer. It works fine but what I want to do now is remove the html content and only allow someone to send the images/files via the URL. I tried using $_GET but I received a lot of errors. I also researched this and read that only $_POST will work.
Here is my PHP source code with HTML but keep in mind, "I want the page blank and the only way for someone to send the images/files is through URL".
PHP:
if(isset($_POST['submit'])){
if(#getimagesize($_FILES['image']['tmp_name']) ==FALSE){
// Select an image
echo "Please select an image.";
}
else{
// THE PATH TO STORE THE UPLOAD IMAGE
$target = "images/".basename($_FILES['image']['name']);
//CONNECT TO DATABASE
$db = mysqli_connect("localhost", "root", "");
mysqli_select_db($db, "magicsever");
if(mysqli_connect_error()){
die ("Database connection error");
}
//GET ALL THE SUBMITTED DATA
$image = $_FILES['image']['tmp_name'];
$name = $_FILES['image']['name'];
//Store te submitted data to database
$sql = "INSERT INTO image_test (name, image)VALUES ('$name','$image')";
$query = mysqli_query($db, $sql);
//Now lets move the uploaded image into the folder
$nullResult = array();
$nullResult['Image'] = (move_uploaded_file($_FILES['image']['tmp_name'], $target))? "Successful": "Unsuccessful";
echo json_encode($nullResult);
}
}
HTML:
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="image">
<br></br>
<input type="submit" name="submit" value="Upload">
</form>
$_POST['']; Parameters come from the usually the form that has the method set to POST, like yours has, that input type you have (file, named image) will be returned has $_POST['image'], $_REQUEST on the other hand is the "GET" method, it works in the same way, the only difference is it's not secure and it comes in the url. I would recommend using POST to be honest. Also use PDO because your code is vulnerable to SQL injection. (mentioned by Alex Howansky)

PHP/MYSQL - Upload Excel/CSV to MySql table

I recently built a web app which allows teachers to give grades to students and a lot of other stuff. Right now I'm adding a feature that gives the teacher the option to upload an excel/csv file with all the grades to the different students. My code seems fine however there are some issues with it and I can't figure out why. What happens is I get a bunch of blank records on my 'avaliacoes' table when I should only be getting 2 records.
How my excel looks :
1 (row) : naluno, uc, tipo, nota
2 (row) : r2011251, BD, exame, 15
3 (row) : r2011223, BD, exame, 16
(the first row isn't accounted for when inserting into the table)
My HTML code for the form (inside Diretor-Curso.php) :
<form class="form-group" action="lancarnota3.php" method="post" enctype="multipart/form-data">
<label class="control-label" for="uc">Enviar Ficheiro Excel/CSV com notas</label>
<br>
<input id="fileSelect" type="file" name="file" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
<br>
<input type="submit" class="btn btn-default botao2" name="Submeter" value="Submeter"></button>
</form>
My PHP page (lancarnota3.php) which handles the upload :
<?php
if(isset($_POST["Submeter"]))
{
$conn = mysqli_connect("localhost", "root", "", "teste");
$conn->set_charset("utf8");
// Check connection
if($conn === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
//$filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($_FILES["file"]["tmp_name"], "r");
$count = 0;
while (($emapData = fgetcsv($file, 1000, ",")) !== FALSE)
{
$count++;
if($count>1){
$sql = "INSERT into avaliacoes (naluno, uc, tipo, nota) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
mysqli_query($conn, $sql);
}
}
fclose($file);
include 'Diretor-Curso.php';
echo "<script> replace('lancarnotas2'); </script>";
}
else
{
include 'Diretor-Curso.php';
echo "<script> replace('lancarnotas6'); </script>";
}
}
// close connection
mysqli_close($conn);
?>
Any idea how to make it work?
Are you sure that your data file doesn't contain empty line? Check the MySQL general log to see which queries were executed. I expect you will see the queries inserting the blank records in the log.
You could simply add a condition before the INSERT to check that you are trying to insert "non-empty" data, or perform additional validation to ensure that the data is indeed complete.
This was a silly one, so basically I had to change the comma (",") to a semi colon (";") because the csv was separating everything like that for some reason. and now it works perfectly. oh well hope this helps anyone :)

Adding photo category to php code?

I was able to develop a code in enabling users to freely upload images, while the pictures would be stored to the MySql database. But I also would like to add to the php and mysql code image categories where before uploading the image, users can select from ether category- All, People, Cities, Nature and Others then click submit. How do I add that to my php code and mysql table? See my original code below:
<?php
$dbCnn = mysql_connect('', '', '');
mysql_select_db('', $dbCnn);
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$image = addslashes(file_get_contents($_FILES['file']['tmp_name']));
$insStr = "INSERT INTO imagedata(id, image) VALUES ('', '{$image}')";
mysql_query($insStr);
}
Don't store images in database because it's useless. Instead of this, store in database only path to file and file save on server.
So...
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<select name="category">
<option>Nature</opton>
<option>People</option
</select>
</form>
<?php
if(isset($_POST['category']) && isset($_FILES['file']['tmp_name'])){
//mysql connect etc
move_uploaded_file($_FILES['file']['tmp_name'], path/where/to/save/file);
mysql_query("INSERT INTO table VALUES('{$_FILES['file']['name']}', '{$_POST['category']}')");
}

Php mysql registration with image

Okay I know I just asked a question about this but now I have it uploading the image to the data base and tried to re do some things to get the text to go in there I added everything back in for the first name but it dosnt seem to be making its way back any help would be amazing thank you btw this community is awesome.
<html>
<head>
<title>Upload an image</title>
</head>
<body>
<form action="UploadContent.php" method="POST" enctype="multipart/form-data">
<p>FirstName:</p><input type="FirstName" name"FirstName"/>
<p>File:</p><input type="file" name="image">
<input type="submit" value="Upload">
</form>
<?php
// connect to database
include"config.php";
// file properties
$FirstName = $_POST['FirstName'];
$file = $_FILES['image']['tmp_name'];
if (!isset($file))
echo "Please select a profile pic";
else
{
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if ($image_size==FALSE)
echo "That isn't a image.";
else
{
$insert = mysql_query("INSERT INTO content VALUES ('".$FirstName."','','','','','','','','','$image_name','$image')");
}
}
?>
</body>
</html>
I changed my insert code as follows
$insert = mysql_query("INSERT INTO content (FirstName, LastName, Gender, City, State, BirthMonth, BirthDay, BirthYear, ProfileUrl, ProfilePicName, ProfilePic) VALUES ('".$FirstName."','".$LastName."','".$Gender."','".$City."','".$State."','".$BirthMonth."','".$BirthDay."','".$BirthYear."','".$ProfielUrl."','$image_name','$image')");
because I was trying to get this youtube video to help but still no luck
http://www.youtube.com/watch?v=xAkunfiZwYQ
Well, whether you get your answer or not but i am not agree with your approach of storing images into database, you may (not may have to) store them in a file system, and the path in database, that will be the correct way to do. here is an good stack post to read Storing images

what is the equivalent of ispostback(.NET) in PHP?

I just start coding in PHP,
i wrote my first php + mysql program for inserting data through web form. it works fine, but whenever i refresh the page, it automatically saves null record to my database.
i know the solution in .NET is ispostback, but not in php?
can somebody give me some idea in PHP.
Code is here:
<body>
<form action="mySQLTest.php" method="post">
First Name :<input type="text" name ="txtFirstName"/> <br/>
Last Name: <input type="text" name ="txtLastName"/> <br/>
Age : <input type="text" name= "txtAge" /> <br/>
<input type="submit"/>
</form>
<?php
$con = mysql_connect("localhost","root","");
if(!$con)
{
die('Could not Connect:' .mysql_error());
}
mysql_select_db("test", $con);
if($_REQUEST[])
{
$sql1 = "Insert into info(FirstName, LastName, Age) Values('$_POST[txtFirstName]','$_POST[txtLastName]','$_POST[txtAge]')";
}
if(!mysql_query($sql1, $con))
{
die('Error: '.mysql_error());
}
else
{
echo "1 Record Added";
}
mysql_close($con)
?>
</body>
Have you tried if ($_SERVER['REQUEST_METHOD']=='POST')
updated answer:
if ($_SERVER['REQUEST_METHOD']=='POST') {
[insert...]
header('Location: added_record.php');
}
When you use the POST-method, it's better (imho) to use $_POST rather than $_REQUEST. To check whether you have data, you could use isset($_POST['txtFirstName']);. If you need all data, it's best to do this for all input fields, resulting in
if(isset($_POST['txtFirstName']) && isset($_POST['txtLastName']) && isset($_POST['txtAge'])) {
// do stuff
}
If you want to know if there was any field submitted using post, you could use if(!empty($_POST)) {.
On a side note: I know you are just starting PHP, it could be quite dangerous to use user-generated code in queries. When you are building stuff online, for everyone to reach, please read a bit about SQL injection. This will also prevent your code from breaking when someone enters an apostrophe (').

Categories