sql and php variable - php

i want to create form to upload file into img dir(i know how to do that),and insert an html code and php variable to database(that works fine), the problem is when i fetch the html code from database it shows <img src=img/$rand>, i what it to show the the result of varible not the name, sorry for my bad english
here is my full code:
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$rand = substr(md5(microtime()),rand(0,26),5);
?>
<!DOCTYPE html>
<html>
<head>
<title>Insert and Display Images From Mysql Database in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br /><br />
<div class="container" style="width:500px;">
<h3 align="center">Insert and Display Images From Mysql Database in PHP</h3>
<br />
<form method="post" enctype="multipart/form-data">
<input type="file" name="image" id="image" />
<br />
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-info" />
</form>
<?php
if(isset($_POST['insert'])){
$fu = $_FILES['image'];
$image_tmp_name= $_FILES['image']['tmp_name'];
$image_name = $_FILES['image']['name'];
move_uploaded_file($image_tmp_name,"img/$image_name");
rename("img/$image_name", "img/$rand");
//echo "<img class='iwalls' data-toggle='modal' data-target='' src='img/$image_name' alt='Loading...'>";
}
?>
<?php
if(isset($_POST["insert"]))
{
$file = '<img src=img/$rand>';
$sql = "INSERT INTO tbl_images(name) VALUES ('$file')";
if(mysqli_query($connect, $sql))
{
echo '<script>alert("Image Inserted into Database")</script>';
} else{
echo '<script>alert("Failed")</script>';
}
}
?>
<br />
<br />
<table class="table table-bordered">
<tr>
<th>Image</th>
<?php
$query = "SELECT * FROM tbl_images ORDER BY id DESC";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
echo "<div>";
echo $row ['name'];
echo "</div>";
}
?>
</tr>
</table>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#insert').click(function(){
var image_name = $('#image').val();
if(image_name == '')
{
alert("Please Select Image");
return false;
}
else
{
var extension = $('#image').val().split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
alert('Invalid Image File');
$('#image').val('');
return false;
}
}
});
});
</script>

When using single quotes, the string will be as is it is.
$rand = "hello.png";
$file = '<img src=img/$rand>';
// $file is <img src=img/$rand>
You need double quotes for string interpolation
$file = "<img src=img/$rand>";
// $file is <img src=img/hello.png>;

Related

Ajax search results with on click result to download file

MY INDEX PAGE
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Some name</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<br />
<h2 align="center">Search by name</h2><br />
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Search</span>
<input type="text" name="search_text" id="search_text" placeholder="Enter model / search here" class="form-control" />
</div>
</div>
<br />
<div id="result"></div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
AND MY fetch.php PAGE
which is used to get data from the database tables and output results.
I also added if the result is > 50 it will ask to enter few more characters because if I don't add if result > 50 then my page took 20sec to display all data because my database table has 25000 entries.
<?php
$connect = mysqli_connect("localhost", "root", "PASSWORD", "DATABASE");
if(isset($_POST["query"]))
{
$search = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM files
WHERE Name LIKE '%".$search."%'
";
}
else
{
$query = "
SELECT * FROM files ORDER BY ID
";
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) < 500)
{
$output1 .= '
<div class="table-responsive">
<table class="table table bordered">
<div>
<th>Name</th>
<th>URL</th>
<th>Extension</th>
<th>Download</th>
</div>
';
while($row = mysqli_fetch_array($result))
{
$output2 .= '
<tr>
<td>'.$row["Name"].'</td>
<td>'.$row["URL"].'</td>
<td>'.$row["Extension"].'</td>
</tr>
';
}
if(mysqli_num_rows($result) > 0)
{
echo "$output1";
echo "$output2";
}
else
{
echo 'no results found';
}
}
else
{
echo 'Please enter few more charecters';
}
?>
I want href link for each of my results and on the click, it should download a file from ./"URL" column from a database table.
My database looks like this:
AND MY CURRENT PAGE IS http://mss1996.ddns.net:8008/files
I tried adding < a href=".$row["URL"]."> in outpur'array' but it destroys my page.
You should be able to easily add the URL field to form a valid URL if the contents of that field is indeed a valid URL. What I see missing form your code is http or https if it's an external link. If it's a relative link within the page then you're ok. Then add the </a> to close the link. So you'd form your table column like this:
echo '<td>' . $row["URL"] . '</td>';

Cant get image using php

