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);
?>
Related
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.
I'm trying to delete an image from data base as well as from a folder in PHP5, but I am unable to delete it. Here is my code:
<?php
$obj=new Crud("localhost","root","","3g");
class Crud{
public $mysqli;
public $data;
public function __construct($host,$username,$password,$db_name) {
$this->mysqli = new mysqli($host, $username, $password, $db_name);
if (mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
} /*else{
echo"Your Database successfully connected";
}*/
}
public function __destruct() {
$this->mysqli->close();
}
public function read() {
$query="SELECT * FROM fashion";
$result= $this->mysqli->query($query);
$num_result=$result->num_rows;
if ($num_result>0) {
while($rows=$result->fetch_assoc()){
$this->data[]=$rows;
//print_r($rows);
}
return $this->data;
}
}
public function delete($id){
$query="DELETE FROM fashion WHERE id='$id'";
$result= $this->mysqli->query($query) or die(mysqli_connect_errno() . "Data cannot inserted");
if ($result) {
header('location:fashion.php');
}
}
}
?>
By using the above code, the record was deleted only from database, but the image remains in the folder.
To delete an image from your folder you have to use unlink
$file = "yourimage.jpg";
unlink($file);
if image is in any other directory you have to specify full directory Path like
$file = "www/images/yourimage.jpg";
The solution you are looking for is the unlink function which does that - unlinks and deletes a file.
You need the name of the file and the path to the file from the PHP current working directory to make it work. Kamrans answer shows this.
So:
public function delete($id){
$query = "SELECT filepath FROM fashion WHERE id = ? LIMIT 1";
$fileLocale = $this->mysqli->prepare($query);
$fileLocale->bind_param("i",$id);
$fileLocale->execute();
$result = $fileLocale->get_result();
$fileLocale->close();
while ($row = $result->fetch_array(MYSQLI_NUM))
{
/***
* only 1 result is returned so easy to collect
***/
foreach ($row as $r)
{
$filepath = $r;
}
}
unset($r,$row);
/***
$filepath is now the string of the location of the file.
***/
if (unlink($filepath)){
$query="DELETE FROM fashion WHERE id=? LIMIT 1";
$delete = $this->mysqli->prepare($query);
$delete->bind_param("i",$id);
$delete->execute();
$affectedRows = $delete->affected_rows;
if ($affectedRows == 1) {
header('location:fashion.php');
die();
}
when using header always place a die command after it.
use unlink to delete a file, it will return TRUE on success.
filepath is the column in your database that you store the file location.
connect and use the database using OOP principles, use prepared statements rather than queries, there is FAR less risk to you or your code.
Add LIMIT to your SQL statements so if there is an issue, it will not mess up your whole table, for example. A safety measure.
Before you delete the database reference, use it to fill the file name, which is what I am assuming is stored in the database. If $id is the file name, just add it into a system command to remove the file. This assumes Linux.
public function delete($id){
exec('rm /path to file/' . $id);//delete the file via system command.
$query="DELETE FROM fashion WHERE id='$id'";
$result= $this->mysqli->query($query) or die(mysqli_connect_errno() . "Data cannot inserted");
if ($result) {
header('location:fashion.php');
die();
}
}
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.
Here's what the situation is: I am trying to use PHP to call scanimage on a Linux host, then save the resulting file to a web directory for future use.
The below code produces no errors, but when I check out the /tmp directory, file.pnm is blank, and the scanner never starts.
<?php
require('/var/www/olin/includes/functions.php');
$con = connect_db();
//setup the POST variables
if (isset($_POST['submit'])) {
$fname = mysqli_real_escape_string($con, $_POST['fname']);
$lname = mysqli_real_escape_string($con, $_POST['lname']);
$license_no = mysqli_real_escape_string($con, $_POST['license_no']);
$comments = mysqli_real_escape_string($con, $_POST['comments']);
}
if ($license_no == '') {
$license_no = "None on File";
}
if ($fname == '' || $lname == '') {
echo '<h1 class="message">Can\'t submit visitor: you are missing information!</h1>';
} else {
//setup the query and prepare it for exection
$query= "insert into visitors (fname, lname, license_no, redsheet, comments)" .
" values (?, ?, ?, 'Allow', ?) on duplicate key update fname = values(fname)," .
"lname = values(lname), license_no = values(license_no), redsheet = values(redsheet)," .
"comments = values(comments)";
$stmnt= mysqli_prepare($con, $query);
//bind the statement parameters to variables
mysqli_stmt_bind_param($stmnt, "ssss", $fname, $lname, $license_no, $comments );
//execute, then close the statment
if (!mysqli_stmt_execute($stmnt)) {
echo "Failed to ececute the query: " . mysqli_error($con);
header('Refresh: 10; url=http://localhost/olin/visitor.php');
}
}
// we'll `try` to scan the license if the checkbox is selected
if (isset($_POST['pic_id'])) {
// get the info from the db
$query = 'select id from visitors where license_no = "'.$license_no.'"';
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
$id = $row['id'];
// set up the path to save the id to (and put path into db for further look up
// and display)
$dir = ( $id % 30 );
$path = '/var/www/olin/images/licenses/'.$dir.'/'.$id.'-license.png';
$path = addslashes(mysqli_real_escape_string($con, $path));
$path1 = '/images/licenses/'.$dir.'/'.$id.'-license.png';
// start the scan, and save image
$command = '/home/jmd9qs/bin/scan.sh "'.$path.'"';
$update = 'update visitors set id_pic = "'.$path1.'" where id="'.$id.'"';
mysqli_query($con, $update) or die ('Error: ' . mysqli_error($con));
exec($command);
header('Location: http://localhost/olin/visitor.php');
}
}
?>
Can anybody provide any hints?
UPDATE:
I have the server running the command now (I know it's failing because of the Apache2 error log).
Here's the error I get:
scanimage: open of device brother3:bus2;dev1 failed: Invalid argument
I've tried adding the www-data user to the scanner and lp groups, but it seems to have no effect... The scanimage command I'm using works under my normal user and as root, so I'm now positive the command I'm using should work. I am still at a loss...
UPDATE (again):
I've fixed some errors in my code... now the server will scan and successfully save images! However, it only works once and then for some odd reason I have to run the scan.sh (which I put the scanimage command into) through my shell for it to run again... otherwise I get the same error message!
Very weird, I have NO clue why, suggestions wanted!
I've read a lot of posts on this general subject but I still can't seem to figure it out.
I'm building a Mac/PC desktop application. When a user first authorizes the app, I want to store their info in an online Mysql database. I'm using the JUCE library to call and handle a php file online which in turn handles the updating of the online database. On my desktop app:
String url = "http://www.syntorial.com/onlinePHPFileToCall.php?email=" + email + "&computer=" + SystemStats::getComputerName();
URL authURL(url);
InputStream *input = authURL.createInputStream(true);
String result = input->readString();
And the php file:
<?php
$result = "";
$mysqli = new mysqli('localhost','username','password','dbname');
if (mysqli_connect_errno())
{
$result = "connection failed";
}
else
{
$mysqli->select_db("UserInfo");
$email = $_GET['email'];
$computer = $_GET['computer'];
$query = "UPDATE UserInfo SET computer = '$computer' WHERE email = '$email'";
if ($queryResult = $mysqli->query($query))
{
$result = "true";
}
else
{
$result = "false";
}
}
echo $result;
?>
The result comes back "true" on my desktop app, but the information doesn't actually get saved into the database. If instead of
InputStream *input = authURL.createInputStream(true);
I use:
authURL.launchInDefaultBrowser();
it opens up the php file in a browser and everything works fine. Any ideas what I'm doing wrong?
Joe,
Seems like one of your first question on this forum. So Welcome. You mentioned you want to store information in an online database. But while connecting you added db information about your local via
mysqli('localhost',
. Update localhost to point to an online database by finding its ip address/servername, username and password. Also you will have to ensure the computer where you run this application can connect to that online db.
Here is what I am ran on my local and worked for me.
<?php
$result = "";
$mysqli = new mysqli('localhost','root','','test');
if (mysqli_connect_errno())
{
$result = "connection failed";
}
else
{
$email = "xyz#yahoo.com";
$computer = "1mycomp";
$query = "UPDATE so1 SET computer = '$computer' WHERE email = '$email'";
/*
Printing the query to check what is being executed.
Remove the below line after program works.
*/
echo $query;
if ($queryResult = $mysqli->query($query))
{
$result = "true";
}
else
{
$result = "false";
}
}
echo $result;
Turns out the "true" argument in CreateInputStream was telling it to use POST data instead of GET so the call was ignoring the GET data. Thanks the help.