Showing images from path in mysql database - mysql

I'm trying to get an understanding of how to retrieve an images from a path stored in mysql database. I have the path as sumple images
Here's the code that I have tried so far.
<?php include 'database.php'; ?>
<!Doctype html>
<html>
<head>
<title>The Image</title>
</head>
<body>
<?php
$sql = 'Select * from images';
$result = mysql_query($sql) or die('Crazy man');
while($row = mysql_fetch_assoc($result))
{
$url = 'http://localhost/image_path/'. $row[image_path];
echo "<img src='$url' height='200' width='200' />";
}
?>
</body>
</html>

Based on your code below
while($row = mysql_fetch_assoc($result))
{
$url = 'http://localhost/image_path/'. $row[image_path];
echo "<img src='$url' height='200' width='200' />";
}
I think you need to change it to something like this
while($row = mysql_fetch_assoc($result))
{
$url = 'image_path/'. $row[image_path];
echo "<img src='$url' height='200' width='200' />";
}
Take note that I removed the http://localhost/
in your $url = 'http://localhost/image_path/'. $row[image_path];
Whenever you try to load images the default directory is automatically loaded so you can just put /image_path/blah-blah directly.

Related

(HY000/2005): Unknown MySQL server host 'fdb32.awardspace.net:3306' (-2) Connection failed: Unknown MySQL server host 'fdb32.awardspace.net:3306' (-2)

Hi all I a new to sql so I apologise in advance. My link is http://suteki.atwebpages.com/test.php and the error I keep getting is
Warning: mysqli::__construct(): (HY000/2005): Unknown MySQL server
host 'fdb32.awardspace.net:3306' (-2) in
/srv/disk20/4134947/www/suteki.atwebpages.com/connect.php on line 8.
Connection failed: Unknown MySQL server host
'fdb32.awardspace.net:3306' (-2)
I am using awardspace and I have all the details correct for port and host db name etc. but this is driving me up the wall. I have searched online and every other similar error found does not relate to my problem. My connect.php is as posted below:
><?php
>$servername = "fdb32.awardspace.net:3306";
>$username = "xxXXXXxx";
>$password = "xxxxxxxx";
>$dbname = "suteki";
>// Create connection
>$conn = new mysqli($servername, $username, $password, $dbname, 3306);
>// Check connection
>if ($conn->connect_error) {
>die("Connection failed: " . $conn->connect_error);
>}
>?>
My test.php is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="description" content="This is a Japanese Restaurant website">
<link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght#600&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Noto+Serif+TC:wght#300&display=swap" rel="stylesheet">
<link rel="stylesheet" href="main.css">
<link rel="icon" href="https://stpierres.co.nz/images/20190329151614.png"/>
<title>素てきSuteki Test</title>
<style>
.orderHere {
display: inline-block;
width: 70%
}
#orderH {
display:flex;
flex-direction: row;
flex-wrap: wrap;
}
</style>
</head>
<body style="background-color:black";>
<div class="box banner">
<h1>素 て き</h1>
</div>
<!-- navigation -->
<div class="box nav">
HOMEPAGE
MENU
ORDER
CONTACT US
TEST
</div>
<!--main content-->
<div class="content">
<h1>Database</h1>
<?php
require_once 'connect.php';
$sql = "SELECT menu.*, order_total.* FROM menu, order_total WHERE menu.menu_id = order_total.menu_id";
$result = $conn->query($sql);
echo '<h1 class="orderHere">Order Here</h1>';
echo '<section id="orderH">';
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo '<article>';
echo '<h2>' . $row["Title"] . '</h2>';
echo '<figure><img src=' . $row["Image"] . ' height="150" width="150"> </figure>';
echo '<p><span id="title">Menu Item: </span><span>'. $row["item_title"] . '</span></p>';
echo '<p><span id="title">Description: </span><span>'. $row["description"] . '</span></p>';
echo '<p><span id="title">Menu Item: </span><span>'. $row["item_title"] . '</span></p>';
echo '<p><span id="title">Price: </span><span>'. number_format((float)$row["price"], 2, '.', '') . '</span></p>';
echo '</article>';
}
}
echo '</section>';
?>
</div>
</body>
Any help would be greatly appreciated - thank you kindly.
thanks so much for your assistance. I have changed my connect.php accordingly, however its still not playing nice
connect_error) {
die("Connection failed: " . $conn->connect_error); }
?>