I´ve been working on this project for a quite while and, the other day I was doing some code when I walk by this piece of code that keeps giving me headaches. So i got my html and php code all right but whenever i try to upload an image to my database, the image goes null, what am i doing wrong?
<?php include "connection.php"; ?>
<?php
$n=$_POST["num"];
$t=$_POST["texto"];
$i=$_POST["imagem"];
$img = mysql_query("SELECT imagem2 from segurancaofensiva where nmr=$n");
$file = $_FILES['imagem']['tmp_name'];
$image = addslashes(file_get_contents($file));
$count = $connect->query("SELECT COUNT(DISTINCT nmr) FROM segurancaofensiva")->fetch_row()[0];
if ($connect->connect_error){
die("Connection failed: " . $connect->connect_error);
}
$sql = "UPDATE segurancaofensiva SET texto='$t', imagem='{$image}', imagem2='{$image}' where nmr=$n" ;
$sql1 = "UPDATE segurancaofensiva SET texto='$t', imagem='$img' where nmr=$n";
if ($_FILES['imagem']['name']!=='' && $connect->query($sql) !== false )
{
if ($n <= $count) {
echo "actualizou\n\n";
var_dump($n);
var_dump($i);
var_dump($image);
}
else
{
echo "nao atualizou numero fora dos limites";
}
} else {
if ($connect->query($sql1) !== false){
echo "atualizou\n\n";
} else {
echo "errp";
}
}
$connect->close();
?>
<?php include 'connection.php'; ?>
<?php
$campo = $_POST['selected'];
$query = "SELECT campo FROM segurancaofensiva";
$result1 = mysqli_query($connect, $query);
$stored = $campo;
$obterquery = "SELECT * FROM segurancaofensiva where campo ='$campo'";
$x = $connect->query ($obterquery) or die ("Erro na variavel resultado");
$final = $x->fetch_array (MYSQL_ASSOC);
?>
<html>
<body>
<head>
<link rel="stylesheet" type="text/css" href="css/styleBO.css">
</head>
<div class="formulario" style="width: 100%; height: 100%;">
<form name="form2" method="POST" action="">
<h6>Campo:</h6> <select name ="selected" id="selected" >
<?php while($row1 = mysqli_fetch_array($result1)):;?>
<option value="<?php echo $row1[0];?>"><?php echo $row1[0];?></option>
<?php endwhile;?>
</select>
<input type="submit" id="load" class="load" name="load" value="Carregar">
<input type="hidden" name="selectedValue" value="0"/><br>
</form>
</div>
<div class="formulario" id="form2" style="width: 100%; height: 100%;">
<form name="form1" target="apresenta" method="POST" action="menu3.php">
<label> Atualizar dados </label><br>
<h6>Texto:</h6><textarea name="texto" id="texto"><?php echo htmlspecialchars($final['texto']);?></textarea><br>
<h6>Imagem:</h6><input type="file" name="imagem"><br>
<input type="hidden" value="<?php echo htmlspecialchars($final['nmr']);?>" name="num">
<input type="submit" name="submit" value="Enviar" class="topo">
<input type="reset" value="Limpar" class="topo">
</form>
</div>
</body>
</html>
Change form html like below. PHP will not detect file object without this.
<form enctype="multipart/form-data">
Add form attribute as per your requirement.
You are missing enctype attribute in form tag
enctype='multipart/form-data'
If you post data and trying to upload file you must use enctype

Simple webpage cannot load some image from MySQL database, some works well

