cannot display picture using php on the page - php

I am trying to dynamically display a picture based on the the entry on the database. I can see i am able to build the url from where the picture has to be fetched but it doesn't display the picture.. I am not able to figure out what is happening.. any help will be appreciated.
// Connect to the database
$dbhost = 'localhost';
$dbusername = 'vote';
$dbpasswd = 'vote';
$database_name = 'vote_active';
$connection = mysql_connect("$dbhost","$dbusername","$dbpasswd")
or die ('Couldn\'t connect to server.');
$db = mysql_select_db("$database_name", $connection)
or die('Couldn\'t select database.');
$sqlMain = ("SELECT DISTINCT number, comments, Engineer, votes FROM active_nomination;");
$lqlMain = mysql_query($sqlMain) or die(mysql_error());
while($lplMain = mysql_fetch_assoc($lqlMain)){
$enge = utf8_encode($lplMain['Engineer']);
//print $enge;
$url= "http://wwwin.kabi.com/dir/photo/prof/$enge.jpg";
print $url;
echo
'<td>;
<img src="<?php $url ?>" />
</td>';
}
?>

Change the echo line to
echo '<td><img src="'.$url.'" /></td>';
You were not properly string concatenating. Also there is no need for wrapping variables within php tags when you are already within the PHP block.

Related

Retrieving image from php mysql database using specific id inserted by user

