Display image from MySql database in Php server - php

I send an image from my Android Application to my Php server using a MySql database, but when i try to display the image in browser it doesn't work.
This is how I send the picture
String imageString=Base64.encodeBytes(this.image);
nameValuePairs.add(new BasicNameValuePair("image", imageString));
And this is how I try to display it
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';
I've checked and imageString in my app is different from base64_encode( $row['image']).
MySql part
$conn = new mysqli($server, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE Posts (
id INTEGER UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user VARCHAR(50) NOT NULL,
date VARCHAR(12) NOT NULL,
event VARCHAR(1000),
image BLOB
)";
if ($conn->query($sql) === TRUE) {
echo "Table Posts created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$user = $_POST['user'];
$date = $_POST['date'];
$event = $_POST['event'];
$image = $_POST['image'];
echo "Test";
$sql = "INSERT INTO Posts (user, date, event,image) ";
$sql .= "VALUES ('$user','$date', '$event', '$image')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Insert success";
}
mysql_close($con);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["user"]. $row["date"]. $row["event"]. "<br>";
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';

Your Java code is doing a Base64 encode of the image before sending it to the server. You do not need to encode it a second time when you go to display it. The result is a base64 encoded string of a base64 encoded string, which isn't what you want to do.
Try this instead:
echo '<img src="data:image/jpeg;base64,' . $row['image'] . '"/>';

Related

Another empty row with time stamp added with every entry in mysql database

another empty row with timestamp added in mysql database each time a new row with entries added ,
here is part of my code
$servername = "localhost";
$username = "root";
$password = "zaheer442";
$dbname = "76H";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}
$sql = "INSERT INTO 76Hlog (Device_ID, Response_status, Device_NO, Status, Time) VALUES ('$keywords[4]', '$keywords[8]', '$keywords[15]', '$keywords[17]', now())";
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
//displaying data
$sql = "SELECT Device_ID, Response_status, Device_NO, Status FROM 76H";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["Device_ID"]. " - Staus: " . $row["Response_status"]. " Devic No " . $row["Device_NO"]. " Mode " . $row["Status"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
[Entries Screenshot has also attached]

Display MySQL image data in PHP page

I am currently looking to display an image on my website using PHP. The image data is in MySQL, and I know how to display data from MySQL, but I can't figure out how to display images using insertname.png type data.
My code is currently this: (In pet_url, it basically states dogpuppyrare.png, which is a png inside my public_html inside my file manager on my hosting website.
<?php
$servername = "localhost";
$username = "dbuser";
$password = "dbpass";
$dbname = "db name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT pet_url FROM user_pets";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["pet_url"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
The fact the field is labelled ['pet_url'], I'm making the assumption that the data in this key is a URL, so just display the src using the HTML img tag.
if ($result->num_rows > 0) {
//output data of each row
while ($row = $result->fetch_assoc()) {
echo '<img src="' . $row["pet_url"] . '" alt="my pet image"/>"<br>"';
}
}
You can read more about image tags at w3schools:
Convert this line:
echo $row["pet_url"]. "<br>";
To this;
echo '<img src="'. $row["pet_url"] . '" alt="my pet image" /><br>';

MySQL Database not Updating when Form Submitted using PHP

This is a webpage that I have:
// Info to connect to the Wishlist database
$servername = "em";
$dbusername = "";
$password = "!19";
$dbname = "";
// To connect to the database please
$conn = new mysqli($servername, $dbusername, $password, $dbname);
// If unable to connect to the database display this error
if ($conn->connect_error) {
echo "Connection to wishlist failed";
die("Connection failed: " . $conn->connect_error);
}
echo "Once you have added creatures to your wishlist, click " .
"<strong><a href='http://eggcavity.com/edit-wishlist'>here</a></strong> to edit your wishlist.";
// Get current user's username
$current_user = wp_get_current_user();
$username = $current_user->user_login;
// Retrieve data from the database
$sql = "SELECT Name, Stage1 FROM Creatures";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// Display all of the data from the database
echo '<form method="POST">';
while($row = $result->fetch_assoc()) {
echo '<div style="display: inline-block; width: 30%;">' .
'<img src="' . $row["Stage1"] . '"><br>'.
$row["Name"] .
'<br><input type="checkbox" name="creautres[]" value="' .
$row["Name"] .
'"></div>';
}
echo '<br><br><input type="submit" value="Submit"></form>';
} else {
echo "Creatures not found";
}
if(isset($_POST['submit'])){
foreach($_POST['creatures'] as $selected){
$sql = "INSERT INTO " . $username .
" (Creature, Picture, Stage, Gender, Frozen, Notes) VALUES ('" .
$selected . "', 'http://static.eggcave.com/90x90/" . $selected .
"_1', 'Stage1', 'Unspecified', 'Unspecified', 'Unspecified', '')";
if ($conn->query($sql) === FALSE) {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
// Close the connection to the database
$conn->close();
It displays like I want it to:
But it doesn't update the database when I click the submit button.
I've tried echoing $stmt, it seemed to be written as it should be.
When I try echoing $selected, within the loop it doesn't seem to output anything.
Can you help me?
I have updated the code to use one database. Please help me. It still isn't adding.
You had a typo in your checkbox name. I re-did the submit line in the form and the isset() I believe.
The below includes activating error reporting, a try/catch, binding for safety against sql injection. The data saves. You will need to deal with what should be unique data getting saved more than once of course. For instance, a unique key on (Creature,Username). And I would re-think the columns for Id's, but this was your table design. Thanks for allowing us to show you a re-use of a table. Good luck.
schema (from you):
drop table if exists Wishlists;
CREATE TABLE `Wishlists` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Creature` varchar(100) DEFAULT NULL,
`Picture` varchar(200) DEFAULT NULL,
`Stage` varchar(100) DEFAULT NULL,
`Gender` varchar(100) DEFAULT NULL,
`Frozen` varchar(100) DEFAULT NULL,
`Notes` varchar(500) DEFAULT NULL,
`Username` varchar(100) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB; -- <------------------------ went with InnoDB
-- truncate table Wishlists; -- used during early testing
PHP (eggs01.php):
// Info to connect to the Wishlist database
$servername = "serve it up";
$dbusername = "dbu dbu dbu";
$password = "OpenSesame";
$dbname = "my db name";
try {
// To connect to the database please
$conn = new mysqli($servername, $dbusername, $password, $dbname);
if ($conn->connect_error) {
die('Connect Error (' . $conn->connect_errno . ') '
. $conn->connect_error);
}
echo "I am connected and feel happy.<br/>";
if(isset($_POST['submit'])){
// Postback - submit
// Get current user's username
//$current_user = wp_get_current_user(); // remmed out, I don't have your system
//$username = $current_user->user_login; // remmed out, I don't have your system
$theCount=0;
foreach($_POST['creatures'] as $selected){
$Creature=$selected;
$Picture="http://static.eggcave.com/90x90/" . $selected . "_1";
$Stage="Stage1";
$Gender="Unspecified";
$Frozen="Unspecified";
$Notes="Unspecified";
$Username="Stackoverflow123";
$sql = "INSERT Wishlists (Creature, Picture, Stage, Gender, Frozen, Notes, Username) " .
" VALUES (?,?,?,?,?,?,?)";
$stmt = $conn->prepare($sql); // SQL Injection - safe prepare / bind / execute
// 7 s's means 7 strings:
$stmt->bind_param('sssssss', $Creature, $Picture, $Stage, $Gender, $Frozen, $Notes, $Username);
$stmt->execute();
$theCount++;
}
echo "<br>Santa has been notified, count = ".$theCount."<br>";
}
else {
// Just display the form
// Retrieve data from the database
$result = $conn->query("SELECT Name, Stage1 FROM Creatures");
if ($result->num_rows > 0) {
// Display all of the data from the database
echo '<form method="POST">';
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
echo '<div style="display: inline-block; width: 30%;">' .
'<img src="' . $row["Stage1"] . '"><br>'.
$row["Name"] .
'<br><input type="checkbox" name="creatures[]" value="' .
$row["Name"] .
'"></div>';
}
echo '<br><br><button type="submit" name="submit">Submit</button></form>';
$result->close();
} else {
echo "Creatures not found";
}
}
} catch (mysqli_sql_exception $e) {
throw $e;
}
After the submit having selected 3 eggs:
Database Image:
First of all, look at code
$dbname1 = *****";
Here you are missing " :
So replace this with
$dbname1 = "*****";
and try again
First issue is you should never run a SQL statement in a Loop ALWAYS AVOID THIS - as it will put your server through a lot of strain.
And 2nd try this and tell me the out put
foreach($_POST['creatures'] as $selected){
$stmt = "INSERT INTO " . $username . " (Creature, Picture, Stage, Gender, Frozen, Notes) VALUES ('" . $selected . "', 'http://static.eggcave.com/90x90/" . $selected . "_1', 'Stage1', 'Unspecified', 'Unspecified', 'Unspecified', '')";
if ($conn->query($stmt) === TRUE) {
}
}
TO
foreach($_POST['creatures'] as $selected){
$stmt = "INSERT INTO " . $username . " (Creature, Picture, Stage, Gender, Frozen, Notes) VALUES ('" . $selected . "', 'http://static.eggcave.com/90x90/" . $selected . "_1', 'Stage1', 'Unspecified', 'Unspecified', 'Unspecified', '')";
$result = $conn->query($stmt) OR die(var_dump($conn));
var_dump($result->fetch_array(MYSQLI_ASSOC));
die;
}

Insert data to database from CSV file. Only inserts last row

I read in data from a csv file, and want to insert it into my database. The issue is that it only inserts the last row in the CSV file each time. However when i print my $sq1 to screen it shows all 48 inserts with the different values that they should have. Could anyone tell me why it only inserts one row into the database?
<?php
// Did modify login values for privacy
$servername = "10.100.";
$username = "myusername";
$password = "abc123";
$dbname = "informationdata";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$file = fopen("ALMGrade.csv","r");
while(! feof($file)){
$ar =fgetcsv($file);
$sql = "INSERT INTO gradetable_copy (Grade, Grade1, Grade2, Grade3, Grade4, Grade5, Grade6)
VALUES ('$ar[0]', '$ar[1]', '$ar[2]', '$ar[3]', '$ar[4]', '$ar[5]', '$ar[6]' )";
echo $sql;
echo "<br>";
}
fclose($file);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
move the execution of query ($conn->query($sql) ) inside while:
while(! feof($file))
{
$ar =fgetcsv($file);
$sql = "INSERT INTO gradetable_copy (Grade, Grade1, Grade2, Grade3, Grade4, Grade5, Grade6)
VALUES ('$ar[0]', '$ar[1]', '$ar[2]', '$ar[3]', '$ar[4]', '$ar[5]', '$ar[6]' )";
echo $sql;
echo "<br>";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
fclose($file);

Displaying ALL data from sql table in PHP?

When I print my code it only prints the question and description of id = 1 but not the rest of the table.
here is my code.
Please show me how to print my entire table which has like 20 questions or so...and also please show me how to make it so that the questions stay on the browser (even when I refresh the page) because currently the data does not stay on the browser when i refresh the page.
Thanks So Much!
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
} else {
echo "failed to fetch array";
}
}
?>
You need a for each loop:
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}
} else {
echo "failed to fetch array";
}
}
?>
All I've done there is change:
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
to:
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}
fetch_assoc() — Fetch a result row as an associative array
so it gets only 1 row you need to loop through the rest of the rows check the examples reference from php docs

Categories