Insert And Retrieve Image from PostgreSQL bytea using PDO - php

Im working usign PDO and PHP.
This is my table in Postgre
CREATE TABLE public.img
(
id integer NOT NULL DEFAULT nextval('img_id_seq'::regclass),
nombre bytea
)
When i store the file data i use this method
<?php
$db = new PDO("pgsql:host=localhost;port=5432;dbname=sac;user=postgres;password=insertPass");
if(isset($_POST["insert"]))
{
$file = pg_escape_bytea(addslashes(file_get_contents($_FILES["image"]["tmp_name"])));
$sql = 'INSERT INTO img (nombre) VALUES (?)';
$ISp_Res = $db->prepare($sql);
$ISp_Res->bindParam(1, $file);
$ISp_Res->execute();
}
?>
And in the table the values are
ID nombre
4; "\377\330\377\340\\0\020JFIF\\0\001\001\\0\\0\001\\0\001\\0\\0\377\341\\0\234Exif\\0\\0II*\\0\010\\0\\0\\0\007\\0\\0\001\003\\0\001\\0\\0\\0S\002\\0\\0\001\001\003\\0\001\\0\\0\\0\026\002\\0\\0\022\001\003\\0\001\\0\\0\\0\\0\\0\\0\\02\001\002\\0\024\\0\\0\\ (...)"
And the form that i retrieve the values in my table
<?php
$query = "SELECT * FROM img ORDER BY id DESC";
$db = new PDO("pgsql:host=localhost;port=5432;dbname=sac;user=postgres;password=insertPass");
$result = $db->prepare($query);
$results = $result->execute();
$results = $result->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row) {
echo($row['nombre']);
$dat= pg_unescape_bytea($row['nombre']);
echo "<img src='".$dat."'";
}
?>
However when i try to retrieve the information i just get Resource id #2 and a Warning: pg_unescape_bytea() expects parameter 1 to be string
This is the testView
<script>
$(document).ready(function(){
$('#insert').click(function(){
var image_name = $('#image').val();
if(image_name == '')
{
alert("Please Select Image");
return false;
}
else
{
var extension = $('#image').val().split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
alert('Invalid Image File');
$('#image').val('');
return false;
}
}
});
});
</script>
<?php
$db = new PDO("pgsql:host=localhost;port=5432;dbname=sac;user=postgres;password=insertPass");
if(isset($_POST["insert"]))
{
$file = pg_escape_bytea(addslashes(file_get_contents($_FILES["image"]["tmp_name"])));
$sql = 'INSERT INTO img (nombre) VALUES (?)';
$ISp_Res = $db->prepare($sql);
$ISp_Res->bindParam(1, $file);
$ISp_Res->execute();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Insert and Display Images From Mysql Database in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br /><br />
<div class="container" style="width:500px;">
<h3 align="center">Insert and Display Images From Mysql Database in PHP</h3>
<br />
<form method="post" enctype="multipart/form-data">
<input type="file" name="image" id="image" />
<br />
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-info" />
</form>
<br />
<br />
<table class="table table-bordered">
<tr>
<th>Image</th>
</tr>
<?php
$query = "SELECT * FROM img ORDER BY id DESC";
$db = new PDO("pgsql:host=localhost;port=5432;dbname=sac;user=postgres;password=insertPass");
$result = $db->prepare($query);
$results = $result->execute();
$results = $result->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row) {
echo($row['nombre']);
$dat= pg_unescape_bytea($row['nombre']);
echo "<img src='".$dat."'";
}
?>
</table>
</div>
</body>
</html>
Please tell me where im doing it wrong :(

Don't use addslashes() while inserting.
$target_file = '/path/to/file.jpg';
$img = fopen($target_file, 'r');
$data = fread($img, filesize($target_file));
$file = pg_escape_bytea($data);
While fetching data use
ob_start();
fpassthru($row['nombre']);
$dat= ob_get_contents();
ob_end_clean();
$dat= "data:image/*;base64," . base64_encode($dat);
echo "<img src='".$dat."'";

Related

PHP / MYSQL: Upload Image to database with encode base64

Currently, I developed a project that requires user to upload image from Computer. I do this from an example on the internet. For now, the column image at the database uses "BLOB" and the upload successful.
But, I don't want to uses BLOB, I want to change to LONGTEXT. When I change this format, the image saved to the database is successful but the image display is broken. The encode text and column image also looks weird. Can I know what is the problem? Below is the code
<?php
$connect = mysqli_connect("localhost", "root", "", "imagephp");
if(isset($_POST["insert"]))
{
$file = addslashes(file_get_contents($_FILES["image"]["tmp_name"]));
$query = "INSERT INTO tbl_images(name) VALUES ('$file')";
if(mysqli_query($connect, $query))
{
echo '<script>alert("Image Inserted into Database")</script>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br /><br />
<div class="container" style="width:500px;">
<h3 align="center">Insert and Display Images From Mysql Database in PHP</h3>
<br />
<form method="post" enctype="multipart/form-data">
<input type="file" name="image" id="image" />
<br />
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-info" />
</form>
<br />
<br />
<table class="table table-bordered">
<tr>
<th>Image</th>
</tr>
<?php
$query = "SELECT * FROM tbl_images ORDER BY id DESC";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
echo '
<tr>
<td>
<img src="data:image/jpeg;base64,'.base64_encode($row['name'] ).'" height="200" width="200" class="img-thumnail" />
</td>
</tr>
';
}
?>
</table>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#insert').click(function(){
var image_name = $('#image').val();
if(image_name == '')
{
alert("Please Select Image");
return false;
}
else
{
var extension = $('#image').val().split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
alert('Invalid Image File');
$('#image').val('');
return false;
}
}
});
});
</script>
Hope someone can help me. Thanks!

