I've migrated a access database with images on its fields to mysql.
When I try to visualize them with several php codes I get a broken image icon or I download php code (PHP: Retrieve image from MySQL using PDO) that I tried to use in a new try:
<?php
$con = mysqli_connect('localhost', 'root', '', 'access');
$query = mysqli_query($con,"SELECT EscudoClub FROM tclubs WHERE CodClub = 'C13'");
$imageData = mysqli_fetch_array($query, MYSQLI_ASSOC);
$image = $imageData['EscudoClub'];
header("Content-type: image/jpeg");
echo $image;
mysqli_free_result($query);
mysqli_close($con);
?>
With above code I get a broken image icon and using pdo I only get dowwnload php code I guess because some syntax problems:
//$dbName = $_SERVER["DOCUMENT_ROOT"]."\\..\db\\teknofo.mdb";
//$con = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=access; Uid=; Pwd=;");
$con = new PDO('mysql:host=localhost;dbname=access;charset=utf8', 'root', '');
$sql = "SELECT EscudoClub FROM tclubs WHERE CodClub = 'C13'";
$st = $con->prepare($sql);
$st->execute(array(17));
$st->bindColumn('photo', $photo, PDO::PARAM_LOB);
$st->fetch(PDO::FETCH_BOUND);
odbc_longreadlen($st, 131072);
odbc_binmode($st,ODBC_BINMODE_CONVERT);
ob_clean();
header('Content-Type: image/*');
if ($rd = $st->fetch(PDO::FETCH_BOUND))
{
echo $rd['photo'];
ob_end_flush();
$con = null;
}
?>
Please, could you help me with this?
Kind regards
When executing your statement, you provide an explicit parameter value (of 17)—but the statement does not contain any parameter placeholders! You're then attempting to bind a column named 'photo', which doesn't exist in the resultset. The odbc_* calls shouldn't be there either.
$con = new PDO('mysql:host=localhost;dbname=access;charset=utf8', 'root', '');
// DON'T USE ROOT USER !!!
$st = $con->prepare('SELECT EscudoClub FROM tclubs WHERE CodClub = ?');
$st->execute(array('C13'));
if ($rd = $st->fetch())
{
header('Content-Type: image/*'); // you should give an exact MIME type
echo $rd['EscudoClub'];
}
You should first map the $sql call from:
$sql = "SELECT EscudoClub FROM tclubs WHERE CodClub = 'C13'";
To :
"SELECT EscudoClub FROM tclubs WHERE CodClub = ':cod_club'";
$st = $con->prepare($sql);
$st->execute(array('cod_club' => 123456));
I don't know if this could solve your issue, but when you get straightly the PHP source code from a call, it is generally due to your server configuration (apache, nginx, etc.).
I would like to add that pictures on access database are stored as microsoft word pictures. I don't know if I should export them to any image format (jpeg, png..) before trying to display them. The problem is that I migrated all data from access database and there is a table with 1,3GB of photos.
Kind regards.
Related
I am running into an issue when querying an Image that is stored as a longblob from a MySQL. I understand that this is not an optimal way to do this, but it is a requirement for the project I am working on.
The server that is running on my local machine is running and querying the data properly, but the live server doesn't return the images properly (the browser believes that the file is corrupted). The code is the same on both devices. The returned longblob from the server has the same sum as the files that was created on the local environment (both files have the same data in theory).
Are there any settings that could be enabled that would cause this to fail on a live server vs a local environment?
Simplified code for creating the image in the database
$productImage = "images/" . time() . $productImageImage["name"];
move_uploaded_file($productImageImage["tmp_name"] , $productImage);
$productImageImage = file_get_contents($productImage);
$query = $connection->prepare("INSERT INTO product (productImage) VALUES (?)");
$query->bind_param("s", $ProductImageImage);
$result = $query->execute();
Code for displaying the file
<?php
header("Content-Type: image/jpeg");
include 'include/db_connection.php';
function getId(){
if(isset($_GET['id']))
$selected = $_GET['id'];
return $selected;
}
function alt_getImage($connection){
$s = getId();
$query = $connection->prepare("SELECT productImage FROM product WHERE productId = ?");
$query->bind_param("i", $s);
$query->execute();
$result = $query->get_result();
return $result;
}
function createImage($connection, $id){
if ($id != null){
$result = alt_getImage($connection);
$row = $result->fetch_assoc();
echo $row["productImage"];
$connection->close();
}
}
$id = $_GET['id'];
$connection = createConnection();
createImage($connection, $id);
?>
My code:
<?php
try {
$t = '040485c4-2eba-11e9-8e3c-0231844357e8';
if (array_key_exists('t', $_REQUEST)) {
$t = $_REQUEST["t"];
}
if (!isset($_COOKIE['writer'])) {
header("Location: xxx");
return 0;
}
$writer = $_COOKIE['writer'];
$dbhost = $_SERVER['RDS_HOSTNAME'];
$dbport = $_SERVER['RDS_PORT'];
$dbname = $_SERVER['RDS_DB_NAME'];
$charset = 'utf8' ;
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname};charset={$charset}";
$username = $_SERVER['RDS_USERNAME'];
$password = $_SERVER['RDS_PASSWORD'];
$pdo = new PDO($dsn, $username, $password);
$stmt = $pdo->prepare("select writer from mydbtbl where writer=? and t=?");
$stmt->execute(array($writer, $t));
$num = $stmt->fetch(PDO::FETCH_NUM);
if ($num < 1) {
header("Location: login.php");
return 0;
}
$dbMsg = "Authorized";
$dbname = 'imgs';
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname};charset={$charset}";
$pdo = new PDO($dsn, $username, $password);
if (isset($_FILES['filename'])) {
$name = $_FILES['filename']['name'];
// set path of uploaded file
$path = "./".basename($_FILES['filename']['name']);
// move file to current directory
move_uploaded_file($_FILES['filename']['tmp_name'], $path);
// get file contents
$data = file_get_contents($path, NULL, NULL, 0, 60000);
$stmt = $pdo->prepare("INSERT INTO file (contents, filename, t) values (?,?,?)");
$stmt->execute(array
($data,
$name,
$t)
);
$dbMsg = "Added the file to the repository";
// delete the file
unlink($path);
}
} catch (Exception $e) {
$dbMsg = "exception: " . $e->getMessage();
}
In the code you will see that the first part is for doing authentication. Then I create a new PDO object on the img schema, and do my file insert query after that.
Later, where I am printing out $dbMsg, it is saying "added file to the repository". But when I query the database (MySQL on Amazon AWS using MySQL Workbench) nothing has been inserted.
I don't understand why if nothing is getting inserted I am not getting an error message. If it says "added file to the respository", doesn't that mean the insert was successful? The only thing I can think is that using a different schema for this is mucking things up. All of my inserts to ebdb are going through fine
--- EDIT ---
This question was marked as a possible duplicate on my query about not getting an error message on my insert / execute code. This was a useful link and definitely something I will be aware of and check in the future, but ultimately the answer is the one I have provided regarding the terms of service for my aws account
The answer is that the (free) amazon account policy I am working under only allows me to have 1 database / schema. When I switched the table over to ebdb it worked right away. I am answering my own question (rather than deleting) so hopefully others using AWS / MySQL can learn from my experience.
So I'm working on a PHP Pastebin-esque project on my freetime to learn PHP and server management, and I've run into a LOT of issues, and I haven't been able to solve them. I decided to restart from sratch on my own with the information I've gathered so far, and threw this code together.
<?php
require 'connection.php';
$getid = $_GET["id"];
$sql = 'SELECT paste FROM pasteinfo WHERE id=:id';
$stmt = $con->prepare($sql);
$stmt->bind_param(':id', trim($_GET["id"], PDO::PARAM_INT));
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['paste'];
}
?>
What I'm trying to achieve with this code is a system where a user can type the id of whatever paste they're interested in viewing in the url and have it display the pasteinfo row, which is the row that holds the paste itself. The format they should have is viewpaste.php?id=(user input).
How can I fix this code? I would also greatly appreciate if you explain whatever code you might end up putting in the comments so I can learn from it. Thanks!
Try this;
connection.php
try{
$db = new PDO('mysql:host=localhost;dbname=database_name;charset=utf8mb4', 'database_username', 'database_password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $ex){
echo $ex->getMessage();return false;
}
function retrieve($query,$input) {
global $db;
$stmt = $db->prepare($query);
$stmt->execute($input);
$stmt->setFetchMode(PDO::FETCH_OBJ);
return $stmt;
}
To retrieve data, call the retrieve() function
Retrieval page, say display.php
require 'connection.php';
$getid = $_GET["id"];
$result=retrieve("SELECT paste FROM pasteinfo WHERE id=?",array($getid));
$row=$result->fetch();
//To get paste column of that id
$paste=$row->paste;
echo $paste;
I've create a table where I've saved images through "LongBLOB". I need to show those images.
i can save images in my sql but when i want to read and display them i have a problem,
"can not be displayed because it contains errores"
im usi8ng this code to save the image to my sql table
<?php
$username = "root";
$password = "";
$host = "localhost";
$database = "imgtest";
$link = mysql_connect($host, $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database);
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$namee = $_FILES['image']['name'];
mysql_query("INSERT INTO image(cap,image) VALUES ('$namee','$data')");
}
?>
and im using this code to read and display the image from my sql table
<?php
$con=mysqli_connect("localhost","root","","imgtest");
$wich=$_POST['wich'];
$resoult=mysqli_query($con,"SELECT * FROM image WHERE id LIKE '$wich'");
$imgd = $_GET['img'];
$row = mysqli_fetch_array($resoult);
$image = $row['image'];
header("content-type:image/jpeg");
echo $image;
?>
anyone can help me with this??
It is strongly advised to store images within your file structure (a directory on your server, cloud server, or other accessible location) and only keep a reference such as a url, file name or path path in the database in order to recreate a link or path to the actual image. It is a bad practice to keep images in a database.
Why are you using mysql_ library - it is deprecated.
You need to store binary data. Use prepared statements. In that way you get back binary data.
From 2 you can dump addslashes. That is the root of the problem
I need to get some data from a Microsoft SQL Server database at work. When I have the data I need, I need to make an Excel spreadsheet that can be saved locally on my computer.
I found PHPExcel which seems to do the job on the Excel part, but what about getting the data from the Database?
I can't seem to find anything that's recent. Only old tutorials.
Use this way to Fetch the Records :
<?php
$hostname = "192.168.3.50";
$username = "sa";
$password = "123456";
$dbName = "yourdb";
MSSQL_CONNECT($hostname,$username,$password) or DIE("DATABASE FAILED TO RESPOND.");
mssql_select_db($dbName) or DIE("Database unavailable");
$query = "SELECT * FROM dbo.table";
$result = mssql_query( $query );
for ($i = 0; $i < mssql_num_rows( $result ); ++$i)
{
$line = mssql_fetch_row($result);
print( "$line[0] - $line[1]\n");
}
?>
This will fetch each rows from the Data Retrieve and Print on the Page. Use your Required format into that. I mean, Use html Table to show the data in well format.
Use this code to get an data from Database.
<?php
// Server in the this format: <computer>\<instance name> or
// <server>,<port> when using a non default port number
$server = '192.168.3.50';
// Connect to MSSQL
$link = mssql_connect($server, 'sa', 'sa');
if (!$link) {
die('Something went wrong while connecting to MSSQL');
}
else{
echo "connected ";
mssql_select_db('Matrix') or die("Wrong DATAbase");
//mssql_query("SELECT Seq_no from dbo.Trans_R WHERE Seq_no = 000001",$link) or die("cannot execute the query");
$query = mssql_query("SELECT Tr_Date,Tr_Time,Tr_Data from Matrix.dbo.Trans_R");
$f = mssql_fetch_array($query);
echo $f['Tr_Date'];
}
?>
Can i know why Negative Vote??
He asked me to :
" but what about getting the data from the Database?"