How to include pdf (getting with php script from db) into HTML - php

I want to include a pdf into html.
I´ll get the PDF File from a DB.
The PHP works fine and shows me the pdf in the Browser PDF-Reader.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
//MySQL Verbindung hier einfügen
$mysqli = new mysqli("ip", "root", "password", "name");
if ($mysqli->connect_errno) {
die("Connection refused: " . $mysqli->connect_error);
}
try{
$sql = "SELECT file FROM Master_Ordner_AMS WHERE id = 1";
$result = mysqli_query($mysqli, $sql);
$row = mysqli_fetch_object($result);
header('Content-type: application/pdf');
$pdf = $row->file;
}catch(Exception $e){
echo "caught exception: ", $e->getMessage(), "\n";
}
?>
If i want to add it in a simple html to custumize it, it doesnt work..
Just want a little div around it or sth. else

Well you can create an iframe and display the pdf file inside the iframe. You can customize the border of the iframe using CSS.

Related

load default image if database connection fails

I am attempting to build a database driven site whereby images are loaded via a php script like so;
<img src="get_image.php?holderID=2">
I can get images to load from a folder outside the root directory when the database is accessible but I also want to be able to load a default image if there is a failure with making the database connection. The DB connection is initiated form a separate php connection file mysqli_template_connect.php;
DEFINE('DB_USER', 'someusername');
DEFINE('DB_PASSWORD', 'amnesia');
DEFINE('DB_HOST', 'localhost');
DEFINE('DB_NAME', 'template');
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
and then config.inc.php sets some constants, one of which is for all DB connections;
define('MYSQL', '../../../dbconnect/mysqli_template_connect.php');
The get_image.php file then has a database connection conditional;
require('includes/config.inc.php');
REQUIRE(MYSQL);
$holderID = $_GET['holderID'];
if(!$dbc){
$image_name = 'img/unavailable.png';
$info = getimagesize($image_name);
header("Content-Type: {$info['mime']}\n");
readfile($image_name);
}
else {
$query = "SELECT imageID FROM image_holder WHERE image_holderID = $holderID ";
$result = #mysqli_query($dbc, $query);
$number_rows = mysqli_num_rows($result);
if ($number_rows == 1) {
$row = mysqli_fetch_array($result, MYSQLI_NUM);
$imageID = $row[0];
}
else {
$imageID = FALSE;
}
if ($imageID) {
$query = "SELECT file_name FROM image WHERE imageID = $imageID";
$result = mysqli_query($dbc, $query);
$number_rows = mysqli_num_rows($result);
if ($number_rows == 1) {
$row = mysqli_fetch_array($result, MYSQLI_NUM);
$image_name = '../../../uploads/' . $row[0];
}
else {
$image_name = 'img/unavailable.png';
}
}
else {
$image_name = 'img/unavailable.png';
}
$info = getimagesize($image_name);
header("Content-Type: {$info['mime']}\n");
readfile($image_name);
mysqli_close($dbc);
}
If I disable the MYSQL database in XAMP, the default image unavailable.png will not load even though the header and readfile section of code is virtually the same in the section of code that does work. I'm quite a newbie to all this so any ideas on loading the default image would be appreciated.
Depending on the database object you are using (MySQLi/PDO/etc), you can check if they connected. PDO returns a boolean that you can run against.
Since PDO is the most popular, I will provide an example of that. If you use something else, feel free to comment and I can clarify.
$connected = true;
if (!extension_loaded('PDO'))
{
$connected = false;
}
if (!extension_loaded('pdo_mysql'))
{
$connected = false;
}
try
{
$pdo = new PDO("mysql:host={$host};dbname={$db}", $user, $pass);
}
catch(PDOException $e)
{
$connected = false;
}
if(!$connected){ /* Load default image */ }
Note: just make sure you use the correct image headers.
Instead of
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
Use
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
hopefully it should work..
I have similar code that do the almost the same thing.
I suspect it was the header, since I have a bit more info added to the header. No harm for you to try out.
header('Content-Description: File Transfer');
header('Content-Type: '. $file_content_type);
header('Content-Length: ' . filesize($file_full_path));
header('Content-Disposition: inline; filename=' . $file_name);
readfile($file_full_path);

PHP Mysql view PDF file error

I was trying to view a PDF from my a MySQL database but it gets stuck on loading.
Here's my code:
<?php
header("Content-type: application/pdf");
$con = mysqli_connect("localhost","root","username","password");
//check if errors occur in connection to database
if (mysqli_connect_errno())
{
//return the error
echo mysqli_connect_error();
}
$filename = $row['name'];
$query = "SELECT content from images WHERE id = 7";
$result = mysqli_query($query,$con)or die(mysqli_error());
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
echo $row['content'];
?>
You can use dompdf or TCP pdf library for better and extended functionality.
or try to use ob_clean() method in starting of the line.
or remove first header("Content-type: application/pdf"); and check whether query is working or not.

Converting from mysql to mysqli and getting Fatal error: Cannot use object of type mysqli as array

