How to show image using php? - php

I am just starting to use html, php, and mysql. I've successfully logged into my database using php, and formed a query. I now want to go a step further and show a picture instead of just strings or numbers.
The variable 'result' will be returning a string that has a url to an image i want to display on this webpage. How would I do this?
<html>
<head>
<title>My First Question</title>
</head>
<body>
<?php
$dbhost = 'someURL.com';
$dbname = 'user';
$dbuser = 'user';
$dbpass = 'password';
$mysql_handle = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Error Connecting To Database Server");
mysql_select_db($dbname, $mysql_handle)
or die("Error selecting database: $dbname");
echo 'Successfully connected to database!';
$first = 'bobbie';
$query = sprintf("SELECT image FROM Player
p WHERE name='%s'", mysql_real_escape_string($first));
$result = mysql_query($query);
mysql_close($mysql_handle);
?>
</body>
</html>

Inside PHP, This will turn your SQL response into a usable variable.
$result = mysql_fetch_assoc(mysql_query($query));
Outside of your PHP tags, Echo the URL from the table into the SRC of an IMG element.
<img src="<?= $result['url_column_name'] ?>"/>
This will create a new IMG element with the source being the URL that you have fetched from your SQL query.
Short tags are also a way of echoing PHP variables in HTML.
<?= $var1, $var2 ?>
is the equivalent of using
<?php echo $var; echo $var2; ?>

This is a simple case of echoing the relevant HTML. You'll also have to fetch the results after you execute the query -
$result = mysql_query($query);
$data = mysql_fetch_assoc($result);
echo '<img src="'.$data['image'].'" />;
For added security, a good practice would be to escape any possible unwanted HTML content in your images path - htmlspecialchars($data['image']).
It should also be noted here that you are using a very old deprecated method to access your database. You might want to think about updating your code to use more modern PDO methods.

So what? simply use it as a source to your image
<?php $imgname = mysqli_fetch_array($connection, $result); ?>
<img src="<?php echo $imgname['image_column_name']; ?>" />
And btw use mysqli_() or PDO instead of using mysql_() as community is not maintaining it anymore

Once you update your mysql to mysqli you can echo the image's url in an html img tag as so:
echo '<img src="'.$result['image'].'"/>';

<?php
$dbhost = 'someURL.com';
$dbname = 'user';
$dbuser = 'user';
$dbpass = 'password';
$mysql_handle = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Error Connecting To Database Server");
mysql_select_db($dbname, $mysql_handle)
or die("Error selecting database: $dbname");
$first = 'bobbie';
$query = sprintf("SELECT image FROM Player
p WHERE name='%s'", mysql_real_escape_string($first));
$result = mysql_query($query);
mysql_close($mysql_handle);
header("Location: $result");
?>
should work

Related

Need to Update the data from mysql

<?php
if(isset($_POST['Search']))
{
$num = $_POST['num'];
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'vasuki';
mysql_select_db($dbname);
$Result = mysql_query("SELECT id, name, age FROM details WHERE id = '$num'");
while($row = mysql_fetch_array($Result)) {
$name = $row['name'] ;
$age = $row['age'];
echo "<div style='top: 273px;
margin-left: 60px;
position: absolute;left: 30px;'>
<table border='1'><tr><th>Name</th>
<th> Age </th></tr>
<tr><td>".$name."</td>
<td>".$age."</td>
<td>Edit</td></tr>
</table></div>";
}
I will explain the concept first :
In first page I insert the person details. and In second page in need to update the details. The above program is for my second page. To update I am searching data using the name and age. If I get the particular person data I need to click Edit and It should go to my 1st page and I need to Update the data.
I completed my html codes. I need to know php code to connect SQL.
Can anyone help on this ?
If you want to redirect to another page, in form you need to add action="otherpage.php" and in that other file you need to write something like:
if (!empty($_GET['newValue']) {
mysql_query("update details set name='".$_GET['name']."', age='".$_GET['age']."' WHERE id=".$_GET['id']."");
header("location: index.php");
exit;
}
This is approximate approach and there a few things you should change like mysql to mysqli or PDO (because deprecated) with prepared statements and escape all inputs.

How can I get a specific data using SQL select query?

I am trying to make a blog site.For this purpose I need to use a specific data from a specific field from my database table.To do that I wrote these code.
<?php
$host = "localhost";
$user = "root";
$pass = "12345";
$db = "bnsb";
$conn = mysql_connect($host, $user, $pass) or die("Connection Failed!");
mysql_select_db($db, $conn) or die("Database couldn't select!");
$img = "select image from news where uid=1";
echo $img;
?>
My database connection is OK.It should print like this user_img1.jpg. But it prints the whole sql query like select image from news where uid=1. I run this code on phpmyadmin. It works! But it does not work in my php script.How can I do now?
You can not give the query as it is and expect result like in phpadmin.
For this first of all you have to connect to your DB like this
$con = mysqli_connect("localhost","my_user","my_password","my_db");
execute required query like this
$query22 = "select image from news where uid = 1";
$result22 = mysqli_query($con, $query22) or die (mysqli_error());
Get the result and display like this
while($rows = mysqli_fetch_array($result22, MYSQLI_BOTH))
{
echo "<br>Values in db: " . $rows['columnname'];
}
Also i advice you to take a look at these tutorials
http://codular.com/php-mysqli
http://www.dreamincode.net/forums/topic/54239-introduction-to-mysqli-and-prepared-statements/
Please read some PHP 101 kind of tutorials on how to use PHP.
To get data from DB (in almost any language)
You need to connect to a DB. The connection gets you some sort of resource
You formulate your query (which you seem to have done)
You execute the query against the DB that you connected to (step #1)
You get a result (set)
You iterate over the result set to get the individual result(s); in your case the result set would be just one result (or row).
The examples to do this in PHP are very basic; please do your own lookup on net. This one seems good enough to get you started - http://www.w3schools.com/php/php_mysql_intro.asp
Try this,
<?php
$host = "localhost";
$user = "root";
$pass = "12345";
$db = "bnsb";
$conn = mysql_connect($host, $user, $pass) or die("Connection Failed!");
mysql_select_db($db, $conn) or die("Database couldn't select!");
$img = "select image from news where uid=1";
$result=mysql_query($img);
while($row=mysql_fetch_array($result)){
echo '<img src="your_path_to_image/'.$row['image'].'" /> - '.$row['image'];
}
?>

how to insert javascript variable into mysql database?

I cant seem to work out how to simply add a javascript variable into a mySQL table!
I have a html code which is just making a canvas for my game. I then have a javascript file doing all the game proccess and here is the code i am using to send the javascript variable to a php file:
var uiStats = $("#gameStats");
var uiHealth = $(".gameHealth");
var health = 10;
$.post('http:/localhost/basic_structure/game.php', { "health" : health});
Then here is the php file to insert the data into the database:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass)
or die
('Error connecting to mysql');
$dbname = 'game';
mysql_select_db($dbname, $conn);
$health = $_POST['health'];
mysql_query("INSERT INTO game_table (health)
VALUES ('$health')");
mysql_close($con);
I simply just want to save the health of the player in my game for later uses.
Any help is appreciated
Thanks
If you copy/pasted this from your actual code,
'http:/localhost/basic_structure/game.php'
should be
'http://localhost/basic_structure/game.php'
Your URL is incorrect in the post call
Also, use PDO or mysqli_ instead of mysql_ because mysql_ is deprecated.
A third suggestion is you should have a callback in your post (from php to javascript) to allow you to check that the process succeeded/failed and inform the user accordingly.

simple php - Mysql search not working properly

I have this code:
<?php
// Make a MySQL Connection
$dbhost = 'xxx';
$dbuser = 'xxx';
$dbpass = 'xxx';
$dbname = 'xxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM clients WHERE FNAME='".$_POST['clientsearch']."' OR LNAME='".$_POST['clientsearch']."' OR MAIL='".$_POST['clientsearch']."' OR TEL='".$_POST['clientsearch']."'"")
or die(mysql_error());
// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );
// Print out the contents of the entry
echo "FName: ".$row['FNAME'];
echo "LNAME: ".$row['LNAME'];
echo "FName: ".$row['MAIL'];
echo "LNAME: ".$row['TEL'];
?>
The goal is to search my mysql database to find the result of $_POST['clientsearch'] in one of the fields and return the lines that have that word in it (it is always 1 word)
If I use this:
$result = mysql_query("SELECT * FROM clients WHERE FNAME='".$_POST['clientsearch']."'"")
it seems to work. but it only searches in the FNAME column, not all of them. Also I only get the first result back. not all.
I'm starting php/mysql so I'm a little lost and don't know all functions yet. Could someone explain how I could fix my code up?
Thanks a lot for your help :)
For starters, you'll need to loop through each row in your result set if you're expecting more than 1 row. I illustrate how to do this with your original code.
<?php
// Make a MySQL Connection
$dbhost = 'xxx';
$dbuser = 'xxx';
$dbpass = 'xxx';
$dbname = 'xxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM clients WHERE FNAME='".$_POST['clientsearch']."' OR LNAME='".$_POST['clientsearch']."' OR MAIL='".$_POST['clientsearch']."' OR TEL='".$_POST['clientsearch']."'"")
or die(mysql_error());
// Print out the contents of the entry for each row in result
while( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) ) {
echo "FName: ".$row['FNAME'];
echo "LNAME: ".$row['LNAME'];
echo "FName: ".$row['MAIL'];
echo "LNAME: ".$row['TEL'];
}
?>
Take a look in the PHP documentation on mysql_real_escape_string for starters on the injection stuff.
Also, as others stated you may be looking for the LIKE instead of = SQL syntax. Also, look into the % wild card for LIKE.
Not an answer to the question, but hopefully helpful. Try writing code like this:
$cs = mysql_escape_string($_POST['clientsearch']);
$result = mysql_query("
SELECT
*
FROM clients
WHERE
FNAME='$cs'
OR LNAME='$cs'
OR MAIL='$cs'
OR TEL='$cs'
");
Exactly how you indent is up to you. This approach helps a great deal with readability, and hence also debugging :)

How does one implement a MySQL database into a webpage?

I am a complete database newbie. So far, I know that I can connect to MySQL using PHP's mysql_connect() command, but apart from that, I really don't see how to take that data and put it onto a web page.
a) are there ways other than mysql_connect()
b) lets say I had a table of data in mysql and all I wanted was for that table (for example: list of names and telephone numbers) to now appear on my web page. I can't for the life of me find a tutorial for this.
<?
$database_name = "dbname";
$mysql_host = "localhost"; //almost always 'localhost'
$database_user = "dbuser";
$database_pwd = "dbpass";
$dbc = mysql_connect($mysql_host, $database_user, $database_pwd);
if(!$dbc)
{
die("We are currently experiencing very heavy traffic to our site, please be patient and try again shortly.");
}
$db = mysql_select_db($database_name);
if(!$db)
{
die("Failed to connect to database - check your database name.");
}
$sql = "SELECT * FROM `table` WHERE `field`= 'value'";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)) {
// code here
// access variables like the following:
echo $row['field'].'<br />';
echo $row['field2'];
}
?>
Check out mysql_fetch_assoc mysql_fetch_array and mysql_fetch_object
This is the very basics, you will want to search for tutorials. There are many about.

Categories