Add Image with php to MySQL blob data - php

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 (" ");
}
?>

Related

sql and php variable

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>;

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

Why do I have all these errors?

In two pages I have there problem. The first problem is before I submitted I get this alert:
(Notice: Undefined index: submit in C:\xampp\htdocs\art-legend\12\admin\add.php on line 15)
and the line 15 in this page is
(if ($_POST['submit'] && !empty($_FILES)){)
The second problem is before I put any image they put that I have an image on the top but I still don't put any image and I have this picture
And the third error is when I upload an image I can't see it and I have a screen like the last screen .
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
<title>Untitled Document</title>
<title>Untitled Document</title>
</head>
<body>
<?
if ($_POST['submit'] && !empty($_FILES)){
$formok = TRUE;
$title = $_POST['title'];
$thread = $_POST['elm1'];
$date = date("d/m/y h;i:s");
$path = $_FILES['upload']['tmp_name'];
$name = $_FILES['upload']['name'];
$size = $_FILES['upload']['size'];
$type = $_FILES['upload']['type'];
$error = $_FILES['upload']['error'];
if (!is_uploaded_file($path)){
$formok = FALSE;
echo "there is no file uploaded try again";
}
if (!in_array($type,array('image/png','image/jpg','image/jpeg'))){
$formok = FALSE ;
echo "the file is not image try again ";
}
if (filesize($path)>800000){
$formok = FALSE ;
echo "the file is bigger ";
}
if ($formok){
if ($connect = mysqli_connect('localhost','root','adminpass','flip')){
$content = file_get_contents($path);
$safetitle = mysqli_real_escape_string($connect,$title);
$safethread = mysqli_real_escape_string($connect,$thread);
$safeimage = mysqli_real_escape_string($connect,$thread);
$sqltitle ="insert into title(title) values ('$safetitle')";
$sqlthread = "insert into threads (topic,date) values ('$safethread','$date')";
$sqlimge ="insert into images (name,size,type,content) values ('$name','$size','$type','$safeimage')";
$querytitle = mysqli_query($connect,$sqltitle);
$querythread = mysqli_query($connect,$sqlthread);
$queryimage = mysqli_query($connect,$sqlimge);
if ($querytitle && $querythread && $queryimage){
$imageid = mysqli_insert_id($connect);
}
mysqli_close($connect);
}
else {
echo "There is error in database connect";
}
echo "insert done all ";
}
}
?>
<img src="image.php?id=<?=$imageid; ?>" />
<hr />
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post" enctype="multipart/form-data">
<p>
title :
<input type="text" name="title" />
</p>
<div>
<textarea id="elm1" name="elm1" rows="15" cols="80" style="width: 80%">
</textarea>
</div>
<input type="hidden" name="MAX_FILE_SIZE" value="800000" />
<p>
<input type="file" name="upload" />
</p>
<p>
<input type="submit" name="submit" value="process" />
</p>
</form>
</body>
</html>
--
<?
$imageid = $_GET['id'];
if ( mysqli_connect('localhost','root','adminpass','flip')){
$escape = mysqli_real_escape_string($connect,$content);
$sql = "select type,content from images where id =$imageid";
$query = mysqli_query($connect, $sql);
$fetch = mysqli_fetch_array($query,MYSQLI_ASSOC);
mysqli_free_result($query);
mysqli_close($connect);
}
else {
echo"ther is no connection 2";
}
if (!empty($fetch)){
header("Content-type:{$fetch['type']}");
echo $fetch['content'];
}
?>
Use isset
isset — Determine if a variable is set and is not NULL
<?
if (isset($_POST['submit']) && !empty($_FILES)){

Derive checkbox state from non-boolean MySQL with PHP

Currently I have a form that makes use of fields and check boxes. The fields and checkboxes both update the database perfectly:
<?php
function renderForm($articletitle, $articleorganization, $articledate, $articleurl, $articletags )
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="stylized" class="myform">
<form id="form" name="form" action="" method="post">
. . .
. . .
if(count($articletags) > 0)
{
$articletags_string = implode(",", $articletags);
}
if (isset($_POST['submit']))
{
$articletitle = mysql_real_escape_string(htmlspecialchars($_POST['articletitle']));
$articleorganization = mysql_real_escape_string(htmlspecialchars($_POST['articleorganization']));
$articledate = mysql_real_escape_string(htmlspecialchars($_POST['articledate']));
$articleurl = mysql_real_escape_string(htmlspecialchars($_POST['articleurl']));
$articletags = implode(',', $_POST['articletags']);
. . .
mysql_query("INSERT articles SET articletitle='$articletitle', articleorganization='$articleorganization', articledate='$articledate', articleurl='$articleurl', articletags='$articletags' ")
or die(mysql_error());
// once saved, redirect to success page
header("Location:addsuccess.html");
}
}
else
{
renderForm('','','','');
}
?>
Now, though, I'm wondering if I should have gone with a boolean checkbox instead.
The reason is that I've built an edit form as well and it follows the new entry form exactly except that values are already filled in via the MySQL DB.
So, I'm assuming that it would be considerably easier to use boolean, right?
So, instead of using an array, I should give the checkboxes different names, and on the edit.php page I can use something like:
<?php
function renderForm($id, $articletitle, $articleorganization, $articledate, $articleurl, $articletags)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="stylized" class="myform">
<form id="form" name="form" action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<h1>Edit Details for <?php echo $articletitle; ?></h1>
<fieldset>
<legend>Article details</legend>
<div class="row">
<div class="field"><label>Article Title</label><input type="text" name="articletitle" value="<?php echo $articletitle; ?>"/></div>
</div>
<div class="row">
<div class="field"><label>Article Author </label><input type="text" name="articleorganization" value="<?php echo $articleorganization; ?>"/></div>
<div class="field"><label>Article Date </label><input type="text" name="articledate" value="<?php echo $articledate; ?>"/></div>
</div>
<div class="row">
<div class="field"><label>Article Url: </label><input type="text" name="articleurl" value="<?php echo $articleurl; ?>"/></div>
<div class="row">
<input type="checkbox" name="articletags1" value="checkbox" id="articletags_0" />
<input type="checkbox" name="articletags2" value="checkbox 2" id="articletags_1" />
</div>
</fieldset>
<footer><input type="submit" name="submit" value="Submit"></footer></form>
</div>
</body>
</html>
<?php
}
include('settings.php');
if (isset($_POST['submit']))
{
if (is_numeric($_POST['id']))
{
$id = $_POST['id'];
$articletitle = mysql_real_escape_string(htmlspecialchars($_POST['articletitle']));
$articleorganization = mysql_real_escape_string(htmlspecialchars($_POST['articleorganization']));
$articledate = mysql_real_escape_string(htmlspecialchars($_POST['articledate']));
$articleurl = mysql_real_escape_string(htmlspecialchars($_POST['articleurl']));
$articletags = implode(',', $_POST['articletags']);
if ($articletitle == '' || $articletags == '')
{
$error = 'ERROR: Please fill in all required fields!';
renderForm($id, $articletitle, $articletags);
}
else
{
mysql_query("UPDATE articles SET articletitle='$articletitle', articleorganization='$articleorganization', articledate='$articledate', articleurl='$articleurl', articletags='$articletags' WHERE id=$id")
or die(mysql_error());
header("Location: editsuccess.html");
}
}
else
{
echo 'Error!';
}
}
else
{
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM articles WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($row)
{
$articletitle = $row['articletitle'];
$articleorganization = $row['articleorganization'];
$articledate = $row['articledate'];
$articleurl = $row['articleurl'];
$articletags = $row['articletags'];
renderForm($id, $articletitle, $articleorganization, $articledate, $articleurl, $articletags, '');
}
else
{
echo "No results!";
}
}
else
{
echo 'Error!';
}
}
?>
The problem with that though is that my checkboxes on the edit.php page still aren't showing the checked state.
You need to use checked="checked" in the same way as you used for value. See the solution bottom:
<input type="checkbox" <?php if(isset($_POST[articletags1])) echo 'checked="checked" ' ?>name="articletags1" value="checkbox" id="articletags_0" />
<input type="checkbox" <?php if(isset($_POST[articletags2])) echo 'checked="checked" ' ?>name="articletags2" value="checkbox 2" id="articletags_1" />
Hope this works. Updated the right code. Use ini_set('display_errors', 1); to get the error generated.