I am working on converting some PHP code from mysql to mysqli. I have created an error and am unable to understand how to fix it. Any suggestions would be greatly appreciated.
The code looks like this:
<?php
include ("admin/includes/connect.php");
$query = "select * from posts order by 1 DESC LIMIT 0,5";
$run = mysqli_query($conn["___mysqli_ston"], $query);
while ($row=mysqli_fetch_array($run)){
$post_id = $row['post_id'];
$title = $row['post_title'];
$image = $row['post_image'];
?>
The error produced is: Fatal error: Cannot use object of type mysqli as array
The error is being called out on this line:
$run = mysqli_query($conn["___mysqli_ston"], $query);
In the line above $conn is a variable from the database connect file which has this code:
<?php
// Stored the db login credentials in separate file.
require("db_info.php");
// Supressing automated warnings which could give out clues to database user name, etc.
mysqli_report(MYSQLI_REPORT_STRICT);
// Try to open a connection to a MySQL server and catch any failure with a controlled error message.
try {
$conn=mysqli_connect ('localhost', $username, $password) or die ("$dberror1");
} catch (Exception $e ) {
echo "$dberror1";
//echo "message: " . $e->message; // Not used for live production site.
exit;
}
// Try to Set the active MySQL databaseand catch any failure with a controlled error message.
try {
$db_selected = mysqli_select_db($conn, $database) or die ("$dberror2");
} catch (Exception $e ) {
echo "$dberror2";
//echo "message: " . $e->message; // Not used for live production site.
exit;
// We want to stop supressing automated warnings after the database connection is completed.
mysqli_report(MYSQLI_REPORT_OFF);
}
?>
This line
$run = mysqli_query($conn["___mysqli_ston"], $query);
should be
$run = mysqli_query($conn, $query);
If you're migrating to mysqli, you should really read these docs at least.
The proper way to use a mysqli connection:
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$res = $mysqli->query("SELECT id FROM test ORDER BY id ASC");
while ($row = $res->fetch_assoc()) {
echo " id = " . $row['id'] . "\n";
}
?>
you should also consider utilizing mysqli's prepared statements

Template in export mysql to excel in php

I export from MySQL to Excel with this code.
I have no problem when executing this code without CMS,
but when I use this code in my CMS the template is in export and I want to get this query result.
$db_name = "test";
$link = mysql_connect("localhost", "root", "") or die("Could not connect to server!");
$table_name = 'users';
$select_db = mysql_select_db($db_name, $link);
mysql_query("SET NAMES 'utf8'");
$query = "SELECT * from users";
$result = mysql_query($query, $link) or die("Could not complete database query");
$num = mysql_num_rows($result);
$num2=mysql_num_fields($result);
$header="";
for ($i = 0; $i < $num2; $i++) {
$header .= mysql_field_name($result, $i) . "\t";
}
if ($num != 0) {
$_xml ="<?xml version='1.0' encoding='UTF-8' standalone='yes'?>\r\n";
$_xml.="<dataroot xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>\r\n";
while ($row=mysql_fetch_array($result)){
$_xml .="\t<qq>\r\n";
if($row[0]<>'') $_xml.="\t\t<q>".$row[0]."</q>\r\n";
if($row[1]<>'') $_xml.="\t\t<a>".$row[1]."</a>\r\n";
$_xml.="\t</qq>\r";
}
$_xml.="</dataroot>";
header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
header("Lacation: excel.htm?id=yes");
print($_xml);
} else {
echo "No Records found";
}`enter code here`
I dont know if I understand your problem. But in the end you are talking about getting a query-result. ALSO you defined an attachment into the header. You cant get output on your website AND download a file at the same step.
If output is generated, the download will be corrupted. So you have to decide: Output or download. If you really need both another way would be: First generate your output, then redirect the user to a blank download-page which appends the attachment. If correctly done, you should visually stay on your main-page while the download-page loads up the attachment after the output on your main-page is done.
Correct me if I got something wrong here.
Ps: Instead of
$var = "";
better use
unset($var);.

Attempting to display an image in PHP from a MySQL database

I attempted to display the image using PHP with the following code
<?php
header('Content-type: image/png');
$port = "*";
$server = "*:".$port;
$dbname ="*";
$user = "*";
$conn = mysql_connect ("$server", "$user", "$pass") or die ("Connection
Error or Bad Port");
mysql_select_db($dbname) or die("Missing Database");
$speakerPic = $_POST['speakerPic'];
$query = "SELECT Speaker.speaker_picture AS image FROM Speaker JOIN Contact c USING(contact_id)
WHERE c.lname = '";
$query .= $speakerPic."';";
$result = mysql_query($query,$dbname);
$result_data = mysql_fetch_array($result, MYSQL_ASSOC);
echo $result_data['image'];
?>
I keep on receiving this error, The image “.../query2.php” cannot be displayed because it contains errors.
Sorry to keep on bugging you guys, but can anyone tell what the problem is?
Not going to lie, there is a lot of bad with the OP code.
You should be pulling images from the database by id, not some string
You are not sanitizing the var being used in the query
You are not serving a default image if one doesn't exist
Also, I would suggest storing file uris in your database, not the actual image (blob). You should store a pointer to an image on your filesystem.
Not going to clean up the code too much, just make it less bad. I'd suggest something along these lines (untested):
// Utility.php
class Utility
{
/**
*
* #param mixed $id is abstract, could be name or an actual id
* #return string?
*/
public static function getImage($id)
{
try {
$port = "*";
$server = "*:".$port;
$dbname ="*";
$user = "*";
$conn = mysql_connect ("$server", "$user", "$pass");
if (!$conn) {
throw new Exception("Connection Error or Bad Port");
}
if (!mysql_select_db($dbname)) {
throw new Exception("Missing Database");
}
$query = "SELECT Speaker.speaker_picture AS image FROM Speaker JOIN Contact c USING(contact_id) WHERE c.lname = " . mysql_real_escape_string($id). ";";
$result = mysql_query($query,$dbname);
$result_data = mysql_fetch_array($result, MYSQL_ASSOC);
if (!isset($result_data['image'])) {
throw new Exception('Image not found');
}
echo $result_data['image'];
} catch Exception($e) {
error_log($e->getMessage();
return file_get_contents('/path/to/some/default/image.png');
}
}
}
// image.php
require_once 'Utility.php';
header('Content-type: image/png');
ob_start();
Utility::getImage($_POST['speakerPic']);
$image = ob_get_flush();
echo $image;

Categories