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.
Related
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.
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.
I'm trying to make an iCalendar file via querying the database, so I don't have to make new iCalendar files with every event created.
<?php
header("Content-type: text/calendar");
$connection = mysqli_connect("localhost", "root", "");
$sql = "SELECT * FROM events WHERE eventID = '{$eventID}'";
$result = mysqli_query($connection, $sql);
$numrows = mysqli_num_rows($result);
// Render iCal file
?>
How to forbid file download if $_GET["eventID"] is not set?
In that case, I want instead of downloading, the visitor to get a blank page for an example.
Stick this at the top:
if (!isset($_GET["eventID"])) {
exit;
}
You should also do something after the SQL query, checking that it has actually returned a result. e.g.
if ($numrows == 0) {
exit;
}
if (!isset($_GET["eventID"])){
echo 'bad';
}else{
// your code here
}
The proper thing to do is the send a 404 Not Found HTTP status code if the URL/entity doesn't exist:
$result = mysqli_query($connection, $sql);
$event = $result->fetch_assoc();
if (!$event) {
header('HTTP/1.0 404 Not Found');
exit;
}
header("Content-type: text/calendar");
echo $event['title'];
..
Here I'm checking whether the event exists in the database. To handle a missing $_GET parameter you could send a 400 Bad Request separately.
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);.
I am new to this and I am having problems trying to get my website to count the number of times a files has been downloaded. The website has download buttons linking to the files which are stored on my database, and I would like to be able to count the amount of downloads per file to display as a statistic, ideally once they click the link to download, the column in the files table should be incremented, but I cannot wrap my head around it. please help?
<?php
error_reporting(E_ALL ^ E_NOTICE);
session_start();
$userid = $_SESSION['userid'];
$username= $_SESSION['username'];
?>
<?php
// Make sure an ID was passed
if(isset($_GET['id'])) {
// Get the ID
$id = ($_GET['id']);
// Make sure the ID is in fact a valid ID
if($id <= 0) {
die('The ID is invalid!');
}
else {
// Connect to the database
$dbLink = new mysqli('dragon.kent.ac.uk', 'repo', '3tpyril', 'repo');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Fetch the file information
$query = "
SELECT `mime`, `name`, `size`, `data`
FROM `files`
WHERE `id` = {$id}";
$result = $dbLink->query($query);
if($result) {
// Make sure the result is valid
if($result->num_rows == 1) {
// Get the row
$row = mysqli_fetch_assoc($result);
// Print headers
header("Content-Type: ". $row['mime']);
header("Content-Length: ". $row['size']);
header("Content-Disposition: attachment; filename=". $row['name']);
// Print data
echo $row['data'];
}
else {
echo 'Error! No files exists with that ID.';
}
}
else {
echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
}
#mysqli_close($dbLink);
}
}
else {
echo 'Error! No ID was passed.';
}
?>
The download link would point to a php file, such as download.php?id=123 -- this file would then take the ID and check the downloads database. If the ID exists, you run a query such as UPDATE files SET downloads = downloads + 1 WHERE id = 123.
Afterwards, you set the headers using header() to set content-type. Then use readfile().
See How to force file download with PHP on how to set headers and force a download.
Cheers!