Skipping empty records in mysql with php

I am trying to make a survey but when I have an empty record in my msql database he just shows an empty question is there a possibility to skip empty records?
<?php
session_start();
include "config.php";
connDB();
$some_questions = mysql_num_rows(mysql_query("SELECT id FROM question"));
if($_POST['next'] && $_SESSION['qnumber'] != '' && $_POST['question'.$_SESSION['qnumber']] != '')
{
if($_POST['question1']){
$_SESSION['antwoordjes'] = $_POST['question1'];
}else{
$_SESSION['antwoordjes'] .= '|'.$_POST['question'.$_SESSION['qnumber']];
}
$_SESSION['qnumber']++;
$questionnumber = $_SESSION['qnumber']++;
$sql = "SELECT id, question FROM question WHERE id = '$questionnumber'";
$result = mysql_query($sql);
while ($count = mysql_fetch_array($result)){
if($count['question'] == null)
{
$_SESSION['qnumber']++;
}
}
}
if($_POST['question'.$some_questions] != '' && $_SESSION['qnumber'] >= ($some_questions + 1))
{
mysql_query("INSERT INTO answers (ip,answers,datum) VALUES ('".$_SERVER['REMOTE_ADDR']."','".$_SESSION['antwoordjes']."',NOW())");
session_destroy();
header("Location: outro.php");
}
if($_SESSION['qnumber'] == '' || $_SESSION['qnumber'] >= ($some_questions + 1))
{
$quest = 1;
$_SESSION['qnumber'] = $quest;
}
else{
$quest = $_SESSION['qnumber'];
}
$data = mysql_fetch_array(mysql_query("SELECT question,answers FROM question WHERE id='".$quest."'"));
$answers = explode('|',$data['answers']);
$quest = stripslashes($data['question']);
if(empty($_POST['atext']))
{
}else{
$quest = $_POST['hsvraag'];
$commentary = $_POST['atext'];
toevoegenOverig($commentary, $quest);
}
?>
<script type="text/javascript">
function disablefield(){
if (document.getElementById('yes_radio').checked == 1){
document.getElementById('textbox_A').disabled='disabled';
document.getElementById('textbox_A').value='';
}else{
document.getElementById('textbox_A').disabled='';
document.getElementById('textbox_A').value=''; }
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- <script type="text/javascript" src="abc.js"></script> -->
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Internet onderzoek</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table align="left">
</table>
<div class="centrum">
<div class="header">Internetsurvey</div>
<div class="content" id="content">
<div class="balk">Introductie | <span style="color:#000033;">question</span> | end</div>
<br/>
<form method="post" action="vragenv.php">
<?php
$nummer = 1;
foreach($answers as $answer)
{
echo '<input id="yes_radio" type="radio" name="question'.$_SESSION['qnumber'].'" value="'.$nummer.'" id="answer'.$nummer.'" onChange="disablefield();"/><label for="answer'.$nummer.'">'.$answer.'</label><br />';
echo '<input type="hidden" name="hsvraag" value="'.$quest.'"/>';
$nummer++;
}
?>
</br>
<br/><input type="text" id="textbox_A" required name="atext"/><br />
<input type="submit" name="next" value="next" class="knop" />
</form>
</div>
</div>
</body>
</html>
Tweak your query.
SELECT
`id`,
`question`
FROM
`question`
WHERE
`id` = '$questionnumber'
AND
`question` IS NOT NULL
AND
LENGTH(TRIM(`question`))>1

Categories