How can I enter an image into mysqli? [duplicate] - php

This question already has answers here:
Empty values being added to all mysql rows instead of just the target row
(2 answers)
Closed 6 years ago.
I am not so sure how to process an image in PHP to put it into a blob type in MYSQLI. Here is my code so far...
<?php
$servername = ""; //Taken out for stack overflow question
$username = ""; //Taken out for stack overflow question
$password = ""; //Taken out for stack overflow question
$dbname = ""; //Taken out for stack overflow question
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn)
{
echo 'Could not connect';
}
else
{
if (!empty($_FILES['cf'] && $_POST['category']))
{
$file = $conn->real_escape_string($_FILES['cf']['tmp_name']);
mysqli_query($conn, "INSERT INTO adDatabase(".$category.") VALUES(".$file.")");
}
else
{
echo 'Empty file';
}
}
mysqli_close($conn);
?>
Now the value of the image is not null so the image is processed. But I cant seem to get it processed. Normally I make a variable $var = $_POST['cf']; then I add that into the query. I also tried $var = $_FILES['cf']; but it wont process. Is there something else I need to do to it to make it send/process properly?
Edit based on answer
I changed my PHP to something that resembles an answer
<?php
$servername = ""; //Taken out for stack overflow question
$username = ""; //Taken out for stack overflow question
$password = ""; //Taken out for stack overflow question
$dbname = ""; //Taken out for stack overflow question
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn)
{
echo 'Could not connect';
}
else
{
if (!empty($_FILES['cf'] && $_POST['category']))
{
try
{
$file = $conn->real_escape_string($_FILES['cf']['tmp_name']);
$filecontents = File_Get_Contents($file);
$filecontentssafe = $conn->real_escape_string($filecontents);
mysqli_query($conn, "INSERT INTO adDatabase(".$category.") VALUES(".$file.")");
echo 'Query successful';
}
catch(Exception $e)
{
echo 'Could not perform action' + $e;
}
}
else
{
echo 'Empty file';
}
}
mysqli_close($conn);
?>
Now I see Query successful, however.. nothing goes into the database.
Edit - added retrieve file
<?php
$servername = "";
$username = "";
$passcode = "";
$dbname = "";
$conn = mysqli_connect($servername, $username, $passcode, $dbname);
if (!$conn)
{
echo 'Could not connect';
}
else
{
try
{
$sql_query = mysqli_query($conn, "SELECT * FROM `adDatabase`");
while ($row = mysqli_fetch_array($sql_query))
{
$id = $row['ID'];
$img = $row['img'];
$image = '<img src="data:image/png;base64,'.base64_encode( $row['food'] ).'" style="height: 12em; width: 12em; margin: 1em; padding: 0.9em; " >';
echo $image;
}
}
catch(Exception $e)
{
echo $e;
}
}
?>
How I retrieve information

By the time you call mysql, $file only contains a path to the temporary uploaded file, not the data you want.
If you want MySQL to look at the file's path, and load its contents directly into your database, have a look at the MySQL function LOAD_FILE() here: http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_load-file
Otherwise, if you'd like to do this in PHP, you'd want to pull the file's contents into a variable with something like
$file_contents=File_Get_Contents($file);
... and then use
$file_contents_safe=$conn->real_escape_string($file_contents);
before sticking $file_contents_safe into the database. Some people also like to Base64 encode.
Edit: Please also keep injection vulnerabilities in mind, as others have suggested. The name of the temporary file, and anything else coming in from post/apache shouldn't be trusted on its own.

