Insert image path(Browse image folder location) in database and retrieve it - php

This is the code what I get from google search. But I don't know that will be the img.php . I search in google but unable to do this problem.
HTML :
< form action =" img.php " method = "POST" enctype = "multipart/form-data">
< input type="file" name = "myfile" />
< input type = "submit" value="upload" />
< /form>
PHP:
mysql_connect("localhost","root","") or die("cant connect to server.");
mysql_select_db("databaseimage") or die("cant connect to database");
echo "name:";
echo $name = $_FILES['myfile']['name'];
echo "type ";
echo $type = $_FILES['myfile']['type'];
echo "<BR>";echo "Size: ";
echo $size = $_FILES['myfile']['size'];
echo "temp: ";
echo $temp = $_FILES['myfile']['tmp_name'];
echo "error code: ";
echo $error = $_FILES['myfile']['error'];
echo "file contents: ";
echo $file_contents = addslashes(file_get_contents($_FILES['myfile']['tmp_name']));
echo "<BR>";
if (!$insert = mysql_query("INSERT INTO table1 VALUES ('','$name','$file_contents')"))
echo "problem uploading file";
else {$last_id = mysql_insert_id();
echo "Image uploaded.";
echo "<BR>";
echo "<img src=get.php?id=$last_id>";
}

Save your php file as a img.php and you have a get.php and get.php have code like,
if(isset($_REQUEST['id'])){
mysql_connect("localhost","root","") or die("cant connect to server.");
mysql_select_db("databaseimage") or die("cant connect to database");
$sql_result = mysql_query("SELECT name FROM table1 WHERE id= $_REQUEST['id']");
$row = mysql_fetch_row($sql_result);
echo $row[0];
}

Related

How to save a select option loaded from database in PHP

[sample][1]
Good day,
I successfully fetched the values from the database **(db) for the select option using mysqli
but
the problem is whenever I try save it in the database it doesn't retrieve the value selected in select the option .
Can you please give any suggestions on how to deal with this.
<?php
$conn = new mysqli('localhost', 'root', '', 'db') ;
if (mysqli_connect_error()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
} else {
echo"db_connection.php RUNNING<br>";
}
/* CONNECTION IN DATABASE*/
/* WHILE LOOP FOR SELECT OPTION IN DATABASE*/
$result = $conn->query("select b_fname from tbl_client");
echo "<html>";
echo "<body>";
echo "<select name='id'>";
while ($row = $result->fetch_assoc()) {
unset($b_id, $b_fname);
$b_id = $row['b_id'];
$b_fname = $row['b_fname'];
echo '<form action ="dropdown_demo.php" method="POST" enctype="multipart/form-data" >';
echo '<option name="b_fname" value="/'.$b_fname.'/">'.$b_fname.'.'.$b_fname.'</option>';
echo " </form>";
}
echo '</select><input type="submit" name="add_drop" />';
echo "</body>";
echo "</html>";
/* SQL INSERT THE VALUE TO THE */
$sql = "INSERT INTO tbl_client (b_fname)VALUES ( '$b_fname' )";
if (mysqli_query($conn, $sql)) {
echo('<script>alert("Record Added Successfully!");</script>');
// header('Refresh: 1; URL= import_addnew-Copy.php');
error_reporting(0);
} else {
error_reporting(0);
}
mysqli_close($conn);
?>
I have made some changes in your code. pu the tag out side while loop etc...
Try the below code:
$conn = new mysqli('localhost', 'root', '', 'db') ;
if (mysqli_connect_error())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}else
{
echo"db_connection.php RUNNING<br>";
}
/* CONNECTION IN DATABASE*/
/* WHILE LOOP FOR SELECT OPTION IN DATABASE*/
$result = $conn->query("select b_fname from tbl_client");
echo "<html>";
echo "<body>";
echo '<form action ="dropdown_demo.php" method="POST" enctype="multipart/form-data" >';
echo '<select name="b_fname" >';
while ($row = $result->fetch_assoc()) {
unset($b_id, $b_fname);
$b_id = $row['b_id'];
$b_fname = $row['b_fname'];
echo '<option value="'.$b_fname.'">'.$b_fname.'.'.$b_fname.'</option>';
}
echo '</select><input type="submit" name="add_drop" />';
echo " </form>";
echo "</body>";
echo "</html>";
/* SQL INSERT THE VALUE TO THE */
if(isset($_POST['add_drop'])){
$b_fname = $_POST["b_fname"];
$sql = "INSERT INTO tbl_client (b_fname) VALUES ( '".$b_fname."' )";
if (mysqli_query($conn, $sql)) {
echo('<script>alert("Record Added Successfully!");</script>');
// header('Refresh: 1; URL= import_addnew-Copy.php');
error_reporting(0);
} else {
error_reporting(0);
}
}
mysqli_close($conn);

