Im my project only image name are stored to SQL So that i can display it using name and image file is stored in folder
My problem is unable to display image since i have to specify path
<?php
// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = '3ss';
$userdb = 'sanoj';
$passdb = '123456';
try {
// Connect and create the PDO object
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
// Define and perform the SQL SELECT query
$sql = "SELECT * FROM `mobile` where id=50";
$result = $conn->query($sql);
// Parse returned data, and displays them
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo $row['id']. '/'. $row['mcat']. '/'. $row['image1']. '/'.'<li><img src=\poster\process\mobile\thumb\"',$row['image1'],'"></li>' .'/'. $row['image3']. '<br />';
}
$conn = null; // Disconnect
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
You can use php variables inside the html tag. This should work:
.'<li><img src=\poster\process\mobile\thumb\$row["image1"]></li>'
It is important that you are consistent with when to use double quotes and when not to. the $row should have different quotes than the ones surrounding the html tag.
Related
I have this code i am trying to create a sitemap from and i need some help. When i run the php file i get the output of the file on the screen but no sitemap.xml file is created, anyone know why ?
<?
$xmlfile = 'sitemap.xml';
// this variable will contain the XML sitemap that will be saved in $xmlfile
$xmlsitemap = '<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
// Connection data (server_address, name, password, database_name)
$hostdb = 'localhost';
$userdb = 'user';
$passdb = 'ps';
$namedb = 'db';
try {
// Connect and create the PDO object
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
// Define and perform the SQL SELECT query
$sql = "SELECT id, shortUrl FROM shorturl WHERE id BETWEEN 15 AND 45000";
$result = $conn->query($sql);
// If the SQL query is succesfully performed ($result not false)
if($result !== false) {
// Parse the result set, and add the URL in the XML structure
foreach($result as $row) {
$xmlsitemap .= '
<br><br>
<url><br>
<loc>https://website.com/'. $row['shortUrl'] .'<loc><br>
<changefreq>monthly<changefreq>
<priority>1<priority><br>
<url>
';
}
}
You have to write the content of your $xmlfile variable to a file.
Try file_put_contents('sitemap.xml', $xmlfile); after the foreach loop.
But i am wondering whether <br> works in xml
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 am trying to import data from a CSV file to my table using PHP. I have tried using the exact same code without the backslash for ENCLOSED BY '"' on phpmyadmin and the import is successful.
I have also checked the user permissions for admin.
Here is my code:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$pdo = new PDO('mysql:dbname=mydatabase;host=localhost;charset=utf8', 'admin', 'admin');
$pdo->exec('SET CHARACTER SET utf8');
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try{
$query = $pdo->prepare("LOAD DATA LOCAL INFILE 'C:\feed.csv' IGNORE INTO TABLE tablename
fields terminated by ','
enclosed by '\"'
lines terminated by '\n'
IGNORE 1 LINES
(field1, field2, field3, field4)", array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));
$query->execute();
$query->fetchAll();
} catch (PDOException $e) {
echo 'error: ' . $e->getMessage();
}
?>
When running this code I am seeing this error:
General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.
I don't no what is wrong in your code but you can use my code it is help full to you I think
I have implement this code and it is tested code. I think it is very use full
You have follow some rule:-
1.your csv file according to database table name (ex: db table name is users then csv should be users.csv)
2.Your csv file's first row should be db table fields name (ex: Id, name etc) after the start your data entry
3.you can download data source class from :- http://code.google.com/p/php-csv-parser/ because i have require below the code: require_once 'CSV/DataSource.php';
<?php
ini_set('memory_limit','512M');
$dbhost = "localhost";
$dbname = "excel_import";
$dbuser = "root";
$dbpass = "";
$conn=mysql_connect ($dbhost, $dbuser, $dbpass) or die ("I cannot connect to the database because: " . mysql_error());
mysql_select_db($dbname) or die("Unable to select database because: " . mysql_error());
require_once 'CSV/DataSource.php';
$filename = "users.csv";
$ext = explode(".",$filename);
$path = "uploads/".$filename;
$dbtable = $ext[0];
import_csv($dbtable, $path);
function import_csv($dbtable, $csv_file_name_with_path)
{
$csv = new File_CSV_DataSource;
$csv->load($csv_file_name_with_path);
$csvData = $csv->connect();
$res='';
foreach($csvData as $key)
{
$myKey ='';
$myVal='';
foreach($key as $k=>$v)
{
$myKey .=$k.',';
$myVal .="'".$v."',";
}
$myKey = substr($myKey, 0, -1);
$myVal = substr($myVal, 0, -1);
$query="insert into ".$dbtable." ($myKey)values($myVal)";
$res= mysql_query($query);
}
if($res ==1)
{
echo "record successfully Import.";
}else{
echo "record not successfully Import.";
}
}
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 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;