If you don't have to stick with saving the blob content in the database, you could only save the file name in the database and do a regular file upload to a selected location. For that, you will need to add this before adding the content in the database
$tmp_name = $_FILES["filename"]["tmp_name"];
$name = $_FILES["filename"]["name"];
move_uploaded_file($tmp_name, "YOUR_UPLOAD_DIR/{$name}");
And after uploading the file, you just need to store it's name in the database instead of storing the blob content. When displaying, you just need to access the actual file in your upload folder and show it. It's much cleaner solution, especially if you don't have to migrate files between servers.
The whole code would look something like this:
if (!empty($_FILES['cf'] && $_POST['category']))
{
$tmp_name = $_FILES["cf"]["tmp_name"];
$name = $_FILES["cf"]["name"];
move_uploaded_file($tmp_name, "YOUR_UPLOAD_DIR/{$name}");
$file = $conn->real_escape_string($name);
mysqli_query($conn, "INSERT INTO adDatabase(".$category.") VALUES(".$file.")");
}
Then when accessing it, you will need to pull the data from the database and just display it. If it is an image, it could be
<img src="<?php YOUR_UPLOAD_DIR.'/'.$name ?>"/>
Otherwise:
To insert the image data in your database do:
$content = file_get_contents($tmpName);
$file = $conn->real_escape_string($content);
$mime_type = mime_content_type($tmpName);
mysqli_query($conn, "INSERT INTO adDatabase(".$category.", mime_type) VALUES(".$file.", ".$mime_type.")");
Note I added a mimetype to the insert, because you will need it in order to be able to display the file properly later.
Then, when you want to display it, just pull the content from the db and echo it together with the proper header.
header('Content-type:'.$mime_type);
echo $content;

Related

Record not inserted into database without any error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have android app to upload image to server and save some records to database, the uploaded image is saved in folder as expected but the php statement to save record in database not work and save nothing without any error show.
my php script
$hostname = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$con = mysqli_connect($hostname,$username,$password,$dbname);
if(isset($_POST['image'])){
$image = $_POST['image'];
$name= $_POST['name'];
$type= $_POST['type'];
$desc= $_POST['desc'];
$phone= $_POST['phone'];
$token= $_POST['token'];
$address= $_POST['address'];
upload($_POST['image']);
exit;
}
else{
echo "image_not_in";
exit;
}
function upload($image){
//create unique image file name based on micro time and date
$now = DateTime::createFromFormat('U.u', microtime(true));
$id = $now->format('YmdHisu');
$upload_folder = "Uploads"; //DO NOT put url (http://example.com/upload)
$path = "$upload_folder/$id.jpeg";
//Cannot use "== true"
if(file_put_contents($path, base64_decode($image)) != false){
$sql= "INSERT INTO donor(name, donor_phone, donor_type, donor_desc, address, donor_img, token) values('$name', '$type', '$phone', '$desc', '$address', '$path', '$token')";
$response["success"]=1;
echo json_encode($response);
}
else{
$response["error"]=2;
echo json_encode($response);
}
}
$con->close();
?>
You're not actually executing the query after building it. What you need is to add, right after defining $sql, something like this:
if (mysqli_query($con, $sql) === TRUE) {
$response["success"]=1;
echo json_encode($response);
}
else {
$response["error"]=2;
echo json_encode($response);
}
You should check the php manual for mysqli_query.