I created a page for Inserting Image with some data into database in php/mysql .
Table Structure
name Varchar(20) |
rollno Varchar(50) PRIMARY KEY |
address Varchar(100) |
image LONGBLOB
but i don't know how to retrieve it using roll no. i.e. when user insert roll no in a text box and click on submit it should display all the details of that roll no including image.
I am Using below code for image displaying.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "galleryupload";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `vision` where `rollno` = VCI/2012-13/C/03"; // manipulate id ok
$sth = mysqli_query($conn,$sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image_file'] ).'"/>'
?>
Actually, you do not have to use Javascript for this (Unless you want to retrieve and display the image without reloading the page).
You can do this by having the form and the script responsible for retrieving image in the same php file. Firstly, display the form (it will be displayed even after it was submitted, and image shown):
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<input type="text" name="rollno">
<input type="submit" name="Search">
</form>
Then, let's check if a POST request was received, lookup and display the image. I am using Jay S. code for DB connection.
<?php
if (isset($_POST['rollno'])) {
$rollno = htmlspecialchars($_POST['rollno']);
$db = new PDO('mysql:host=localhost;dbname=testdb;', 'username', 'password');
$stmt= $db->prepare("SELECT * FROM table WHERE rollno = :rollno");
$stmt->execute(array(":rollno", $rollno));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$row = $rows[0];
//display info about image
?>
<div class="row-info">
<span>Name: </span>
<span><?php echo $row['name'] ?></span>
</div>
<div class="row-info">
<span>Rollno: </span>
<span><?php echo $row['rollno'] ?></span>
</div>
<div class="row-info">
<span>Address: </span>
<span><?php echo $row['address'] ?></span>
</div>
<div class="image">
<img src="<?php echo $row['image'] ?>"/>
</div>
<?php
}
Of course, you should add your own markup to display the information.
Ok, I am assuming this textbox is on and HTML page, so you would need to use Javascript to get the information from the server, where the MySQL database is. You will need a php page on the server that the Javascript can call. For this answer, i'll just name it getRecord.php. Also, to make the JavaScript alot easier, I recommend using jQuery. I will be assuming you know ho to use that in this answer.
Javascript
var rollno = $("#inputbox").val();
$.get("getRecord.php",{
data: {rollno : rollno},
success: function(data){
data = JSON.parse(data);
//Display the data how you wish
}
);
getRecord.php
<?
$rollno = $_GET['rollno'];
//For the Database retrieval part, I'm going to assume you are using PDO, but if you're using mysqli, just translate this
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$stmt= $db->prepare("SELECT * FROM table WHERE rollno = :rollno");
$stmt->execute(array(":rollno", $rollno));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows[0]);
//Because this should only return one row, im doing [0]. After echo, this will be sent back to the Javascript where the success function will execute
?>
// this is the code of get.php page...
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "galleryupload";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `vision` where `rollno` = VCI/2012-13/C/03"; // manipulate id ok
$sth = mysqli_query($conn,$sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image_file'] ).'"/>'
?>

display stored procedure on my website (php, mssql)

I'm whole new to stored procedures and mssql so i have no idea where to start with my code. I've tried to google/search around the forum but i dont understand the code.
Here is my scenario:
I've got the name of some stored procedures that i'm trying to display on my website using php. I have the name of the server(mssql), i've got the name of the database and i have a username and password to the server.
I've used Toad and tried the stored procedures(with success) and now im just trying to put together some code where i can display the results of the stored procedures on my website.
Firstly i've tried to just display the results of a stored procedure without parameters but nothing happens...
<?php
$server = "myServername";
$username = "myUsername";
$password = "myPassword";
$database = "myDatabase";
$connect = mssql_connect($server, $username, $password) or die ("Couldn't connect to SQL Server");
mssql_select_db($database, $connect) or die ("Couldn't open database");
$query = mssql_init("usp_ThisIsMyStoredProcedure", $connect);
$result = mssql_execute($query);
while ($row = mssql_fetch_row($result)) {
echo "<li>" . $row[0] . "</li>";
}
?>
My website only displays: -->" . $row[0] . ""; } ?> <--
please feel free to come with tips on how i can restructure my code!
(don't have enough reputation to comment your post so i post here).
Shouldn't you add the value you want ?
Like
echo "<li>" . $row[0]->{'id'} . "</li>";
echo "<li>" . $row[0]->{'nickname'} . "</li>";
for example ...

UPDATING mysql data using PHP

I am trying to display a Website Title on my Home Page. This website title is stored in the database named mywebsite and in table settings. I want to update this with an input type text's value. The title is displayed perfectly but when I write something in the text field and submit it, the database doesn't update. I think I am doing everything right and there isn't any error displaying on my page, but still it is not working. Can anyone figure out the error?
Here's my code:
<?php
// Some database detail
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'mywebsite';
// Making connection
$con = mysqli_connect($host, $username, $password, $database);
// Making a sql query for "Website Title" and saving it in variable $query
$query = "SELECT * FROM settings WHERE NameOfSetting='Website Title'";
// Applying query
$result = mysqli_query($con, $query);
// Fetching data from database
$row = mysqli_fetch_array($result);
if (isset($_POST['submit'])) {
$title = $_POST['text'];
mysqli_query($con, "UPDATE settings SET TheSetting=$title WHERE NameOfSetting='Website Title'");
}
?>
<h1><?php echo $row['TheSetting']; ?></h1>
<form method="POST">
<input type="text" placeholder="Change the title" name="text">
<input type="submit" name="submit">
</form>
EDIT: When I enter any numbers in the field and then submit and refresh it works fine but it's only working with numbers not with alphabets. I don't know why?
This line:
SET TheSetting=$title
$title needs to be wrapped in quotes:
SET TheSetting='$title'
Sidenote: You may also want to change this line (as a security precaution):
$title = $_POST['text'];
to:
$title = mysqli_real_escape_string($con,$_POST['text']);
Try with
mysqli_query($con, "UPDATE settings SET TheSetting='$title' WHERE NameOfSetting='Website Title'");
Well you can always do some sort of error checking. I.e. using or die(mysqli_error);
$con = mysqli_connect($host, $username, $password, $database)or die(mysqli_error);
This will atleast give you an idea of what your proplem is. Use this error checking method every time you connect, query, or close a database.
use this code it will solve your problem.
<?php
// Some database detail
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'mywebsite';
// Making connection
$con = mysqli_connect($host, $username, $password, $database)or die(mysqli_error());
// Making a sql query for "Website Title" and saving it in variable $query
$query = "SELECT * FROM settings WHERE NameOfSetting='Website Title'";
// Applying query
$result = mysqli_query($con, $query);
// Fetching data from database
$row = mysqli_fetch_array($result);
if (isset($_POST['submit'])) {
$title = $_POST['text'];
mysqli_query($con, "UPDATE settings SET TheSetting='".$title."' WHERE NameOfSetting='Website Title'");
}
?>
<h1><?php echo $row['TheSetting']; ?></h1>
<form method="POST">
<input type="text" placeholder="Change the title" name="text">
<input type="submit" name="submit">
</form>

SQL Server Database Query with PHP

I need to get some data from a Microsoft SQL Server database at work. When I have the data I need, I need to make an Excel spreadsheet that can be saved locally on my computer.
I found PHPExcel which seems to do the job on the Excel part, but what about getting the data from the Database?
I can't seem to find anything that's recent. Only old tutorials.
Use this way to Fetch the Records :
<?php
$hostname = "192.168.3.50";
$username = "sa";
$password = "123456";
$dbName = "yourdb";
MSSQL_CONNECT($hostname,$username,$password) or DIE("DATABASE FAILED TO RESPOND.");
mssql_select_db($dbName) or DIE("Database unavailable");
$query = "SELECT * FROM dbo.table";
$result = mssql_query( $query );
for ($i = 0; $i < mssql_num_rows( $result ); ++$i)
{
$line = mssql_fetch_row($result);
print( "$line[0] - $line[1]\n");
}
?>
This will fetch each rows from the Data Retrieve and Print on the Page. Use your Required format into that. I mean, Use html Table to show the data in well format.
Use this code to get an data from Database.
<?php
// Server in the this format: <computer>\<instance name> or
// <server>,<port> when using a non default port number
$server = '192.168.3.50';
// Connect to MSSQL
$link = mssql_connect($server, 'sa', 'sa');
if (!$link) {
die('Something went wrong while connecting to MSSQL');
}
else{
echo "connected ";
mssql_select_db('Matrix') or die("Wrong DATAbase");
//mssql_query("SELECT Seq_no from dbo.Trans_R WHERE Seq_no = 000001",$link) or die("cannot execute the query");
$query = mssql_query("SELECT Tr_Date,Tr_Time,Tr_Data from Matrix.dbo.Trans_R");
$f = mssql_fetch_array($query);
echo $f['Tr_Date'];
}
?>
Can i know why Negative Vote??
He asked me to :
" but what about getting the data from the Database?"

How to include variables from one page in another when writing a file with fwrite()?

Here's the code:
<?php
// For use in creating individual page
$tpl_file = "submission.php";
$tpl_path = "templates/";
$submissions_path = "submissions/";
// For use in querying submitter name
$username = $_GET['username'];
session_start();
$_SESSION['username'] = $username;
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$name = $_POST['name'];
$filename = $_POST['filename'];
$submitter = $username;
list($width, $height) = getimagesize("$filename");
$type = exif_imagetype($_POST['filename']);
$checkuser = mysql_query("SELECT filename FROM images WHERE filename='$filename'");
$filename_exist = mysql_num_rows($checkuser);
if($filename_exist > 0){
echo "I'm sorry but this image has already been submitted. Please feel free to try another.";
unset($filename);
include 'upload.php';
exit();
}
if (exif_imagetype($_POST['filename']) == IMAGETYPE_GIF) {
echo "Sorry, but we can't accept GIFs. Please feel free to try uploading another.";
unset($filename);
include 'upload.php';
exit();
}
$query = "INSERT INTO images (name, filename, submitter, width, height, type)
VALUES('$name', '$filename', '$submitter', '$width', '$height', $type)";
mysql_query($query) or die(mysql_error());
mysql_close();
echo "Thanks for your submission!<br/> Upload another <a href='/~lyons/upload.php'>here</a>!";
$tpl = file_get_contents($tpl_path.$tpl_file);
$php_file_name = $name.".php";
$fh = fopen($submissions_path.$php_file_name, "w");
fwrite($fh, $tpl);
fclose($fp);
?>
When a user submits a picture, it is supposed to automatically create a page based on a template. Here's the code for the template:
<html>
<title><?php echo $name; ?></title>
<head>
</head>
<body>
<h1><?php echo $name ?></h1>
Posted by: <?php echo $username ?>
<br/>
<img src="<?php echo $filename ?>"/>
</body>
</html>
As you might have already guessed, I want it to put in values for name, username, and filename that were derived in the first script where they submit the picture. However, it seems they don't carry over. The page is created, but where ever it's supposed to echo the values for the variables, it is blank. How can I include the values for those variables that I want to use in the created page?
Thanks in advance to whoever can help me.
I would suggest using a string like %name%, %username% etc. to mark placeholders for variables.
Then, before writing to the file, try something like this:
$tpl = preg_replace("(%([a-z_][a-z0-9_]*)%)ie",'$$1',$tpl);
This will find, for example, %filename% and replace it with the contents of the variable $filename.
Look up PHP Sessions
It is a built-in feature to PHP used for exactly what you're doing.
Sessions store data on a per-user basis however, so if you're wanting other people to see the variables, you're going to have to use either a database or saving to a file.

Categories