Storing Pictures To mysql Using Laravel - mysql

I'm trying to store some upload pictures to my database using laravel. Everything goes well, everything got stored, but for the file, they keep storing a bin file of 38B, I've tried reading it to .Txt files and it has a path to /Applications/MAMP/tmp/php/phpUzMXbn.
Here is my function code :
Route::post('/FruitCreate',function(Request $request){
$fruit = new fruit;
$fruit->name = $request->name;
$fruit->price = $request->price;
$fruit->picture = $request->image;
$fruit->save();
return redirect('FruitsChangingPricePanel');
My form blade :
<form enctype="multipart/form-data" method="POST" action="{{ url('FruitCreate') }}" >
{{ csrf_field() }}
<input type="text" name='name'>
<input type="text" name='price'>
<input type="hidden" name="MAX_FILE_SIZE" value="30000000" />
<input type="file" name='image'>
<button type='submit'> submit </button>
thank u For Your Help !!

You can do may be something like that:
$file = $request->file('image');
$imageContent = $file->openFile()->fread($file->getSize());
$fruit = new fruit; $fruit>picture = $imageContent; $fruit>save();
Note: Your column type must be Blob

because you are trying to save directly bin.
try this one
$file = Input::file('file');
$destinationPath = public_path(). '/uploads/';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
echo $filename;
//echo '<img src="uploads/'. $filename . '"/>';
$user = ImageTest::create([
'filename' => $filename,
]);

Firstly, you should get your image and then store it to public/uploads/fruits folder.And after that, you are saving the path to your picture to DB.
$fruit = new fruit;
$fruit->name = $request->name;
$fruit->price = $request->price;
if ($request->has('image')) {
if (!file_exists(public_path('uploads/fruits/'))) {
mkdir(public_path('uploads/fruits/'));
}
if (!file_exists(public_path('uploads/fruits/' . date('FY') . '/'))) {
mkdir(public_path('uploads/fruits/' . date('FY') . '/'));
}
$image = $request->file('image');
$filename = public_path('uploads').'/fruits/' . date('FY') . '/' . str_random() . '.' . $image->guessExtension();
\Image::make($image->getRealPath())->encode('jpg')->resize(220, 220)->put($filename);
$fruit->picture = $filename;
}
$fruit->save();

Related

How can I store an image to the database from modal?

I want to store an Image through a modal, usually, I store images this way. But it never stores, it stores null on the database, like the file wasn't even uploaded. Everything else on the modal stores perfectly, except the image.
This is the code for the image on my controller.
if($request->hasFile('image')){
$file = $request->file('image');
$extension = $file->getClientOriginalExtension();
$filename = time() .'.'.$extension;
$file->move('uploads/event/',$filename);
$event->image = $filename;
}
In my view, this is how I upload the image.
<div class="text-center">
<img src='http://ssl.gstatic.com/accounts/ui/avatar_2x.png' width="300px" height="300px" class="avatar img-circle img-thumbnail" alt="avatar" name="image" >
</div><hr>
<div class="input-group">
<div class="custom-file">
<input type="file" class="custom-file-input" name="image" >
<label class="custom-file-label">Upload picture</label>
</div>
</div>
For the code I had, the only problem was that I didn't use the enctype="multipart/form-data". After looking for options, I found this and wrote it on the form of action and form-group div. It worked, the image stores and it also updates.
<form action="{{action('CalendarController#store')}}" method="POST" enctype="multipart/form-data">
{{csrf_field()}}
<div class="modal-body">
<div class="form-group" enctype="multipart/form-data">
Since I got this working I will start implementing other codes for better performance and start to learn about the Storage in laravel. Thanks to all of you!
Try this on your Controller:
use Image;
public function store(CreateRequest $request)
{
$file = $request->file('image');
$imagename = $file->getClientOriginalName();
$imageext = $file->getClientOriginalExtension();
$path = 'upload/image/'.time().'.'.$imageext;
$image = Image::make($file);
$image->save($path);
$input = $request->all();
$input['image'] = $path;
$user = $this->userRepository->create($input);
return redirect(route('users.index'));
}
do the same with update() function
The file will store in /public/upload/image folder
You can also try and use the 'Intervention\Image' and File class:
composer require intervention/image
<?php
...
use File;
use Intervention\Image\Facades\Image
...
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = 'image.'.$image->getClientOriginalExtension();
$save_path = storage_path().'uploads/event/';
$path = $save_path.$filename;
$public_path = 'uploads/event/'.$filename;
// Make the user a folder and set permissions
File::makeDirectory($save_path, $mode = 0755, true, true);
// Save the file to the server
Image::make($image)->resize(300, 300)->save($save_path.$filename);
// Save the public image path
$event->image = $public_path;
$event->save();
}
return response()->json(['path' => $path], 200);
} else {
return response()->json(false, 200);
}