User not being deleted on link click [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I have a users table and I want to be able to delete a user when a link is clicked. $user_name is set in a session. Here is the link:
<?php echo "Delete Account" ?>
Here is the code on delete_user.php:
<?php
session_start();
session_destroy();
require "connection.php";
?>
<?php
if($_GET['id'] != ""){
$user_name = $_GET['id'];
$sql = "DELETE FROM users WHERE user_name='{$user_name}'";
$result = mysqli_query($connection, $sql);
header('Location: register.php');
}
?>
<?php include "footer.php";?>
I don't understand why it's not deleting the user from the database when this code is executed?
There's no clear reason as to why your code is not working. However, you mentioned being new to PHP, so picking up good practices with your code could (1) help solve the issue at hand, (2) make your code more efficient, and easier to debug.
I recommend you use mysqli in the object-oriented manner, it requires less code, and usually easier to follow.
Making the connection is simple:
<?php
$host = 'localhost';
$user = 'USERNAME';
$pass = 'PASS';
$data = 'DATABASE';
$mysqli = new mysqli($host, $user, $pass, $data);
// catch errors for help in troubleshooting
if ($mysqli->errno)
{
echo 'Error: ' . $mysqli->connect_error;
exit;
}
?>
Creating a safe environment for your server keep in mind these things:
Do not trust user input (ever!)
Do not perform direct queries into your database.
When developing, break your code into steps so you can easily troubleshoot each part.
With those three simple things in mind, create a delete file.
<?php
if (isset($_GET['id'])
{
// never trust any user input
$id = urlencode($_GET['id']);
$table = 'users';
// set a LIMIT of 1 record for the query
$sql = "DELETE FROM " . $table . " WHERE user_name = ? LIMIT 1";
// to run your code create a prepared statement
if ($stmt = $mysqli->prepare( $sql ))
{
// create the bind param
$stmt->bind_param('s', $id);
$stmt->execute();
$message = array(
'is_error' => 'success',
'message' => 'Success: ' . $stmt->affected_rows . ' were updated.'
);
$stmt->close();
}
else
{
$message = array(
'is_error' => 'danger',
'message' => 'Error: There was a problem with your query'
);
}
}
else
{
echo 'No user id is set...';
}
The code will help you set the query, and delete the user based on their user_name... Which I am not sure that is the best solution, unless user_name is set to be an unique field on your MySQL database.
Firstly this is a horrible way to do this, you are prone to SQL Injections and also using GET literally just tags the query to the end of the URL which is easily obtainable by a potential hacker or ANY user as a matter of fact. Use POST instead with a bit of jQuery magic, I would also recommend using Ajax so that you don't get redirected to php file and it will just run. As it is not anyone can access that URL and delete users so I recommend using PHP SESSIONS so that only people from your site can delete users. Also simply passing the id to the PHP file is very insecure as ANYONE could simply create a link to your php file on their site and delete users.
Therefore try this to fix your code (with added security):
PLEASE NOTE: I am aware that this may not be the best way nor the worst but it is a fairly secure method that works well.
Your main page, index.php:
<?php
session_start();
// Create a new random CSRF token.
if (! isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = base64_encode(openssl_random_pseudo_bytes(32));
}
// Check a POST is valid.
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
// POST data is valid.
}
?>
...
<form id="delete_user_form" action="delete_user.php" method="post">
<input type="hidden" name="user_id" value="<?php echo $user_name; ?>" />
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>" />
<input type="submit" value="Delete User" />
</form>
In your .js file (make sure you have jQuery linked):
window.csrf = { csrf_token: $("input[name= csrf_token]").val() };
$.ajaxSetup({
data: window.csrf
});
$("#delete_user_form").submit(function(event) {
event.preventDefault(); //Stops the form from submitting
// CSRF token is now automatically merged in AJAX request data.
$.post('delete_user.php', { user_id: $("input[name=user_id]").val() }, function(data) {
//When it it's complete this is run
console.log(data); //With this you can create a success or error message element
});
});
Now for your delete_user.php file, this should fix the errors:
<?php
session_start();
require "connection.php";
// Checks if csrf_token is valid
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
if(isset($_POST['user_id']) && $_POST['user_id'] != ""){
$user_name = $_POST['user_id'];
$sql = "DELETE FROM users WHERE user_name = '$user_name' LIMIT 1"; //LIMIT 1 only allows 1 record to be deleted
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully"; //You get this in your javascript output data variable
} else {
echo "Error deleting record: " . $conn->error; //You get this in your javascript output data variable
}
$conn->close();
}
}
?>
I don't know what your connection.php contains so this is what I'd put in it:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

php- How to record which user clicked on a link to download a file