CSV file upload with data validation

I'm trying to upload a *.CSV file to the database using PhP.
I can't really make the data validation work with the file upload.
The script should see if the data from certain cells is valid by searching in the db's tables.
The file should not be uploaded if there are errors!
Here's the code!
<form name="import" method="post" enctype="multipart/form-data">
<input type="file" name="file" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
include ("connection2.php");
if(isset($_POST["submit"]))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
$err = 0;
if ($_FILES["file"]["type"]=='application/vnd.ms-excel')
{
while(($filesop = fgetcsv($handle, 3000, ",")) !== false)
{
$tid = trim($filesop[0]);
$beneficiar = ucwords(strtolower(trim($filesop[1])));
$locatie = ucwords(strtolower(trim($filesop[2])));
$localitate = ucwords(strtolower(trim($filesop[3])));
$judet = ucwords(strtolower(trim($filesop[4])));
$adresa = ucwords(strtolower(trim($filesop[5])));
$model = trim($filesop[6]);
$query = mysqli_query("SELECT * FROM modele WHERE `model` = '".$model."'");
if (!empty($query)) {
$err ++;
$msg=$msg."Model error on row $c <br>";
}
$query = mysqli_query("SELECT * FROM judete WHERE `nume` = '".$judet."'");
if (!empty($query)) {
$err ++;
$msg=$msg."Judet error on row $c <br>";
}
$query = mysqli_query("SELECT * FROM beneficiari WHERE `nume` = '".$beneficiar."'");
if (!empty($query)) {
$err ++;
$msg=$msg." Beneficiar error on row $c <br>";
}
// if (strlen($tid)!==8){
// $err ++;
// $msg=$msg."TID length error at row $c <br>";
// }
$c ++;
}
if ($err!==0){
echo $msg; echo "ERROR COUNT= ".$err;
break;
}
$c=0;
while(($filesop = fgetcsv($handle, 3000, ",")) !== false)
{
$tid = trim($filesop[0]);
$beneficiar = ucwords(strtolower(trim($filesop[1])));
$locatie = ucwords(strtolower(trim($filesop[2])));
$localitate = ucwords(strtolower(trim($filesop[3])));
$judet = ucwords(strtolower(trim($filesop[4])));
$adresa = ucwords(strtolower(trim($filesop[5])));
$model = trim($filesop[6]);
$qry=mysql_query("SELECT id FROM beneficiari WHERE `nume` = '".$beneficiar."'");
while ($row = mysql_fetch_assoc($qry)){
$id_client=$row['id'];
echo "Beneficiar=".$row['id'];
}
$qry_id_model=mysql_query("SELECT id FROM modele WHERE `model` = '".$model."'");
while ($row = mysql_fetch_assoc($qry_id_model)){
$id_model=$row['id'];
echo "Model=".$row['id'];
}
echo "MODEL2:".$id_model;
$adresa1 = $adresa.", ".$localitate;
if ($c!==0){
$sql = mysql_query("INSERT INTO equipments
(id_client, model, tid, beneficiar, adresa, agentie, judet)
VALUES
('$id_client','$id_model','$tid','$beneficiar','$adresa1','$locatie','$judet')");
}
$c = $c + 1;
}
if($sql){
echo "You database has imported successfully. You have inserted ". $c ." recordes <br>";
}else{
echo "Sorry! There is some problem.<br>";
}
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
}
else echo "NOT CSV!";
}
?>
What's wrong here?
When i try to run it the data is not uploaded and no errors are shown, I left errors in the file to test it. Also i uploaded a clean file and also the file is not uploaded. If i break the code in 2 and make 2 separate codes, one to verify and one to upload, the upload works, but i need the verification and the upload to be in the same code. also tried mysql_query in stead of mysqli_query.
The procedural style of mysqli_query takes 2 arguments - the connection and the query. You're only passing the query.
You can read the official documentation for the mysqli_query() method here:
http://php.net/manual/en/mysqli.query.php
A suggestion as to how to approach this would be something like:
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
if(!$link)
{
echo("Unable to connect");
} else {
if($ret = mysqli_query($link, "SELECT id FROM modele WHERE `model` = '".mysqli_real_escape_string($link, $model)."'"))
{
$data = mysqli_fetch_assoc($ret);
echo($data["id"]);
}
mysqli_close($link);
}
Important: Note my use of mysqli_real_escape_string in the example above - your current code leaves you vulnerable to SQL injection attacks.
first of all you should upload this file on a temporary folder and save the file name. Then use getCSV php function to read properly the file.
Finally you can check if it's all OK, insert on database, and, if not, echo an error message and delete the file (remember we saved the name and we know the static route of the temporary folder).
Hope it helps!

