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

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'] ).'"/>'
?>

Related

How to ask a user input and use it as a parameter for a stored procedure in a PHP script?

Sorry for the newbie question, but I have this task which kind of got me stuck.
So, I made a database in PhpMyAdmin, created a table with data : Products(id, name, city) and created a stored procedure that will actually do a query on the table to find out the product with a certain name (which will be input-ed by the user on the web page). My stored procedure is: proc_test and takes one VARCHAR paramter.
So, how can I do this in a php script? How can i ask the user for some data, (on the site he should have like a box to type it) then click a search button, and get redirected to the page with the query results. This is my code so far:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "CALL proc_test('pencil');";
if ($result = mysqli_query($conn, $sql)) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['numec'] . "<br/>";
}
}
$conn->close();
?>
Here, of course, I manually give the parameter in the script. But I don't know how to change this and ask for a user input instead. Any help is welcome!
You can use ajax to send the data from your website to the php file where you can search for it in the database and send that data back to the user. In my example, the data is being displayed on the same webpage. You could echo the link to the website and redirect the user on the webpage using JavaScript if you really wanted to but my example is just a proof of concept.
index.html
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<input required type="text" id="user_input">
<button onclick="sendData()">Search</button>
<p id="result"></p>
<script>
function sendData() {
var var_params = $('#user_input').val();
$.post('test.php', {params: var_params}, function(data) {
document.getElementById('result').innerHTML = "Your search result: " + data;
});
}
</script>
</body>
</html>
test.php
<?php
if(isset($_POST['params'])) {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
$conn = new mysqli($servername, $username, $password, $dbname); // Create connection
if ($conn->connect_error) { // Check connection
die("Connection failed: " . $conn->connect_error);
}
$param = mysqli_real_escape_string($conn, $_POST['params']);
$sql = "CALL proc_test('$param');";
if($result = mysqli_query($conn, $sql)) {
while($row=mysqli_fetch_assoc($result)) {
echo $row['numec']. "<br/>";
}
}
$conn->close();
}
?>

Error while filling a mysql database with data from php/html

I created this for one of my projects. We have a webshop where users can enter their credentials and order products. The current solution puts all the data into a .csv-file and I was tasked with creating a mysql database as a new solution.
I added a simple HTML insert for the user to enter his name, but if I try to run the script I get a syntax error for line 19. I'm new to programming and therefore not sure what the error is here.
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "localhost";
$password = "";
$dbname = "test"
// create a variable
$Vorname=$_POST['Vorname'];
$Nachname=$_POST['Nachname'];
//Execute the query
mysqli_query($connect "INSERT INTO tbl_bestellungen(Vorname,Nachname)
VALUES('$Vorname','$Nachname')");
<?php include 'database.php';>
if(mysqli_affected_rows($connect) > 0){
echo "<p>Bestellung erfasst</p>";
} else {
echo "Bestellvorgang fehlgeschlagen<br />";
echo mysqli_error ($connect);
<h2>Text Input</h2>
<form>
Vorname:<br>
<input type="text" name="Vorname">
<br>
Nachname:<br>
<input type="text" name="Nachname">
<input type="submit" name="button1" value="Senden">
</form>
</body>
</html>
Thanks in advance.
Well you should do like this way:
$servername = "localhost";
$username = "localhost";
$password = "";
$dbname = "test"
$dbConn = mysqli_connect($servername, $username, $password, $dbname);
if(!$dbConn){
echo "No Db connected";
}
//above connection code should be in a separate file and include in all files or header
$Vorname=$_POST['Vorname'];
$Nachname=$_POST['Nachname'];
$query = "INSERT INTO tbl_bestellungen (Vorname,Nachname)
VALUES('$Vorname','$Nachname')";
or you can set query like
$query = "INSERT INTO tbl_bestellungen (Vorname,Nachname)
VALUES('".$Vorname."','".$Nachname."')";
if($dbConn->query($query)){
echo "Record inserted !";
}else{
echo "Record cannot be inserted !";
}

cannot display picture using php on the page

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.

take database user,pass,name and host info from user's and want to update a database column info

I am new here and noob in programming.
I have created a script that can change a database column but now I want to take database login info from user's and the changed value from user's when they give all info correctly the script changed the database column info which was given by the user's.
Here is my login.html source code :
<html>
<center>
<form action="db.php" method="post">
DB Host: <input type="text" name="host"><br>
DB Username: <input type="text" name="usr"><br>
DB Password: <input type="password" name="psw"><br>
DB Name: <input type="text" name="dbname"><br><br><br>
Admin changed Username: <input type="text" name="admusr"><br>
Admin Changed Password: <input type="password" name="admpsw"><br>
<input type="submit">
</form>
</center>
</html>
and here is my db.php source code which can update database column info manually
<?php
$servername = "localhost";
$username = "admin";
$dbname = "mydb";
$password = "1234";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
mysqli_select_db($conn,"$dbname");
$sql = "UPDATE admins SET user_login='admin1',user_pass='1234' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
Is it possible to take value from user's and changed the database column info?
Sorry for bad english.
It's very bad idea... loads of security issues. But if you want to change it from received form values just change your query to this:
// escape received values
$usr = $conn->real_escape_string($_POST['usr']);
$psw = $conn->real_escape_string($_POST['psw']);
// use them in query
$sql = "UPDATE admins SET user_login='".$usr."',user_pass='".$psw."' WHERE id=1";
You got more field which is user filling... I don't know your exact table structure. But if you want to use all of them just add received escaped values to your query:
// escape received values
$usr = $conn->real_escape_string($_POST['usr']);
$psw = $conn->real_escape_string($_POST['psw']);
$host = $conn->real_escape_string($_POST['host']);
$dbname = $conn->real_escape_string($_POST['dbname']);
$admusr = $conn->real_escape_string($_POST['admusr']);
$admpsw = $conn->real_escape_string($_POST['admpsw']);
// use all of them in query depending on your table structure
$sql = "UPDATE admins SET user_login='".$usr."',user_pass='".$psw."' WHERE id=1";
Use $_POST variable to retrieve data that user entered on login.html page
like in db.php for $servername and $username use
$servername = $_POST['host'];
$username = $_POST['usr'];

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>

Categories