Select multiple items from one dropdown and insert into multiple rows of database

I want to allocate multiple individual courses to students with one row per student-course combination when the data is coming from a multi-select (checkboxes) field on a form. That is, the data is returned as a single result with multiple courses, and I want to split this up.
Short version: the teacher selects multiple courses from a single dropdown but I want to save data in multiple rows.
Here is my code.
<?php
$con = mysqli_connect('localhost','root');
mysqli_select_db($con,'sss_qr');
$q="select * from course_tb ";
$result=mysqli_query($con,$q);
?>
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Bootstrap Multi Select Dropdown with Checkboxes using Jquery in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css" />
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<h2 align="center">Bootstrap Multi Select Dropdown with Checkboxes using Jquery in PHP</h2>
<br /><br />
<form method="post" id="framework_form">
<div class="form-group">
<label>Select which Framework you have knowledge</label>
<select id="framework" name="framework[]" multiple class="form-control" >
<?php
if($result)
{
while($row=mysqli_fetch_array($result))
{
$course=$row["course_name"];
$code=$row["course_code"];
echo "<option value='$code'>$course</option>";
}
}
?>
</select>
</div>
<div class="form-group">
<input type="submit" class="btn btn-info" name="submit" value="Submit" />
</div>
</form>
<br />
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#framework').multiselect({
nonSelectedText: 'Select Framework',
enableFiltering: true,
enableCaseInsensitiveFiltering: true,
buttonWidth:'400px'
});
$('#framework_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data)
{
$('#framework option:selected').each(function(){
$(this).prop('selected', false);
});
$('#framework').multiselect('refresh');
alert(data);
}
});
});
});
</script>
and insert.php file
<?php
$connect = mysqli_connect("localhost", "root", "", "sss_qr");
if(isset($_POST["framework"]))
{
$framework = '';
foreach($_POST["framework"] as $row)
{
$framework .= $row . ', ';
}
$framework = substr($framework, 0, -2);
$query = "INSERT INTO allocoursestudent(course_code) VALUES('".$framework."')";
if(mysqli_query($connect, $query))
{
echo 'Data Inserted';
}
}
?>
so i solve the problem by using this code.
<?php
$con = mysqli_connect("localhost", "root", "", "sss_qr");
$course=$_POST['course'];
if($course)
{
foreach($course as $c)
{
$q="INSERT INTO allocoursestudent(course_code) VALUES('".$c."')";
mysqli_query($con,$q);
}
}
?>
Firstly, you need to create a new table that pairs the student and the courses.
Secondly, you need to display students in the form (dropdown menu).
After that, you can do something like this:
<?php
$connect = mysqli_connect("localhost", "root", "", "sss_qr");
if(isset($_POST["course_code"])){
$course_code = mysqli_real_escape_string($con, $_POST["course_code"]);
$student_id = mysqli_real_escape_string($con, $_POST["student_id"]);
$query = "INSERT INTO new_table_name(course_code, student_id) VALUES";
for($i=0; $i<count($course_code); $i++){
$query .= " ('".$course_code[$i] ."', '".$student_id[$i]."'),";
}
$query = substr($query, 0, -1);
if(mysqli_query($connect, $query)){
echo 'Data Inserted #'.$i;
}
}
?>