broken file icon retrieving image from database php and mysql

I need to upload and retrieve image from a database, I am able to store the image in the database but unable to display it later. please help
I wrote the following code to retrieve from the database.
$result1=mysql_query("INSERT INTO userdata(id, username, firstname, lastname, imageType, image)VALUES('', '" . $_SESSION['username'] . "', '" . $_SESSION['firstname'] . "', '$lastname','{$image_size['mime']}','{$imgData}')") or die("Invalid query: " . mysql_error());
if($result1)
{
echo "</br>";
echo "Registration successful";
echo "</br>";
echo $lastid=mysql_insert_id();//get the id of the last record
echo "uploaded image is :"; ?>
<img src="imageView.php?image_id=<?php echo $lastid; ?>" /><br/>
<?php
echo "</br>";
}#if result1into db successful
else
{
echo $result1;
echo "Problem in database operation";
imageView.php has the following code:
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("wordgraphic") or die(mysql_error());
if(isset($_GET['id'])) {
$sql = "SELECT imageType,image FROM userdata WHERE id=". $_GET['image_id'];
$result = mysql_query("$sql") or die("<b>Error:</b> Problem on Retrieving Image BLOB<br/>" . mysql_error());
$row = mysql_fetch_array($result);
header("Content-type: " . $row["imageType"]);
echo $row["image"];
}
mysql_close($conn);
?>
What could be possibly wrong with the code?
When i try to run imageView.php with static id image is getting displayed. So i guess the error is in passing the variable is this code:
echo "uploaded image is :"; ?>
<img src="imageView.php?image_id=<?php echo $lastid; ?>" /><br/>
<?php
what could be possibly wrong?
just a smal rectification
<img src="imageView.php?image_id=<?php echo $lastid; ?>" />
instead of this
src = src path where u r saving the image file lets say in images folder that would be here $imagedata store the file name in the DB so that you can retreive it from the image folder
<img src="images/$imgData" width="your wish" height="your wish"/>

Display all images from database (php)

I use this code to upload images in the database:
<?php
//Store the upload form
$UploadForm = " <form id='idForm' action='upload.php' method='post' enctype='multipart/form-data'>
<input type='file' name='image'/><br/><br/>
<input id='BTN' type='submit' value='Upload'/><br/><br/>
</form>";
//if logged in show the upload form
if($userid && $username){
echo $UploadForm;
// Connect to database
$con = mysqli_connect('***', '***', '***', '***_dbimage');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//file properties
if(isset($_FILES['image'])){
$file = $_FILES['image']['tmp_name'];
}
//if image selected
if(isset($file) && $file != ""){
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size == FALSE){
echo "That's not an image!";
header( "refresh:2;url=upload.php" );
}
else{
$qry = mysqli_query($con,"SELECT * FROM store WHERE name='$image_name'");
$Nrows = $qry->num_rows;
if( $Nrows == 0){
if(!$insert = mysqli_query($con,"INSERT INTO store VALUES ('','$image_name','$username','$image')")){
echo "We had problems uploading your file!";
header( "refresh:2;url=upload.php" );
}
else{
echo "Image $image_name uploaded!";
header( "refresh:2;url=upload.php" );
}
}
else{
echo "There is already an image uploaded with the name $image_name<br/>";
}
}
}
else{
echo "Please select an image";
}
mysqli_close($con);
}
else{
echo "You have to be logged in to upload!";
}
?>
And this code to display all images from the database:
// Connect to database
$con = mysqli_connect('***', '***', '***', '***_dbimage');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$res = mysqli_query($con,'SELECT * FROM store');
while($row = $res->fetch_array()){
$image = $rows['image'];
echo "<img src='".$image."' />";
}
And I get something like tons of random symbols like diamonds with question marks in them and letters instead of my image. The scripts are not made by me. I just watched some tutorials and combined them and it seems that I didn't "combined" them properly. What am I doing wrong?
LATER EDIT:
HTML:
<img src="getImage.php?id=26"/>
PHP (getImage.php):
$con = mysqli_connect('***', '***', '***', '***_dbimage');
if(isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
$query = mysql_query("SELECT * FROM store WHERE id=$id");
while($row = mysql_fetch_assoc($query))
{
$imageData = $row['image'];
}
header("content-type:image/jpeg");
echo $imageData;
}
else
{
echo "Error!";
}
?>
Still can't get it to work! Help please!
I finaly did it!
This is the upload script:
<?php
//Store the upload form
$UploadForm = " <form id='idForm' action='upload.php' method='post' enctype='multipart/form-data'>
<input type='file' name='image'/><br/><br/>
<input id='BTN' type='submit' value='Upload'/><br/><br/>
</form>";
//if logged in show the upload form
if($userid && $username){
echo $UploadForm;
// Connect to database
$con = mysqli_connect('***', '***', '***', '***_dbimage');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//file properties
if(isset($_FILES['image'])){
$file = $_FILES['image']['tmp_name'];
}
//if image selected
if(isset($file) && $file != ""){
$image = mysqli_real_escape_string($con,file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size == FALSE){
echo "That's not an image!";
header( "refresh:2;url=upload.php" );
}
else{
$qry = mysqli_query($con,"SELECT * FROM store WHERE name='$image_name'");
$Nrows = $qry->num_rows;
if( $Nrows == 0){
if(!$insert = mysqli_query($con,"INSERT INTO store VALUES ('','$image_name','$username','$image')")){
echo "We had problems uploading your file!";
header( "refresh:2;url=upload.php" );
}
else{
echo "Image $image_name uploaded!";
header( "refresh:2;url=upload.php" );
}
}
else{
echo "There is already an image uploaded with the name $image_name<br/>";
}
}
}
else{
echo "Please select an image";
}
mysqli_close($con);
}
else{
echo "You have to be logged in to upload!";
}
?>
Here is the diplay script:
$con = mysqli_connect('***', '***', '***', '***_dbimage');
$query = mysqli_query($con,"SELECT id FROM store");
while($row = mysqli_fetch_assoc($query))
{
$IDstore = $row['id'];
echo "<img src='getImage.php?id=".$IDstore."'/>";
}
And the "getImage.php":
<?php
$con = mysqli_connect('***', '***', '***', '***_dbimage');
if(isset($_GET['id']))
{
$id = mysqli_real_escape_string($con,$_GET['id']);
$query = mysqli_query($con,"SELECT * FROM store WHERE id=$id");
while($row = mysqli_fetch_assoc($query))
{
$imageData = $row['image'];
}
header("content-type:image/jpeg");
echo $imageData;
}
else
{
echo "Error!";
}
?>
I hope it will help someone cause it's ready to use now. :)