Real time html editor for download

I like solution in this post Real-Time Html editor with Javascript or editor on this site. Just simple solution without extra functionalities.
How to edit the code to add SAVE/LOAD option? Is there somethin like "downloadable little CMS" to play with HTML/CSS? I want upload it to my hosting, easy access from home/phone/work, I do not want use online services like codepen or Liveweave.
thanks!
EDIT: Due to comments, I will clarify my question. I have some hosting, mySite.com. There is folder with this magic editor, mySite.com/xxx where i have some sample images and some basic css etc.. Im learning html/css, so I developing some basic html temapltes. HTML editor I linked is just fine. Only I need add 3 buttons, NEW/OPEN/SAVE which make new html file/can open it in live editor/and save it. AND I WANT HAVE THIS EASY SOLUTION ON MY OWN HOSTING.
<?php
$fileName = "page.html";
$fileContent = fopen($fileName, "r") or die("Unable to open file!");
if (isset($_POST['text'])) {
file_put_contents($fileName, $_POST["text"]);
}
?>
<!DOCTYPE html><html lang="cs"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.error {background-color: red; color: white;}
</style>
</head><body>
<form method="POST">
<textarea name="text" class="form-control" rows="20" id="pure">
<?php echo fread($fileContent,filesize($fileName)); ?>
</textarea><br>
<input type="submit" value="submit" />
</form>
<hr>
<div id="compiled"></div>
</body>
</html>
<?php
fclose($fileContent);
?>
<script type="text/javascript">
var h = document.getElementById("pure");
var compiled = document.getElementById("compiled");
h.onkeyup = function() {
compiled.innerHTML = h.value;
pure.classList.toggle("error",
compiled.innerHTML !== h.value);
};
h.onkeyup();
</script>
Its my actual work, real-time html editor from link in my question. File "page.html" must exist.
Added func. to load content from "page.html" file into textarea when page loads..
Added button to save textarea content to "page.html" when done..
Probably not perfect code, and for multiple projects must copy into diferent folders and load one by one :( no popup or form to choose diferent filename easily.. but for now it fits my requirements. I can learn/try/work on html template from home/work/mobile on my own hosting without login into third party service.
Ok, I'm done. Here is my final solution.
real-time html editor
Load/save buttons
automatically load files from /projects/ folder into dropdown list
you can upload files to make new project
no need to modify anything, you can just use it.
Index.php
<?php
$fileName = $_POST['project']?? 'index.html';
$fileContent = fopen("./projects/" . $fileName, "r") or die("Unable to open file!");
if (isset($_POST['text'])) {
file_put_contents("./projects/" . $fileName, $_POST["text"]);
}
?>
<!DOCTYPE html><html lang="cs"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.error {background-color:red; color:white;}
.dib {display:inline-block;}
</style>
</head><body>
<?php
echo "<form class='dib' method='POST'><select name='project'>";
$path = './projects/';
$files = scandir($path);
$files = array_diff(scandir($path), array('.', '..'));
foreach($files as $file){
echo "<option" . (($fileName == $file)?' selected':'') . ">" . $file . "</option>";
}
echo "</select> <input type='submit' value='Load!'></form>";
?>
<input type='submit' form='content' value='Save!'>
<form class="dib" style="float:right;" action="fileUploadScript.php" method="post" enctype="multipart/form-data">
Upload a File:
<input type="file" name="the_file" id="fileToUpload">
<input type="submit" name="submit" value="Start Upload">
</form>
<p style='margin:auto; text-align:center; width:20%; text-transform:uppercase; font-weight: bold;'><?php echo $fileName?></p>
<br>
<form id="content" method="POST">
<textarea name="text" rows="40" id="pure" style="width:100%;margin-top:8px;" wrap="off">
<?php echo fread($fileContent,filesize("./projects/" . $fileName)); ?>
</textarea><br>
<input type="hidden" name="project" value="<?php echo $fileName; ?>">
</form>
<hr>
<div id="compiled"></div>
</body>
</html>
<?php
fclose($fileContent);
?>
<script type="text/javascript">
var h = document.getElementById("pure");
var compiled = document.getElementById("compiled");
h.onkeyup = function() {
compiled.innerHTML = h.value;
pure.classList.toggle("error",
compiled.innerHTML !== h.value);
};
h.onkeyup();
</script>
fileUploadScript.php
<?php
$currentDirectory = getcwd();
$uploadDirectory = "/projects/";
$errors = []; // Store errors here
$fileExtensionsAllowed = ['jpeg','jpg','txt','bmp','html','htm','rar','zip','7z','doc','docx','xls','xlsx','ppt','pptx','pdf','pptm','png','gif']; // These will be the only file extensions allowed
$fileNamee = $_FILES['the_file']['name'];
$fileSize = $_FILES['the_file']['size'];
$fileTmpName = $_FILES['the_file']['tmp_name'];
$fileType = $_FILES['the_file']['type'];
$tmp = explode('.',$fileNamee);
$fileExtension = strtolower(end($tmp));
$uploadPath = $currentDirectory . $uploadDirectory . basename($fileNamee);
if (isset($_POST['submit'])) {
if (! in_array($fileExtension,$fileExtensionsAllowed)) {
$errors[] = "This file extension is not allowed. Please upload a JPEG or PNG file";
}
if ($fileSize > 4000000) {
$errors[] = "File exceeds maximum size (4MB)";
}
if (empty($errors)) {
$didUpload = move_uploaded_file($fileTmpName, $uploadPath);
if ($didUpload) {
echo "The file " . basename($fileNamee) . " has been uploaded";
} else {
echo "An error occurred. Please contact the administrator.";
}
} else {
foreach ($errors as $error) {
echo $error . "These are the errors" . "\n";
}
}
}
?>
After you save these two files, dont forget make new folder named "projects" and default file called "index.html" in this folder..

problem with redirect page on Facebook login

I am trying to use Facebook login on my website with inserting Facebook user data on my database.
I have those files as shown below :
index.php:
session_start();
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" type="text/css" href="css/preload.css?ve=5"/>
<title>Myexpect</title>
</head>
<body>
<?php
if ($_SESSION['FBID']):
require_once('connections/connect.php');
?> <!-- After user login -->
<div id="warper">
<div class="logo">
<img width="150px" height="150px"src="images/Logo - Copy.png">
</div>
<div class="welcome">
<h2>Welcome to our website</h2>
</div>
<div class="preload">
<img width="50" height="50px"src="loading.gif">
</div>
</div>
<?php
echo '<meta http-equiv = "refresh" content = "3; url = games.php" />'
?>
<?php else: ?> <!-- Before login -->
<div class="container">
<div><img src="images/fb-login-btn.png" ></div>
</div>
<?php endif ?>
</body>
</html>
fbconfig.php :
<?php
session_start();
// added in v4.0.0
require_once 'autoload.php';
require 'dbconfig.php';
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\Entities\AccessToken;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;
// init app with app id and secret
FacebookSession::setDefaultApplication( 'xxxxxxxxxxxx','xxxxxxxxxxxxxx' );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper('https://xxxxx/fbconfig.php' );
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
}
// see if we have a session
if ( isset( $session ) ) {
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
$fbid = $graphObject->getProperty('id'); // To Get Facebook ID
$fbfullname = $graphObject->getProperty('name'); // To Get Facebook full name
$femail = $graphObject->getProperty('email'); // To Get Facebook email ID
/* ---- Session Variables -----*/
$_SESSION['FBID'] = $fbid;
$_SESSION['FULLNAME'] = $fbfullname;
$_SESSION['EMAIL'] = $femail;
$check = mysqli_query($connection,"select * from Users where Fuid='$fbid'");
$check = mysqli_num_rows($check);
if (empty($check)) { // if new user . Insert a new record
$query = "INSERT INTO Users (Fuid,Ffname,Femail) VALUES ('$fbid','$fbfullname','$femail')";
mysqli_query($connection,$query);
} else { // If Returned user . update the user record
$query = "UPDATE Users SET Ffname='$ffname', Femail='$femail' where Fuid='$fuid'";
mysqli_query($connection,$query);
/* ---- header location after session ----*/
header("Location: index.php");
} } else {
$loginUrl = $helper->getLoginUrl();
header("Location: ".$loginUrl);
}
?>
The problem i have is when user try to login successfully it is not redirect to index.php file but fbconfig.php with a code :
https://xxxx/fbconfig.php?code=AQAAuanQBQ9lmXsAgbCuRB3aYy3YEEhrd81VBMMjih5oHo4dK_C7zMkQPZnuX5EdVvRJ2v4ybyAQ3EZ7qTzIrK9Oo-uY0KWiA6ZjNVh_4I6J7_AZDsJ12f7LGfc8EAGwgAfWwAm2Scwkx0UON9Vpjj75SBg7TX7n....etc
when i click back it work correctly and index.php work
how can i solve this
Sorry it was variables name mistake
this code is wrong :
$query = "UPDATE Users SET Ffname='$ffname', Femail='$femail' where Fuid='$fuid'";
i changed it to :
$query = "UPDATE Users SET Ffname='$fbfullname', Femail='$femail' where Fuid='$fbid'";
and it is work now