PHP click count with mysqli

I want to make a program what will count clicks after click button.
I have this code but it don't work. I use mysqli to connect to database and I use query to insert value to database and query to select from database.
<html>
<head>
<meta charset="UTF-8">
<title>Click</title>
</head>
<body>
<form action="#" method="post">
<input type="submit" name="click" value="Klikni mě">
<br>
<?php
if(isset($_POST["click"])){
$connection=new mysqli("hidden","hidden","hidden","hidden");
if($connection == false){
die("Sorry jako");
}
$query="INSERT INTO klik (klikcount) VALUES ('$klik')";
if($connection->query($query) == false){
die("Promiň");
}
$sql="SELECT klikcount FROM klik";
$result=$connection->query($sql);
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
echo $row["klikcount"];
}
}
$klik=$klik+1;
}
?>
</form>
</body>
</html>
thanks.
I try solve your code and I made some changes.
Change position of "$klik = $klik+1;"
Add another SELECT
My new code:
<html>
<head>
<meta charset="UTF-8">
<title>Click</title>
</head>
<body>
<form action="#" method="post">
<input type="submit" name="click" value="Klikni mě">
<br>
<?php
if(isset($_POST["click"])) {
$connection = new mysqli("hidden","hidden","hidden","hidden");
if($connection == false) {
die("Sorry jako");
}
$sql="SELECT klikcount FROM klik";
$result=$connection->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
$klik = $row["klikcount"];
}
}
$klik = $klik+1;
$query = "INSERT INTO klik (klikcount) VALUES ('$klik')";
if($connection->query($query) == false) {
die("Promiň");
}
$sql = "SELECT klikcount FROM klik";
$result = $connection->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["klikcount"];
}
}
}
?>
</form>
</body>
</html>

checking result from select query then compare to current value if available then should not insert

I am saving latlong with the help of geolocation api into mysql db but problem is same latlong are inserted in database.I am trying to check last row of my mysql table and then comparing with current latlong if both are same,it should not be executed.Please help me to get this..Thanks in advance.
$latitude = 19.1579;
$longitude = 72.9935;
$address = airoli;
$sql = "SELECT latitude FROM tracklatlong ORDER BY id DESC LIMIT 1";
$result = mysqli_query($sql, $conn);
$row = mysqli_fetch_array($result);
$currentlat = $_row["latitude"];
if($currentlat != $latitude){
$query = "INSERT INTO `tracklatlong` (latitude, longitude,address) VALUES ('$latitude','$longitude','$address')";
if($conn->query($query) === TRUE){
echo "success";
}
else{
echo "failed";
}
}
else{
echo"Already exists";
}
As understood you need to check weather the latitute or longitute is in database Table insert it only if found false.
I am using PHP Object oriented with mysqli prepared statements.
This code returns false only when both latitute and longitute are same.
if you want output to return false were any one matchs the output than just add OR operator in SELECT query.
Here is the table image with data
Here is html code :index.php
<?php
include('co_ordinate.php');
$newcoordinate = new co_ordinate();
?>
<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-md-6 col-md-offset-3" style="margin-top:100px;">
<form action="" method="post">
<div class="form-group">
<i>Add Latitute</i>
<input type="text" name="latitute" class="form-control">
</div>
<div class="form-group">
<i>Add Longitute</i>
<input type="text" name="longitute" class="form-control">
</div>
<div class="form-group">
<input type="submit" name="addcoordinate" class="btn btn-primary">
</div>
</form>
<?php
if(isset($_POST['addcoordinate'])){
$latitude = $_POST['latitute'];
$longitute = $_POST['longitute'];
$newcoordinate->getCo_ordinates($latitude,$longitute);
}
?>
</div>
</body>
</html>
Here is the class file :co_ordinate.php
<?php
class co_ordinate{
private $link;
function __construct(){
$this->link = new mysqli ('localhost','root','','example');
if(mysqli_connect_errno()){
die("connection Failed".mysqli_connect_errno());
}
}
function getCo_ordinates($latitude,$longitute){
$sql = $this->link->stmt_init();
if($sql->prepare("SELECT latitude,longitude FROM tracklatlong WHERE latitude=? AND longitude= ?")){
$sql->bind_param('dd',$latitude,$longitute);
$sql->execute();
$sql->store_result();
if($sql->num_rows > 0){
echo "The Co-Ordinates Already Exists";
}
else
{
$query = $this->link->stmt_init();
if($query->prepare("INSERT INTO tracklatlong (latitude,longitude) VALUES (?,?)")){
$query->bind_param('dd',$latitude,$longitute);
$query->execute();
echo "The Co-Ordinates Inserted Successfully";
}
}
}
else
{
echo $this->link->error;
}
}
}
?>

