Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to PHP and i have been trying to create a PDF file with images from the database.All the tutorial i have seen only put an image in the Header(not from the database) and only pull text from the database to put in the PDF.i am using FPDF to create my PDF files.Any guidelines or help to achieve this will be appreciated.
Let's say that you have a table called images, where the image URLs are stored under the column url. You can use FPDF and the MySQL adapter to construct a PDF out of all of the images like this:
require 'fpdf/fpdf.php';
// DB parameters
$host = "localhost";
$user = "username";
$pass = "password";
$db = "db";
// Create fpdf object
$pdf = new FPDF('P', 'pt', 'Letter');
// Add a new page to the document
$pdf->addPage();
// Try to connect to DB
$r = mysql_connect($host, $user, $pass);
if (!$r) {
echo "Could not connect to server\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Connection established\n";
}
// Try to select the database
$r2 = mysql_select_db($db);
if (!$r2) {
echo "Cannot select database\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Database selected\n";
}
// Try to execute the query
$query = "SELECT * FROM images";
$rs = mysql_query($query);
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Query: $query executed\n";
}
while ($row = mysql_fetch_assoc($rs)) {
// Get the image from each row
$url = $row['url'];
// Place the image in the pdf document
$pdf->Image($url);
}
// Close the db connection
mysql_close();
// Close the document and save to the filesystem with the name images.pdf
$pdf->Output('images.pdf','F');
References
http://blog.themeforest.net/tutorials/how-to-create-pdf-files-with-php/
http://zetcode.com/databases/mysqlphptutorial/
Related
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 3 years ago.
I'm having a bit of a weird problem.
I'm trying to read data of my database, the connection works but the instruction doesn't.
I try with code that should work, query("show tables"); but this also doesn't show anything.
Application is another php in which I make the connection and configuration with the database.
use Aplication as App;
class Company {
public static function login($username, $password) {
$app = App::getSingleton();
$conn = $app->conexionBd();
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$query = sprintf("SELECT * FROM company E WHERE E.Name= %s", $conn->real_escape_string($username));
$rs = $conn->query($query);
if ($rs)
{
$row = $rs->fetch_assoc();
$c = new Company($row['id'], $row['Name'],$row['Password']);
$rs->free();
return $c;
}
return false;
}
}
What is wrong?
Thanks in advance!
Best way to troubleshoot such problems is to print the query and run on mysql command prompt.
E.Name= %s should be changed to E.Name= '%s' as strings should be enclosed by quotes.
This question already has answers here:
Empty values being added to all mysql rows instead of just the target row
(2 answers)
Closed 6 years ago.
I am not so sure how to process an image in PHP to put it into a blob type in MYSQLI. Here is my code so far...
<?php
$servername = ""; //Taken out for stack overflow question
$username = ""; //Taken out for stack overflow question
$password = ""; //Taken out for stack overflow question
$dbname = ""; //Taken out for stack overflow question
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn)
{
echo 'Could not connect';
}
else
{
if (!empty($_FILES['cf'] && $_POST['category']))
{
$file = $conn->real_escape_string($_FILES['cf']['tmp_name']);
mysqli_query($conn, "INSERT INTO adDatabase(".$category.") VALUES(".$file.")");
}
else
{
echo 'Empty file';
}
}
mysqli_close($conn);
?>
Now the value of the image is not null so the image is processed. But I cant seem to get it processed. Normally I make a variable $var = $_POST['cf']; then I add that into the query. I also tried $var = $_FILES['cf']; but it wont process. Is there something else I need to do to it to make it send/process properly?
Edit based on answer
I changed my PHP to something that resembles an answer
<?php
$servername = ""; //Taken out for stack overflow question
$username = ""; //Taken out for stack overflow question
$password = ""; //Taken out for stack overflow question
$dbname = ""; //Taken out for stack overflow question
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn)
{
echo 'Could not connect';
}
else
{
if (!empty($_FILES['cf'] && $_POST['category']))
{
try
{
$file = $conn->real_escape_string($_FILES['cf']['tmp_name']);
$filecontents = File_Get_Contents($file);
$filecontentssafe = $conn->real_escape_string($filecontents);
mysqli_query($conn, "INSERT INTO adDatabase(".$category.") VALUES(".$file.")");
echo 'Query successful';
}
catch(Exception $e)
{
echo 'Could not perform action' + $e;
}
}
else
{
echo 'Empty file';
}
}
mysqli_close($conn);
?>
Now I see Query successful, however.. nothing goes into the database.
Edit - added retrieve file
<?php
$servername = "";
$username = "";
$passcode = "";
$dbname = "";
$conn = mysqli_connect($servername, $username, $passcode, $dbname);
if (!$conn)
{
echo 'Could not connect';
}
else
{
try
{
$sql_query = mysqli_query($conn, "SELECT * FROM `adDatabase`");
while ($row = mysqli_fetch_array($sql_query))
{
$id = $row['ID'];
$img = $row['img'];
$image = '<img src="data:image/png;base64,'.base64_encode( $row['food'] ).'" style="height: 12em; width: 12em; margin: 1em; padding: 0.9em; " >';
echo $image;
}
}
catch(Exception $e)
{
echo $e;
}
}
?>
How I retrieve information
By the time you call mysql, $file only contains a path to the temporary uploaded file, not the data you want.
If you want MySQL to look at the file's path, and load its contents directly into your database, have a look at the MySQL function LOAD_FILE() here: http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_load-file
Otherwise, if you'd like to do this in PHP, you'd want to pull the file's contents into a variable with something like
$file_contents=File_Get_Contents($file);
... and then use
$file_contents_safe=$conn->real_escape_string($file_contents);
before sticking $file_contents_safe into the database. Some people also like to Base64 encode.
Edit: Please also keep injection vulnerabilities in mind, as others have suggested. The name of the temporary file, and anything else coming in from post/apache shouldn't be trusted on its own.
If you don't have to stick with saving the blob content in the database, you could only save the file name in the database and do a regular file upload to a selected location. For that, you will need to add this before adding the content in the database
$tmp_name = $_FILES["filename"]["tmp_name"];
$name = $_FILES["filename"]["name"];
move_uploaded_file($tmp_name, "YOUR_UPLOAD_DIR/{$name}");
And after uploading the file, you just need to store it's name in the database instead of storing the blob content. When displaying, you just need to access the actual file in your upload folder and show it. It's much cleaner solution, especially if you don't have to migrate files between servers.
The whole code would look something like this:
if (!empty($_FILES['cf'] && $_POST['category']))
{
$tmp_name = $_FILES["cf"]["tmp_name"];
$name = $_FILES["cf"]["name"];
move_uploaded_file($tmp_name, "YOUR_UPLOAD_DIR/{$name}");
$file = $conn->real_escape_string($name);
mysqli_query($conn, "INSERT INTO adDatabase(".$category.") VALUES(".$file.")");
}
Then when accessing it, you will need to pull the data from the database and just display it. If it is an image, it could be
<img src="<?php YOUR_UPLOAD_DIR.'/'.$name ?>"/>
Otherwise:
To insert the image data in your database do:
$content = file_get_contents($tmpName);
$file = $conn->real_escape_string($content);
$mime_type = mime_content_type($tmpName);
mysqli_query($conn, "INSERT INTO adDatabase(".$category.", mime_type) VALUES(".$file.", ".$mime_type.")");
Note I added a mimetype to the insert, because you will need it in order to be able to display the file properly later.
Then, when you want to display it, just pull the content from the db and echo it together with the proper header.
header('Content-type:'.$mime_type);
echo $content;
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
this mycode
I'am try to edit but no success.
if(move_uploaded_file($_FILES["filUpload"]["tmp_name"],"docfile/".$_FILES["filUpload"]["name"]))
{
//*** Insert Record ***//
$file = $_FILES["filUpload"]["name"];
$fileup = mysql_real_escape_string($file);
$strSQL = "INSERT INTO fileproject(filename) VALUES($fileup);";
if(!$strSQL){
echo "<h1>Error Store FileName2DB<h1>";
exit;
}
echo "Upload Complete<br>";
}
you dont execute your query. You have to use your object to the database for query.
try
{
$bdd = new PDO('mysql:host=localhost;dbname=yourdb;charset=utf8', 'root', 'yourpassword',
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
if(move_uploaded_file($_FILES["filUpload"]["tmp_name"],"docfile/".$_FILES["filUpload"]["name"]))
{
//*** Insert Record ***//
$file = $_FILES["filUpload"]["name"];
$fileup = mysql_real_escape_string($file);
$strSQL = "INSERT INTO fileproject(filename) VALUES($fileup)";
$result=$bdd->query($strSQL);
if(!$strSQL){
echo "<h1>Error Store FileName2DB<h1>";
exit;
}
echo "Upload Complete<br>";
}
You are not using mysql extension for executing your query. Other example is about to PDO.
You can also INSERT the new row by using mysqli_* extension.
MYSQL procedural structure:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(move_uploaded_file($_FILES["filUpload"]["tmp_name"],"docfile/".$_FILES["filUpload"]["name"]))
{
//*** Insert Record ***//
$file = $_FILES["filUpload"]["name"];
$fileup = mysql_real_escape_string($file);
$strSQL = "INSERT INTO fileproject (filename) VALUES ('$fileup')";
// here you need to use mysqli_* extension
if(mysqli_query($conn, $strSQL)){
echo "Upload Complete<br>";
}
else{
echo "<h1>Error Store FileName2DB<h1>";
// exit;
}
}
mysqli_close($conn); // DATABASE CONNECTION CLOSE
?>
Side note:
As I mentioned in comments $fileup value is a string value so you need to use single quotes between the variable.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I've double-checked and everything looks closed to me, so I can't find the error. I just want to create a table to display mySQL data.
EDIT: I don't know why the closing tag was above the rest of the code, but I still get the error when it's in the correct place.
<?php
$servername = "localhost";
$username = “x”;
$password = “x”;
$dbname = “x”;
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM Classroom”;
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
echo “<tr><th>Building</th><th>Floor</th><th>Room</th><th>Instructional</th><th>Type<th>Size</th>
<th>Seating</th><th>Decking</th><th>Access</th><th>Whiteboard</th><th>Chalkboard</th></tr>”;
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo “<tr><td>”.$row[“building”].”</td></tr>”;
}
} else {
echo (“0 results”);
}
mysqli_close($conn);
}
?>
Edit: As per your original post https://stackoverflow.com/revisions/27974352/1
This should go at the very bottom:
?>
In fact, it isn't even required unless you're going to put some pure HTML after it. So leaving it out completely might save you headaches in the future.
However, several of your double-quotes look funky pasted here. You might check that they are just double-quotes, and not special characters.
These curly/smart quotes “ ” should be replaced by regular double quotes " throughout your code.
Those alone will break its functionality and cause a parse/syntax error.
Edit: As per your edit: You need to remove the last } in your file, the one just after mysqli_close($conn);. The number of braces do not match.
This works!
<?php
mb_internal_encoding('UTF-8');
$servername = "localhost";
$username = "x";
$password = "x";
$dbname = "x";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM Classroom";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
echo "<tr><th>Building</th><th>Floor</th><th>Room</th><th>Instructional</th><th>Type<th>Size</th>
<th>Seating</th><th>Decking</th><th>Access</th><th>Whiteboard</th><th>Chalkboard</th></tr>";
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>".$row["building"]."</td></tr>";
}
}else{
echo("0 results");
}
mysqli_close($conn);
?>
Remove ?> from all your documents, as it's unneeded, as PHP self closes at the end of a file.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Any one knows why my $result echo in footer instead of body? Is it an html maybe div problem or PHP?
Here is a something similar to what I have:
<?php
// 1. Create a database connection
$dbhost = "localhost";
$dbuser = "tester";
$dbpass = "12345";
$dbname = "practice";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Test if connection occurred.
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
?>
<?php
// 2. Perform database query
$SQLstring = "SELECT *FROM user ORDER BY username";
// Test if there was a query error
$QueryResult = #mysqli_query($connection, $SQLstring)
Or die("<p>Unable to execute query.</p>"
. "<p>Error code " . mysqli_errno($connection)
. ": " . mysqli_error($connection)) . "</p>";
?>
<!DOCTYPE>
<html>
<head>
</head>
<body>
<?php
//3. uses the mysqli_assoc() to print table
echo "<table>";
echo "<tr><th>Name</th><th>Address</th><th bgcolor='#0099FF'
align='left'>City</th><th bgcolor='#0099FF' align='left'>State</th></tr>";
$num_results = $QueryResult->num_rows;
for ($i=0; $i <$num_results; $i++) {
// 3. Use returned data (if any)
$Row = mysqli_fetch_assoc($QueryResult); //associative array
// output data from each row
echo "<tr><td>{$Row['username']}</td>";
echo "<td>{$Row['address']}</td>";
echo "<td>{$Row['city']}</td>";
echo "<td>{$Row['state']}</td>";
</tr>";
}
// 4. Release returned data - close query
mysqli_free_result($QueryResult);
?>
</body>
</html>
<?php
// 5. Close database connection
mysqli_close($connection);
?>
Any ideas? The table prints out fine no problem just not in the correct place on the site
echo "<td>{$Row['city']}</td>";
echo "<td>{$Row['state']}</td>";
</tr>"; //You got an error here!
}
I think you forgot to echo this line.
you should get parse error but i could not point that
just try change this lines
// output data from each row
echo "<tr><td>{$Row['username']}</td>";
echo "<td>{$Row['address']}</td>";
echo "<td>{$Row['city']}</td>";
echo "<td>{$Row['state']}</td>";
echo "</tr>";
}