Convert excel file to HTML table in Symfony2

I just want to display a Excel file in a twig view with a Symfony2.5 Controller.
With PHPExcel, I can do this trick and it works :
<?php
error_reporting(E_ALL ^ E_NOTICE);
require_once '/../Classes/PHPExcel.php';
$filename = 'filename.xlsx';
$reader = PHPExcel_IOFactory::createReaderForFile($filename);
$excel = $reader->load($filename);
$writer = PHPExcel_IOFactory::createWriter($excel, "HTML");
?>
<html>
<head>
</head>
<style>
<?php
echo $writer->generateStyles(true);
?>
</style>
<body>
<?php
echo $writer->generateSheetData();
?>
</body>
</html>
How can I do the same thing in my Controller in Symfony 2.5 ?
Actually i have this :
public function newAction()
{
$filename = 'filename.xls';
$reader = \PHPExcel_IOFactory::createReaderForFile($filename);
$excel = $reader->load($filename);
$writer = \PHPExcel_IOFactory::createWriter($excel, "HTML");
echo $writer->generateStyles();
echo $writer->generateSheetData();
}
What should i have in my render view ?
Thanks for help !

How to escape HTML elements when fetching an array in PHP using Javascript?

I think the problem is in the "aif.php" file"
I am trying to fetch and display an array using PHP but the HTML element <br> is showing up in my result from the following scrip. I know I have to escape the HTML tags but I'm just not sure how! Also, any other advice on this code would be greatly appreciated (i.e. is there any redundancy or areas to improve? Thanks.
HTML
<DOCTYPE! html>
<html>
<head>
<title>The Auditors' Report: Data Entry</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<header><h1>Work Station<h1></header>
<div = id="leftnav">
<h2>Select Action</h2>
Name: <input type="text" id="name">
<input type="submit" id="grab" Value="Grab">
</div>
<div id="content"></div>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="aif.js"></script>
</body>
</html>
PHP - config (filename: "config.php")
<?php
$dbhost = "localhost";
$dbname = "x";
$dbuser = "y";
$dbpass = "z";
$dsn = "mysql:host=$dbhost;dbname=$dbname";
$dbh = NULL
?>
PHP - query / resulting content (filename: "aif.php")
<?php
require "config.php";
$dbh = new PDO($dsn, $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = "SELECT * FROM table1 LIMIT 0,10";
$sth = $dbh->prepare($sql);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo $row['field1'],"<br>";
echo $row['field2'],"<br>";
echo $row['field3'],"<br>";
}
?>
Javascript
$('input#grab').on('click', function() {
var name = $('input#name').val();
if ($.trim(name) !='') {
$.post('aif.php', {name: name}, function(data) {
$('div#content').text(data);
});
}
});
If you want to html encode a line like this:
this is <br /> a test
into a line like this:
this is <br /> a test
Use the nifty little function described here: HTML-encoding lost when attribute read from input field
I made a simple error in the Javascript. I wanted to pass back HTML and not TEXT.
With the following change, the PHP is rendered properly:
$('div#content').text(data);
to
$('div#content').html(data);