How to upload a file in Laravel?

Here is the code to upload an image to the database.
public function create(Request $request)
{
$this->validate($request, [
'comment' => 'required',
]);
$mess = new messageUser;
$mess->user_id = Auth::guard('userLogin')->user()->id;
$mess->message = $request->comment;
if($request->hasFile('image')){
$filenameWithExtention = $request->file('image')->getClientOriginalName();
$fileName = pathinfo($filenameWithExtention,PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameStore = $fileName .'_'.time().'.'.$extension;
$path = $request->image->storeAs('images', $fileNameStore);
$mess->attach = $fileNameStore;
}
$mess->save();
return $mess;
}
Blade
<div class="form-group">
<textarea id="compose-textarea" name="comment"></textarea>
</div>
<div class="form-group">
<div class="input-group">
<input type="file" name="image" class="form-control inputFileVisible" placeholder="attach one file">
<button type="button" class="btn btn-fab btn-round btn-info"><i class="material-icons">attach an image</i>
</button>
</div>
</div>
<button type="submit" class="btn btn-primary"><i class="fa fa-envelope-o"></i>send image</button>
The code sends the message successfully but didn't upload the image.
You can do something like this:
if($request->hasFile('image')){
$filenameWithExtention = $request->file('image')->getClientOriginalName();
$fileName = pathinfo($filenameWithExtention,PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameStore = $fileName .'_'.time().'.'.$extension;
$path = $request->photo->storeAs('images', $fileNameStore);
$mess->attach = $fileNameStore;
}
For more Visit this
Thanks.
Note: Don't forget to run php artisan storage:link
What is the error show us please it will be better to guide you... BTW you ca use following code to uplaod an image/file
if ($request->image) {
$file = $request->File('image');
$ext = $student->username . "." . $file-
>clientExtension();
$file->storeAs('images/', $ext);
$student->image = $ext;
}

Query works when form action is to same page, not when it redirects to another

I have query that gets data from a form, when the submit button is pressed the data should be stored in a database. When the form's action is action="#" the data is inputted into the database. But when the action is action="otherPage.php" the data is not inserted into the database. Any help ?
Side Note: I know the queries need to be changed to counter SQL injection this is just for testing
Code:
if(isset($_POST['submit']))
{
$name = $_POST['fullName'];
$idNumber = $_POST['idNo'];
$cardNo = $_POST['cardNo'];
$_SESSION['fullName'] = $name;
$_SESSION['id'] = $idNumber;
$checkExists = "SELECT * FROM system.table WHERE idNumber = '$idNumber' ";
$resExists = mysqli_query($connection,$checkExists)
or die("Error in query: ". mysqli_error($connection));
if(mysqli_fetch_assoc($resExists) > 0)
{
$updateCard = "UPDATE system.table SET cardNo = '$cardNo' WHERE idNumber=$idNumber";
$resUpdate= mysqli_query($connection,$updateCard)
or die("Error in query: ". mysqli_error($connection));
}
if(mysqli_fetch_assoc($resExists) < 1)
{
$company = $_POST['company'];
$name = trim($name);
$last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
$first_name = trim(preg_replace('#'.$last_name.'#', '', $name));
$insert = "INSERT INTO system.table (idNumber,name,surname,company,cardNo) VALUES
('$idNumber','$first_name','$last_name','$company','$cardNo')";
$resInsert = mysqli_query($connection,$insert)
or die("Error in query: ". mysqli_error($connection));
}
$connection->close();
}
I do not know if this is the corrext way to go around it, but it works. I included ob_start(); at the beginning of my code, left the action as
<form role="form" method="POST" action="#">
Then included
header('Location:otherPage.php');
so that the page automatically redirects to otherPage.php
If you have two files in the same folder, it should be working:
myFolder
- testForm.php
- testUpload.php
testForm.php:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post" action="testUpload.php">
<fieldset>
<legend>Form</legend>
<label>Name: </label>
<input type="text" name="name">
<input type="submit">
</fieldset>
</form>
</body>
</html>
testUpload.php:
<?php
print($_POST['name']);
exit;
Do you have any Redirection Statements in the config of your Web Server (e.g. Apache httpd.conf)?

how to Load Text file into HTML, inside <textarea> tag?

how to Load Text file into HTML, inside tag?, I don't have an source to show you.
thanks
You can use PHP to load files from the user's computer. Here is an example.
form.html
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
upload.php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(isset($_POST["submit"])) {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
header("Location: http://example.com/displaymessage.php?filename=" + basename( $_FILES["fileToUpload"]["name"]));
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
displaymessage.php
<?php
$file = $_GET['filename'];
?>
<script>
var client = new XMLHttpRequest();
client.open('GET', '/uploads/<?=$file?>');
client.onreadystatechange = function() {
document.getElementById("#textbox").value = client.responseText;
}
client.send();
</script>
Make sure to change #textbox, to the ID of the textarea tag. (e.g. <textarea id="foo">)
NOTE: I just came up with half of this code, and I am not sure if it will work

Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

I'm having a problem regarding Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING. I tried every solution in available online but still I got the same error over and over again.
So the problem is: Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in C:\wamp\www\RedCross\load.php on line 25
load.php
<?php
include_once('connect.php');
$EventNum = $_POST['ename'];
//die('You sent: ' . $selStudent);
//Run DB query
$query = "SELECT Price FROM events WHERE EventID = '".$EventNum."' ";
$result = mysql_query($query) or die('Fn another_php_file.php ERROR: ' . mysql_error());
$num_rows_returned = mysql_num_rows($result);
//die('Query returned ' . $num_rows_returned . ' rows.');
//Prepare response html markup
$r = "
<div class='control-group'>
<label class='control-label' for='price'>Price </label>
<div class='controls'>
";
//Parse mysql results and create response string. Response can be an html table, a full page, or just a few characters
if ($num_rows_returned > 0) {
while ($row = mysql_fetch_array($result)) {
$r = $r . "<input type='text' name='price' id='price' class='input-xlarge' value = " . $row['Price'] . " readonly>";
}
$r = $r . "<center>
<button type='submit' class='btn btn-large btn- danger' name='submit' id='submit'>Join!</button>
</center>";
//The response echoed below will be inserted into the
echo $r;
} else {
$r = '<p>sorry there is no available staff for this</p>';
// $r = $r . '</select><input type="submit" name ="go" value="press me">';
$r = $r . '</div></div>';
//The response echoed below will be inserted into the
echo $r;
}
//Add this extra button for fun
?>
Line 25 is this code:
Even though I put spaces before it making this line not in line 25 still the error is in line 25.
Please help.
Change the code in line 25 to line below and test:
$r = $r . '<input type="text" name="price" id="price" class="input-xlarge" value = ' . $row["Price"] . ' readonly>';