I am trying to record which user has downloaded a file in an SQL database. Every file uploaded has its path displayed as a link on the site, allowing the user to download that file from a folder on the server. I am having trouble figuring out how to record which user has downloaded a file though. How can I query my database that a specific user has clicked a specific link? I have the user id stored as a session variable, so possessing the user id is not a problem. My code to display the downloadable files are as follows:
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "project_website1";
$user_id = $_SESSION[ 'user_id' ];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT task_id,file, description, title, deadline_claim FROM task";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>TITLE</th><th>DESCRIPTION</th><th>DEADLINE</th><th>TASK</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
//echo "<tr><td>" . $row["file"]. "</td><td>" . $row["title"]. "</td><td>" . $row["deadline_claim"]. "</td></tr>";
echo "<tr><td>".$row["title"]."</td><td>".$row["description"]."</td><td>".$row["deadline_claim"]."<td><a href='" .$row["file"]. "'>CLAIM</td></a>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
If you want it to be purely PHP, as suggested, just use the task_id of the row in your file table. Here is a basic example, noting I have reorganized some elements to help keep your script cleaner. Ideally you will want to keep the functions on a different page and include them when you want to use them. Keeps your script cleaner and more easily readable.:
# Better to make a function/class to do your database so you can reuse it easily.
function getConnection( $servername = "localhost", $username = "root",$password = "",$dbname = "project_website1")
{
# Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
# Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
# Make a task retrieval function/class that will deal with getting the rows only
function getTasks($con,$id=false)
{
$sql = "SELECT task_id,file, description, title, deadline_claim FROM task";
# I am assuming your task_id values are numeric, so I don't sanitize here
if ($id) {
if(is_numeric($id))
# Append sql
$sql .= " WHERE `task_id` = '{$id}'";
else
# You shouldn't get this exception unless someone is trying to
# Manually put something else here via injection attempt
throw new Exception("Id must be numeric!");
}
$result = $con->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$new[] = $row;
}
}
# Send back rows
return (!empty($new))? $new : array();
}
# This is more of a listener, but it will cut down on some redundant check-script
function getFileId()
{
if(!empty($_GET['file']) && is_numeric($_GET['file']))
return (!empty($_GET['action']) && $_GET['action'] == 'download')? $_GET['file'] : false;
return false;
}
# As noted, you would include the functions here...
session_start();
# Get session id
$user_id = $_SESSION[ 'user_id' ];
# Get the database connection
$conn = getConnection();
# If there is a download
if(!empty($_GET['action']) && $_GET['action'] == 'download') {
# Get the tasks, could be based on id or all
$tasks = getTasks($conn, getFileId());
# Save to the database, make sure that you either bind parameters, or
# check that the values are numeric (if they are supposed to be numeric)
# Also check the count here first for the task before inserting. Make an error if not.
# Usually means user is trying to manipulate the request
$conn->query("INSERT into downloads (`fileid`,`userid`) VALUES('".$tasks[0]['task_id']."','".$user_id."')");
# Download file. If you want to obfuscate the file, you would use
# download headers instead:
# http://php.net/manual/en/function.readfile.php
header('Location: '.$tasks[0]['file']);
# Stop execution
exit;
}
# Get all tasks
$tasks = getTasks($conn);
# If there are rows, output them
if (!empty($tasks)) {
echo "<table><tr><th>TITLE</th><th>DESCRIPTION</th><th>DEADLINE</th><th>TASK</th></tr>";
# output data of each row
foreach($tasks as $row) {
echo "<tr><td>".$row["title"]."</td><td>".$row["description"]."</td><td>".$row["deadline_claim"]."<td><a href='?action=download&file=" .$row["task_id"]. "'>CLAIM</td></a>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
Final note, I have not tested this, so be aware of that.
your header for calling script in html
<head>
<script laqnguage="javascript" src="myfunction.js" type="text/javascript"></script>
</head>
then in your while loop in php jump out of php
?>
<form name"myform" method="get" action="<? php echo $row["file"]; ?>">
<input type="button" name="name" Value"<? php echo $row["file"]; ?>" onClick="setinsertAction();" />
</form>
then jump into php again
<?php
now create a file called myfunction.js and put this inside
function setinsertAction() {
document.myform.action = "HERE PUT YOUR PHP FILE THAT WILL DO THE QUERY";
document.myform.submit()'
}
if all goes well it should the retrieve the file for download and executed your php script if the you replace your php file for the query in the .js file if it fails let me know

how to store filename to mysql by upload [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
this mycode
I'am try to edit but no success.
if(move_uploaded_file($_FILES["filUpload"]["tmp_name"],"docfile/".$_FILES["filUpload"]["name"]))
{
//*** Insert Record ***//
$file = $_FILES["filUpload"]["name"];
$fileup = mysql_real_escape_string($file);
$strSQL = "INSERT INTO fileproject(filename) VALUES($fileup);";
if(!$strSQL){
echo "<h1>Error Store FileName2DB<h1>";
exit;
}
echo "Upload Complete<br>";
}
you dont execute your query. You have to use your object to the database for query.
try
{
$bdd = new PDO('mysql:host=localhost;dbname=yourdb;charset=utf8', 'root', 'yourpassword',
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
if(move_uploaded_file($_FILES["filUpload"]["tmp_name"],"docfile/".$_FILES["filUpload"]["name"]))
{
//*** Insert Record ***//
$file = $_FILES["filUpload"]["name"];
$fileup = mysql_real_escape_string($file);
$strSQL = "INSERT INTO fileproject(filename) VALUES($fileup)";
$result=$bdd->query($strSQL);
if(!$strSQL){
echo "<h1>Error Store FileName2DB<h1>";
exit;
}
echo "Upload Complete<br>";
}
You are not using mysql extension for executing your query. Other example is about to PDO.
You can also INSERT the new row by using mysqli_* extension.
MYSQL procedural structure:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(move_uploaded_file($_FILES["filUpload"]["tmp_name"],"docfile/".$_FILES["filUpload"]["name"]))
{
//*** Insert Record ***//
$file = $_FILES["filUpload"]["name"];
$fileup = mysql_real_escape_string($file);
$strSQL = "INSERT INTO fileproject (filename) VALUES ('$fileup')";
// here you need to use mysqli_* extension
if(mysqli_query($conn, $strSQL)){
echo "Upload Complete<br>";
}
else{
echo "<h1>Error Store FileName2DB<h1>";
// exit;
}
}
mysqli_close($conn); // DATABASE CONNECTION CLOSE
?>
Side note:
As I mentioned in comments $fileup value is a string value so you need to use single quotes between the variable.

Generate PDF file with images from mysql database [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to PHP and i have been trying to create a PDF file with images from the database.All the tutorial i have seen only put an image in the Header(not from the database) and only pull text from the database to put in the PDF.i am using FPDF to create my PDF files.Any guidelines or help to achieve this will be appreciated.
Let's say that you have a table called images, where the image URLs are stored under the column url. You can use FPDF and the MySQL adapter to construct a PDF out of all of the images like this:
require 'fpdf/fpdf.php';
// DB parameters
$host = "localhost";
$user = "username";
$pass = "password";
$db = "db";
// Create fpdf object
$pdf = new FPDF('P', 'pt', 'Letter');
// Add a new page to the document
$pdf->addPage();
// Try to connect to DB
$r = mysql_connect($host, $user, $pass);
if (!$r) {
echo "Could not connect to server\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Connection established\n";
}
// Try to select the database
$r2 = mysql_select_db($db);
if (!$r2) {
echo "Cannot select database\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Database selected\n";
}
// Try to execute the query
$query = "SELECT * FROM images";
$rs = mysql_query($query);
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Query: $query executed\n";
}
while ($row = mysql_fetch_assoc($rs)) {
// Get the image from each row
$url = $row['url'];
// Place the image in the pdf document
$pdf->Image($url);
}
// Close the db connection
mysql_close();
// Close the document and save to the filesystem with the name images.pdf
$pdf->Output('images.pdf','F');
References
http://blog.themeforest.net/tutorials/how-to-create-pdf-files-with-php/
http://zetcode.com/databases/mysqlphptutorial/

Categories