I have a simple webpage and a database to upload and show image on webpage.However, some image cannot be downloaded and shown correctly on webpage, some images show well. I have checked my database, each image can be inserted into database correctly.
My PHP code is below:
<?php
ini_set('mysql.connect_timeout',10);
ini_set('default_socket_timeout',5);
include_once 'dbconnect.php';
?>
<?php
if(isset($_POST['btn_Upload_Image']))
{
if(getimagesize($_FILES['image']['tmp_name']) == FALSE)
{
// echo "Please select an image.";
?>
<script>alert('Please select an image.');</script>
<?php
}
else
{
$image= addslashes($_FILES['image']['tmp_name']);
$Name= addslashes($_FILES['image']['name']);
$image= file_get_contents($image);
$image= base64_encode($image);
saveimage($Name,$image);
}
}
//displayimage();
function saveimage($Name,$Image)
{
$qry="Insert into Clothing (Picture_Name,Picture_Storage) values ( '$Name','$Image')";
// echo "$qry" ."</br>";
$result=mysql_query($qry);
if($result)
{
?>
<script>alert('Image uploaded.');</script>
<?php
}
else
{
?>
<script>alert('Image not uploaded.');</script>
<?php
}
}
function displayimage()
{
$qry = "Select * from Clothing";
$result=mysql_query($qry);
while($row = mysql_fetch_array($result))
{
echo '<img height="200" width="200" src="data:image;base64,'.$row[Picture_Storage].' "> ';
}
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hello PeekABuy</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
<div id="left">
<label>Cropped Images </label>
</div>
</div>
<div id="body">
<div id="Hotel-InfoForm">
<form method="post" enctype="multipart/form-data">
<center>
<table align="center" width="40%" border="0">
<tr>
<td>
<input type="file" name="image" />
<br/>
<br/>
<input type="submit" name="btn_Upload_Image" value="Upload" />
</td>
</tr>
<center>
</table>
<br>
<br>
<br>
<br>
<br>
<br>
</form>
<?php
displayimage();
?>
<br>
<br>
<br>
<br>
<hr>
</div>
</div>
</body>
</html>
1:How webpage looks like; 2: Datatype of my database; 3: Inserting status
Thanks a lot!

Add Image with php to MySQL blob data

In the last hours I tried many codes but none of them works.
I try to upload an image to my database. But the Picture doesnt show on the localhost database :(
The other variables like Titel etc. are okay.
My Code is like this:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<meta charset="ISO-8859-1">
<title>Film Hinzufügen</title>
<script type=“text/javascript”>
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
<?php
if (isset($_POST['addButton'])) {
//SQL Injection defence!
//Variablen hinzufügen
$Titel = $_POST['Titel'];
$Genre = $_POST['Genre'];
$Picture = $_POST['Datei'];
$Erscheinungsjahr = $_POST['Erscheinungsjahr'];
$FSK = $_POST['FSK'];
$Filmdauer = $_POST['Filmdauer'];
$Beschreibung = $_POST['Beschreibung'];
$imgData =$_POST['Beschreibung'];
//Film hinzufügen
$con = mysql_connect("127.0.0.1","root","");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysql_select_db("db_movie_usr");
$sqlString = "INSERT INTO t_movie (FilmTitel, Genre, Erscheinungsjahr, FSK, Filmdauer, Beschreibung, Picture) VALUES ('".$Titel."','".$Genre."','".$Erscheinungsjahr."','".$FSK."','".$Filmdauer."','".$Beschreibung."','file_get_contents($imgData)')";
if (mysql_query($sqlString)) {
header("Location:MainPage.php");
}
}
else {
print (" ");
}
?>
</head>
<body class="body2" >
<form METHOD ="POST" ACTION = "AddMovie.php">
<div style="margin:0 auto;text-align:center">
<div class="centre" >
<table class="tg">
//Add the Title, Genre etc.
</table>
<input name="Datei" type="file" size="50" accept="text/*">
<input type="Submit" name="addButton" value="Film adden" >
</div>
</div>
</form>
</body>
</html>
In my MySQL Database is a mediablob data.
Do you guys see my problem?
Sorry for the bad code. It is my first php code and I need to do this as my homework.
Just copy and paste this body to your code:
<body class="body2" >
<form method="POST" action="AddMovie.php" enctype="multipart/form-data">
<div style="margin:0 auto;text-align:center">
<div class="centre" >
<table class="tg">
//Add the Title, Genre etc.
</table>
<input name="Datei" type="file" size="50" accept="text/*">
<input type="Submit" name="addButton" value="Film adden" >
</div>
</div>
</form>
</body>
Also use this php code:
<?php
if (isset($_POST['addButton'])) {
//SQL Injection defence!
//Variablen hinzufügen
$Titel = $_POST['Titel'];
$Genre = $_POST['Genre'];
$Picture = $_FILES['Datei']['tmp_name'];
$Erscheinungsjahr = $_POST['Erscheinungsjahr'];
$FSK = $_POST['FSK'];
$Filmdauer = $_POST['Filmdauer'];
$Beschreibung = $_POST['Beschreibung'];
$imgData =$_POST['Beschreibung'];
//Film hinzufügen
$con = mysql_connect("127.0.0.1","root","");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysql_select_db("db_movie_usr");
$sqlString = "INSERT INTO t_movie (FilmTitel, Genre, Erscheinungsjahr, FSK, Filmdauer, Beschreibung, Picture) VALUES ('".$Titel."','".$Genre."','".$Erscheinungsjahr."','".$FSK."','".$Filmdauer."','".$Beschreibung."','file_get_contents($imgData)')";
if (mysql_query($sqlString)) {
header("Location:MainPage.php");
}
}
else {
print (" ");
}
?>

Using a variable with a changing value in MySQL query?

I'm building a tagging system for a site I'm working on. I have a variable for the url of the image that changes as the user selects different pictures. I'm using a MySQL command to display 3 tags for the selected picture, but it isn't working if I give it that changing variable. However, if I manually insert a url of an image, the captions show. However, these will show no matter what picture you're on so that doesn't really help. If I store a url under a variable, that works too, but not with the one that changes all the time.
Here's the site.
I know this isn't very easy to understand, so please let me know if you want me to try re-explaining something or if you want me to include some of the code. Thanks!
EDIT: Ok, I'll retry here. First, here's the code:
<?php
$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());
//Do the query
$query = mysql_query("SELECT * FROM images ORDER BY idnum DESC LIMIT 5");
// Generate an array of all images.
$images = array();
while($image = mysql_fetch_array($query)) {
// Adds each image to the images array.
$images[] = $image;
}
$image['filename'] = $current_image;
$query_captions = mysql_query("SELECT * from captions WHERE image = '$current_image' ORDER BY idnum DESC LIMIT 3");
$captions = array();
while($caption = mysql_fetch_array($query_captions)) {
$captions[] = $caption;
}
?>
<?php
// Beginning attempt at a caption script.
?>
<html>
<head>
<title>Home - Site in Development</title>
<link rel="stylesheet" type="text/css" href="styles.css"/>
<script type="text/javascript">
// Switches the url to view large image.
function switchImageUrl(url, width, height) {
var x = document.getElementById('caption_selection');
var y = document.getElementById('caption_input');
var z = document.getElementById('input_value');
x.style.display = 'none';
y.style.display = 'none';
z.value = '';
document.getElementById('center_frame').style.backgroundImage = 'url' + '(' + url + ')';
document.getElementById('center_frame').style.width = width;
document.getElementById('center_frame').style.height = height;
}
</script>
<!--Toggles view of caption selection tools and resets after.-->
<script type="text/javascript">
function selectionToggle() {
var x = document.getElementById('caption_selection');
var y = document.getElementById('caption_input');
var z = document.getElementById('input_value');
if(x.style.display == 'block')
x.style.display = 'none';
else
x.style.display = 'block';
x.style.width = '75px';
x.style.height = '75px';
x.style.top = '0px';
x.style.left = '0px';
if(y.style.display == 'block')
y.style.display = 'none';
else
y.style.display = 'block';
z.value = '';
}
</script>
<script type="text/javascript">
function collectAttributes() {
var cap = document.getElementById('caption_selection');
var cw = document.getElementById('cap_width');
var ch = document.getElementById('cap_height');
var cl = document.getElementById('cap_left');
var ct = document.getElementById('cap_top');
cw.value = cap.style.width;
ch.value = cap.style.height;
cl.value = cap.style.left;
ct.value = cap.style.top;
}
</script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
$("#caption_selection").draggable({
containment : "#center_frame"
});
$("#caption_selection").resizable({
containment : "#center_frame"
});
});
</script>
</head>
<body onLoad="CalculateAllImageWidthes()">
<div id='account_links'>
<?php
if ($_SESSION['username']) {
echo "Welcome $username!";
} else { ?>
<a href='login.php'>Login</a> | <a href='register.php'>Register</a>
<?php } ?>
</div>
<h1>Picture Captions</h1>
<br/>
<br/>
<div id="left_bar">
Submit a picture here.
<hr/>
<h2>Top Images</h2>
<br/>
<div id="front_pg_images">
<?php foreach($images as $image) { ?>
<a onClick="switchImageUrl('<?php echo $image['filename']; ?>', '<?php echo $image['width']; ?>', '<?php echo $image['height']; ?>')"><img src="<?php echo $image['filename'];?>" width="72px" height="58px" id="front_pg_thumbnail"/></a>
<?php echo $image['name']." - by ".$image['submitter']; ?> <br/>
<br/>
<?php } ?>
</div>
</div>
<div id="center_frame" style="width: <?php echo $image['width']; echo "px" ?>; height: <?php echo $image['height']; echo "px" ?>; background-image: url('<?php echo $image['filename'];?>')" >
<?php foreach($captions as $caption) { ?>
<div id="set_caption" style="width:<?php echo $caption['width'].'px';?>;height:<?php echo $caption['height'].'px';?>; left:<?php echo $caption['posleft'].'px';?>; top:<?php echo $caption['postop'].'px';?>"><?php echo $caption['text'];?></div>
<?php } ?>
<div id="caption_selection" style="display:none">
</div>
</div>
<div id="toggle_select_container">
<input type="button" id="toggle_select" onClick="selectionToggle()" value="Caption"/>
<div id="caption_input" style="display:none">
<form action="postcaption.php" method="post" onSubmit="collectAttributes()">
<br/>
<textarea name="caption_text" cols="27" rows="4" id="input_value"></textarea><br/>
<input type="hidden" name="filename" value="<?php echo $image['filename'];?>"/>
<input type="hidden" name="width" value="" id="cap_width"/>
<input type="hidden" name="height" value="" id="cap_height"/>
<input type="hidden" name="left" value="" id="cap_left"/>
<input type="hidden" name="top" value="" id="cap_top"/>
<input type="submit" value="Post Caption"/>
</form>
</div>
</div>
</body>
</html>
It uses a JavaScript function to change the image when the user clicks on the thumbnail. Take note of the foreach. For everywhere else on the page, the $image['filename'] has worked perfectly for similar uses, but it just isn't working when I try to use it with this.

Categories