(PHP) The Image cannot be displayed because it contains errors

I've read almost all topics related to this. i dont know whats causing it.
This is code for showing images
<html>
<body>
<?php
mysql_connect('localhost','root','') or die("Unable to Connect: ".mysql_error());
mysql_select_db("punjabi") or die("Unable to Select Database: ".mysql_error());
$sql = "SELECT imagename, mimetype, imagedata
FROM images WHERE ID = 1";
$result = #mysql_query($sql);
if(!$result)
{
die(mysql_error());
}
$file = mysql_fetch_array($result);
$imagename = $file['imagename'];
$mimetype = $file['mimetype'];
$imagedata = $file['imagedata'];
header("content-type: $mimetype");
echo($imagedata);
?>
This is the code for inserting images
<!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>Add Post</title>
<style type="text/css">
*
{
margin:0px;
padding:0px;
}
</style>
</head>
<body bgcolor="#333333">
<?php if(isset($_POST['submit'])):
{
if (!is_uploaded_file($_FILES['uploadfile']['tmp_name']))
{
die("$uploadfile is not an uploaded file!");
}
$uploadfile = $_FILES['uploadfile']['tmp_name'];
$uploadname = $_FILES['uploadfile']['name'];
$uploadtype = $_FILES['uploadfile']['type'];
$uploaddesc = $_POST['desc'];
$tempfile = fopen($uploadfile,'rb');
$filedata = fread($tempfile,filesize($uploadfile));
$filedata = addslashes($filedata);
$sql = "INSERT INTO images SET
imagename = '$uploadname',
mimetype = '$uploadtype',
description = '$uploaddesc',
imagedata = '$filedata'";
$ok = #mysql_query($sql);
if (!$ok) die("Database error storing file: " .mysql_error());
$sql = "Select id from images where imagename = '$uploadname'";
$result = #mysql_query($sql);
if(!$result) die(mysql_error());
if(mysql_num_rows($result)!=1) die(mysql_error());
$row = mysql_fetch_array($result);
$imageid = $row['id'];
$title = $_POST['title'];
$content = $_POST['content'];
$sql = "INSERT into posts SET
title = '$title',
content = '$content',
imageid = '$imageid'";
if(!#mysql_query($sql))
{
die(mysql_error());
}
header("Location:http://localhost/punjabi/adminhome.php");
}
?>
<?php else: ?>
<div id="post">
<form action="<?php echo($_SERVER['PHP_SELF']) ?>" method="post" enctype="multipart/form-data" >
Title: <input type="text" name="title" /><br /><br /><br />
Content:<br /> <textarea cols=100 rows="40" wrap="hard" name="content" /></textarea><br /><br />
Image: <input type="file" name="uploadfile" /><br /><br />
Image Desc: <input type="text" name="desc" /><br /><br />
<input type="submit" value="Submit" name="submit" />
</form>
</div>
<?php endif; ?>
</body>
</html>
And This is the Table Structure:
CREATE TABLE filestore (
-> ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
-> FileName VARCHAR(255) NOT NULL,
-> MimeType VARCHAR(50) NOT NULL,
-> Description VARCHAR(255) NOT NULL,
-> FileData MEDIUMBLOB
->);
And Help would be appreciated!
The problem is that the headers have already been sent when you do:
<html>
<body>
<?php
So you cannot set the header for the image anymore:
header("content-type: $mimetype");
Just getting rid of the html (an image is not html / text) before the php tag should solve that.

Categories