display recent uploaded image in php only display single image corresponding to the ther data submited to that fie

I want to display uploaded image to a different page showing first name last name and image corresponding to that upload this is the code I have it currently displaying all the images save on a folder I just want to display the recent uploaded image corresponding to the information submitted
<?php
$con = mysql_connect("localhost","username","pa…
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$sql="INSERT INTO nametable (fname, lname, mname, image, status, id)
VALUES
('$_POST[fname]','$_POST[mname]','$_PO… 'display','')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "";
mysql_close($con);
?> <?php
// Assigning value about your server to variables for database connection
$hostname_connect= "localhost";
$database_connect= "database";
$username_connect= "username";
$password_connect= "password";
$connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR…
#mysql_select_db($database_connect) or die (mysql_error());
if($_POST)
{
// $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.
if ($_FILES["file"]["error"] > 0)
{
// if there is error in file uploading
echo "Return Code: " . $_FILES["file"]["error"] . "
";
}
else
{
// check if file already exit in "images" folder.
if (file_exists("images/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{ //move_uploaded_file function will upload your image.
if(move_uploaded_file($_FILES["file"]["t… . $_FILES["file"]["name"]))
{
// If file has uploaded successfully, store its name in data base
$query_image = "insert into table";
if(mysql_query($query_image))
{
echo "Stored in: " . "images/" . $_FILES["file"]["name"];
}
else
{
echo'';
}
}
}
}
}
?>
<html>
<head>
</head>
<body>
<p>First name: <?php echo $_POST["fname"]; ?><br></p>
<p>Middle name: <?php echo $_POST["mname"]; ?><br></p>
<p>Last name: <?php echo $_POST["lname"]; ?><br></p>
</form>
</body>
</html>
<?php
// Assigning value about your server to variables for database connection
$hostname_connect= "localhost";
$database_connect= "database";
$username_connect= "username";
$password_connect= "password";
$connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR…
#mysql_select_db($database_connect) or die (mysql_error());
$query_image = "SELECT * FROM table";
// This query will show you all images if you want to see only one image pass id='$id' e.g. "SELECT * FROM nametable id='$id'".
$result = mysql_query($query_image);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result))
{
echo '<img width="165" height="104" border="0" src="images/'.$row["image"].'">';
}
}
else
{
echo 'File name not found in database';
}
?>
$query_image = "SELECT * FROM table order by id desc limit 1";

Categories