How to keep file from deleting - php

I am creating a website where I can edit texts, and upload a picture for my texts. The picture get uploaded to a server and the file path is saved in the MySQL database. I made a function to update content, including the picture. If I upload a new picture, the old one gets deleted from the server.
The problem is if I DON'T upload the picture, the old picture still gets deleted!
I just started programming and I need your help with this guys!
My code
<?php
include_once('../include/config.php');
include_once('../include/functions.php');
getHeader('Boek updaten', 'Schrijf een boek!');
if (isset($_GET['action']) == 'save')
{
$id = $_GET["id"];
$boek_naam = $_POST['boek_naam'];
$boek_text = $_POST['boek_text'];
$boek_genre = $_POST['boek_genre'];
$allow = array("jpg", "jpeg", "gif", "png");
if(isset($_FILES['cover']['name'])) {
$query = $db->prepare("
SELECT `boeken_cover` FROM `boeken` WHERE boeken_id = '$id'");
$query->execute();
foreach($query->fetchAll() as $row){
$old_cover = $row['boeken_cover'];
}
chmod($old_cover, 0600);
unlink($old_cover);
$imgdir = "../images/";
$fulldir = $imgdir.$_FILES['cover']['name'];
if (!!$_FILES['cover']['tmp_name']) {
$info = explode('.', strtolower($_FILES['cover']['name']));
if (in_array(end($info), $allow)) {
if (move_uploaded_file($_FILES['cover']['tmp_name'], $imgdir . basename($_FILES['cover']['name']))) {
echo "Foto uploaden gelukt";
}
}
}
try
{
$query=$db->prepare("
UPDATE `boeken` SET `boeken_naam` = :naam, `boeken_text` = :text, `boeken_genre` = :genre, `boeken_cover` = :fulldir WHERE `boeken_id` ='$id'");
$query->bindParam(':naam', $boek_naam);
$query->bindParam(':text', $boek_text);
$query->bindParam(':genre', $boek_genre);
$query->bindParam(':fulldir', $fulldir);
$query->execute();
echo "Het boek is geupdated. Klik <a href='index.php'>hier</a> om naar het overzicht te gaan.";
}
catch(PDOException $e)
{
$sMsg = '<p>
Regelnummer: '.$e->getLine().'<br/>
Bestand: '.$e->getFile(). '<br/>
Foutmelding: '.$e->getMessage().'
</p>';
trigger_error($sMsg);
}
}
else{
try
{
$query=$db->prepare("
UPDATE `boeken` SET `boeken_naam` = '$boek_naam', `boeken_text` = '$boek_text', `boeken_genre` = '$boek_genre' WHERE `boeken_id` ='$id'");
$query->execute();
echo "Het boek is geupdated. Klik <a href='index.php'>hier</a> om naar het overzicht te gaan.";
}
catch(PDOException $e)
{
$sMsg = '<p>
Regelnummer: '.$e->getLine().'<br/>
Bestand: '.$e->getFile(). '<br/>
Foutmelding: '.$e->getMessage().'
</p>';
trigger_error($sMsg);
}
}
}
else {
$id = $_GET["id"];
try {
$query = $db->prepare("
SELECT * FROM `boeken` WHERE boeken_id = '$id'");
$query->execute();
} catch (PDOException $e) {
$sMsg = "<p>
Regelnummer: " . $e->getLine() . "<br />
Bestand: " . $e->getFile() . "<br />
Foutmelding: " . $e->getMessage() . "
</p>";
trigger_error($sMsg);
}
while ($rij = $query->fetch(PDO::FETCH_ASSOC)) {
$boeken_id = $rij["boeken_id"];
$boeken_naam = $rij["boeken_naam"];
$boeken_genre = $rij["boeken_genre"];
$boeken_text = $rij["boeken_text"];
}
echo "
<form name = \"boeken updaten\" action=\"?action=save&id=$id\" method=\"post\" enctype=\"multipart/form-data\">
<table>
<tr>
<td>Boek naam</td>
<td><input type=\"text\" name=\"boek_naam\" value=\"$boeken_naam\" required> </td>
</tr>
<tr>
<td>Boek genre</td>
<td><input type=\"text\" name=\"boek_genre\" value=\"$boeken_genre\" required> </td>
</tr>
<tr>
<td>Cover</td>
<td><input type='file' name='cover' id='cover'></td>
</tr>
<tr>
<td>Inhoud</td>
<td><textarea cols='50' rows='20' name='boek_text'>$boeken_text</textarea></td>
</tr>
<tr>
<td colspan=\"2\" ><input type=\"reset\" name=\"reset\" value=\"Leeg maken\">
<input type=\"submit\" name=\"submit\" value=\"Updaten\"</td>
</tr>
</table>
</form>";
}
getFooter();
?>
Thank you guys!
Ali

You have to check in posted form if it having picture or not
if(!empty($_FILES['NAME_OF_YOUR_INPUT_TYPE_FILE']['tmp_name'])){
unlink($oldFile);
}

This code with the extra ! will have the effect of reversing the state
if (!!$_FILES['cover']['tmp_name']) {
says if ( not not $_FILES['cover']['tmp_name']) {
use only one !
if (!$_FILES['cover']['tmp_name']) {

Try to change the following line
if(isset($_FILES['cover']['name'])) {}
to
if(isset($_FILES['cover']['name']) && !empty($_FILES['cover']['name'])) {}

Related

Inserting checkbox values into multiple rows

I have an echo of a number of groups a user is a member of.
It will output multiple checkboxes. The value of the checkboxes (groupid)+ 2 hidden values need to be inserted into a row in a new table.
How do I insert the values per checkbox into separate rows?
<?php
$user=$_SESSION['SESS_USERID'];
if(isset($_REQUEST['user'])){
$user = preg_replace('#[^a-z0-9]#i', '', $_GET['user']);
}
if(isset($_REQUEST['id'])){
$id = preg_replace('#[^a-z0-9]#i', '', $_GET['id']);
}
$sql="SELECT * FROM groepsleden,groepen,werken WHERE groepsleden.groepid=groepen.groepid
AND groepsleden.userid='$user'AND werken.werkid='$id' ORDER BY groeplidid DESC ";
$result = $conn->query($sql) or die ("The query could not be completed. try again");
if ($result->num_rows > 0) {
echo" <table>";
while ($row = $result->fetch_assoc()) {
echo"<tr>
<td bgcolor='#1E1E1E'> </td>
<td bgcolor='#1E1E1E'><div align='right'>
<input name='groepid' type='checkbox' value=" . $row['groepid'] . ">
<input type='hidden' name='werkid' value=" . $row['werkid'] . ">
<input type='hidden' name='userid' value=" . $row['userid'] . ">
</div></td>
<td bgcolor='#1E1E1E'>Paats dit werk in <a href='groep.php?
id=" . $row['groepid'] . "'</a>".$row["groepsnaam"]."</span></td></tr></table>
}
}
?>
<?php
$sql=$dbo->prepare("INSERT INTO groepwerken(werkid,groepid,userid)
VALUES ('$werkid','$groepid','$user')");
$sql->bindParam(':werkid',$werkid,PDO::PARAM_INT);
$sql->bindParam(':groepid',$groepid,PDO::PARAM_INT);
$sql->bindParam(':userid',$userid,PDO::PARAM_INT);
Veldnamen als array ....
name="groepid[]"
name='werkid[]'
name='userid[]'
vervolgens kun je met foreach door deze waarden heen loopen
$werkid = $_POST['werkid'];
$userid = $_POST['userid'];
$x = 0;// teller zodat we juiste element kunnen selecteren
foreach($_POST['groepid'] as $groepen)
{
if($groepen!=="") // als niet leeg is
{
$juisterwerkid = $werkid[$x];
$juisteuserid= $userid[$x];
$degroep = $groepen;
$x++; // teller ophogen adhv element
echo "Groep: ".$groepen." juisterwerkid: ".$juisterwerkid." juisteuserid: ".$juisteuserid."";
}
}
zoiets zou moeten werken :)

how can i display values from table according to a column between two dates and time?

I have two tables floattable(dateandtime,mitm,tagindex,value,status,marker) and tagtable(tagname,tagindex,tagtype,tagdatatype).i want to display output as
<form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
<p>REPORT</p>
Select AI Type:
<select name="AI-Types" id="AI-Tpes">
<option value="select">--Select--</option>
<option value="DTP4">DTP4</option><option value="FT1">FT1</option><option value="FT2">FT2</option><option value="FT3">FT3</option><option value="LT1">LT1</option><option value="LT2">LT2</option><option value="PT1">PT1</option><option value="PT2">PT2</option>
<option value="PT3">PT3</option><option value="TE1">TE1</option><option value="TE2">TE2</option><option value="TE4">TE4</option><option value="VFD">VFD</option><option value="XT3">XT3</option><option value="XT4">XT4</option><option value="PT2">PT2</option>
</select><br><br>
<b>From Date:</b>
<input type="date" id="fromdate" name="fromdate" value="<?php if(isset($fromdate)) echo $fromdate;?>" size="20" />
<b>To Date:</b>
<input type="date" id="todate" name="todate" value="<?php if(isset($todate)) echo $todate;?>" size="20"/><br><br>
<b>From Time:</b>
<input type="time" id="fromtime" name="fromtime" value="<?php if(isset($fromtime))echo $fromtime;?>" size="30" />
<b>To Time:</b>
<input type="time" id="totime" name="totime" value="<?php if(isset($totime)) echo $totime;?>" size="30"/><br><br>
<input type="submit" id="submit" name="submit" value="GENERATE"/> <input type="reset" id="reset" name="reset" value="RESET"/><br><br>
</div>
</body>
</html>
<?php
if(isset($_POST["submit"]))
{
$fromdate=$_POST['fromdate'];
$todate=$_POST['todate'];
$fromtime=$_POST['fromtime'];
$totime=$_POST['totime'];
if(!$fromdate || !$todate ||!$fromtime||!$totime)
echo " please provide all the fields";
global $conn;
// Create connection
$conn = mysqli_connect('localhost', 'root', '','test');
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
$sql ="SELECT * FROM floattable WHERE TagIndex=$tagindex AND (DateAndTime between '$fromdate .' '. $fromtime' AND '$todate .' '. $totime') ORDER BY DateAndTime ASC;";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
function fill_data($tagindex)
try{
function fill_data($tagindex)
{//for IP
if (($tagindex=0)||($tagindex=1)||($tagindex=2)||($tagindex=3)||($tagindex=4)||($tagindex=5)||($tagindex=6)||($tagindex=7)||($tagindex=8)||($tagindex=10)||($tagindex=11)||($tagindex=12)||($tagindex=13)||($tagindex=14)||($tagindex=14)||($tagindex=15)||
($tagindex=16)||($tagindex=17)||($tagindex=18)||($tagindex=19)||($tagindex=20)||($tagindex=21)||($tagindex=22)||($tagindex=23)||($tagindex=24)||($tagindex=25)||($tagindex=26)||($tagindex=27)||($tagindex=28)||($tagindex=29)||($tagindex=30)||($tagindex=31)||($tagindex=32)||
($tagindex=33)||($tagindex=34)||($tagindex=35)||($tagindex=36)||($tagindex=37)||($tagindex=38)||($tagindex=39)||($tagindex=40)||($tagindex=41)||($tagindex=42)||($tagindex=43)||($tagindex=44)||($tagindex=45)||($tagindex=46)||($tagindex=47)||($tagindex=48)||($tagindex=49))
{
// to display output
echo "<table border='1' cellspacing='3' align='centre'>
<tr>
<th>DateAndTime</th>
<th>Millitm</th>
<th>TagIndex</th>
<th>Value</th>
<th>Status</th>
<th>Market</th>
</tr>";
while ($row = mysqli_fetch_array($result))
{
echo " <tr>
<td>".$row['DateAndTime']."</td>
<td>".$row['Millitm']."</td>
<td>".$row['TagIndex']."</td>
<td>".$row['Val']."</td>
<td>".$row['Status']."</td>
<td>".$row['Marker']."</td>
</tr>";
}
echo "</table>";
}
}
}
catch (Exception $e)
{
echo $e->getmessage();
exit(1);
}
if(isset($_POST['submit']))
{
$selected_val = $_POST['AI-Types'];
try{
$currentSheet = "DTP4";
fill_data(0);
fill_data(1);
fill_data(2);
$currentSheet = "FT1";
fill_data(3);
$currentSheet = "FT2";
fill_data(4);
$currentSheet = "FT3";
fill_data(5);
fill_data(6);
$currentSheet = "LT1";
fill_data(7);
$currentSheet = "LT2";
fill_data(8);
fill_data(9);
$currentSheet = "PT1";
fill_data(10);
$currentSheet = "PT2";
fill_data(11);
fill_data(12);
fill_data(13);
fill_data(14);
$currentSheet = "PT3";
fill_data(15);
fill_data(16);
$currentSheet = "TE1";
fill_data(17);
fill_data(18);
fill_data(19);
$currentSheet = "TE2";
fill_data(20);
fill_data(21);
fill_data(22);
fill_data(23);
$currentSheet = "TE4";
fill_data(24);
fill_data(25);
fill_data(26);
fill_data(27);
fill_data(28);
fill_data(29);
$currentSheet = "VFD";
fill_data(30);
fill_data(31);
fill_data(32);
fill_data(33);
fill_data(34);
fill_data(35);
fill_data(36);
$currentSheet = "XT3";
fill_data(37);
fill_data(38);
$currentSheet = "XT4";
fill_data(39);
$currentSheet = "PT2";
fill_data(40);
}
catch (Exception $e)
{
echo $e->getmessage();
exit(1);
}
}
mysqli_close($conn);
}
?>
but the issue is that in floattable tagindexes are in 0-81 indexes and I want to get all records which are having their tagindex eg. 1 but conditions are like I have to sort data according to tagnames from tag table eg.DTP4_xxxx/IP(its a tagname).I have written a method fill_data($tagindex).
I am new at PHP.plz help me.Thanks in advance
Try this..
$date="2012-12-25";
$time="00:00:00";
$date1="2012-12-25";
$time1="23:59:59";
$firstdatetime=$date." ".$time;
$seconddatetime=$date1." ".$time1;
$data=mysql_query("SELECT * FROM floattable
WHERE DateAndTime BETWEEN '$firstdatetime AND '$seconddatetime'");

mysqli_real_escape_query, query seems ok, but nothing written in database

I have a form, method="post" where users can input info like their name and email, that then get's inserted in a database. For safety I tried to use mysqli_real_escape_string.
Now, the query says it worked but no data get's inserted in my database. Without the escape everything worked allright too (except for not being escaped)
CODE:
(Updated missing quote, it's there in my original code, so that's not the problem. Sry for that)
if(isset($_POST['submit'])) {
$email = explode('#',$_POST['mail']); //explode because I only need the prefix
$maila = mysqli_real_escape_string($link,$email[0]);
$name = mysqli_real_escape_string($link,$_POST['name']);
$query = "INSERT INTO base(mail,name) VALUES ('$maila','$name')";
if(mysqli_query($link,$query)) {
echo "SUCCES";
}
else {
echo "FAIL";}
}
So when I process the query, SUCCES comes up but the mail and name don't arrive in my table.
I googled and searched here, but couldn't find a solution (excuse me if I overlooked it). I also hope I posted enough of my code.
Extra info:
Before the SQL-query goes into action the form is checked in a way like
if($_POST['name'] == null){echo "an error message";}
EDIT; FULL CODE (I am aware that there are mistakes/stupid things in my if-statements, but these work fine without escaping so I will check these later)
<?php
if(isset($_POST['submit'])) {
if($_POST['ios'] == null ) {$resios = 0;} else {$resios = $_POST['ios'];}
if($_POST['android'] == null) {$resand = 0;} else {$resand = $_POST['android'];}
if($_POST['windows'] == null) {$reswin = 0;} else {$reswin = $_POST['windows'];}
//Check for errors
if($_POST['naam'] == null) {echo "<span class=\"error\">Gelieve een naam in te vullen</span><br />";}
if($_POST['opleiding'] == 0) {echo "<span class=\"error\">Selecteer een opleiding</span><br />";}
if($resios > $ios) {$resios = $ios; echo "<span class=\"error\">Aantal iOS tablets overschreden. Maximum " . $ios . " tablets beschikbaar.</span><br />";}
if($resand > $android) {$resand = $android; echo "<span class=\"error\">Aantal Android tablets overschreden. Maximum " . $android . " tablets beschikbaar.</span><br />";}
if($reswin > $windows) {$reswin = $reswin; echo "<span class=\"error\">Aantal Windows tablets overschreden. Maximum " . $windows . " tablets beschikbaar.</span><br />";}
if($resios < 0) {$resios = 0; echo "<span class=\"error\">Aantal tablets kan niet lager zijn dan 0!</span><br />";}
if($resand < 0) {$resand = 0; echo "<span class=\"error\">Aantal tablets kan niet lager zijn dan 0!</span><br />";}
if($reswin < 0) {$reswin = 0; echo "<span class=\"error\">Aantal tablets kan niet lager zijn dan 0!</span><br />";}
if($_POST['terms'] != 'on') {echo "<span class=\"error\">Reglement moet aanvaard worden.</span><br />";}
if($resios == 0 && $resand == 0 && $reswin == 0) {echo "<span class=\"error\">Er moet minstens 1 tablet gereserveerd worden</span>";}
else {
//ESCAPE + INSERT
$email = explode('#',$_POST['mail']);
$maila = mysqli_real_escape_string($link,$email[0]);
$opleiding = mysqli_real_escape_string($link,$_POST['opleiding']);
$naam = mysqli_real_escape_string($link,$_POST['naam']);
$datum = mysqli_real_escape_string($link,$datum);
$resios = mysqli_real_escape_string($link,$resios);
$resand = mysqli_real_escape_string($link,$resand);
$reswin = mysqli_real_escape_string($link,$reswin);
$opmerking = mysqli_real_escape_string($link,$_POST['opmerking']);
$query = "INSERT INTO reservaties(oplid,naam,datum,ios,android,windows,emailname,opmerking) VALUES ('$opleiding','$naam','$datum','$resios','$resand', '$reswin','$maila', '$opmerking')";
if(mysqli_query($link,$query)) {
echo "<p class=\"succes\">U hebt succesvol " . $resios . " iOS-tablets, " . $resand . " Android-tablets en " . $reswin . " Windows-tablets gereserveerd op " . $disdate . "</p>";
echo "<p>Een bevesting van uw reservatie via mail? <form style=\"display:inline;\" target=\"_blank\" action=\"print.php\" method=\"post\"><input type=\"text\" name=\"mail\" value=\"".$maila."\" />#arteveldehs.be <input type=\"hidden\" name=\"naam\" value=\"".$_POST['naam']."\"/><input type=\"hidden\" name=\"datum\" value=\"". $datum . "\"/><input type=\"submit\" name=\"print\" value=\"mail\"></form></p>";
}
else {
echo "<p class=\"error\">Er is een fout opgetreden. Probeer opnieuw, of neem contact op met de Mediatheek.</p>";}
}
}
?>
<!-- my form-->
<form action="#" method="post">
<table>
<tr><td colspan="3"><span class="required">*</span> = verplicht veld</td></tr>
<tr><td>Naam:<span class="required">*</span></td><td><input type="text" name="naam" placeholder="Naam" /></td></tr>
<tr><td>Email:</td><td><input type="text" name="mail" placeholder="voornaam.naam" />#arteveldehs.be</td></tr>
<tr><td>Opleiding:<span class="required">*</span></td><td colspan="2">
<select name="opleiding">
<option value="0">Selecteer een opleiding</option>
<?php
$sql2 = "SELECT SUM(ios) as iostotal,SUM(android) as androidtotal,SUM(windows) as windowstotal FROM reservaties WHERE '$datum' = datum";
$check2 = mysqli_query($link,$sql2) or die(mysql_error());
while ($free2 = mysqli_fetch_array($check2)) {
$iosall = 16;
$andall = 18;
$winall = 20;
$ios2 = $iosall - $free2['iostotal'];
$android2 = $andall - $free2['androidtotal'];
$windows2 = $winall - $free2['windowstotal'];
}
$opleidingen = "SELECT * FROM opleidingen";
$values = mysqli_query($link,$opleidingen) or die(mysql_error());
while ($row = mysqli_fetch_array($values)) {
$oplid = $row['oplid'];$opleiding = $row['opleiding'];
echo "<option value=\"".$oplid."\">".$opleiding."</option>";
}
?>
</select>
</td></tr>
<tr><td>Aantal iOS</td><td><input type="text" name="ios" placeholder="<?= $ios2;?>" ><span class="max">(maximum <?= $ios2;?> beschikbaar)</span></td></tr>
<tr><td>Aantal Android</td><td><input type="text" name="android" placeholder="<?= $android2;?>" ><span class="max">(maximum <?= $android2;?> beschikbaar)</span></td></tr>
<tr><td>Aantal Windows</td><td><input type="text" name="windows" placeholder="<?= $windows2;?>" ><span class="max">(maximum <?= $windows2;?> beschikbaar)</span></td></tr>
<tr><td>Opmerking:</td><td colspan="2"><textarea maxlength="512" rows="5" cols="50" name="opmerking" placeholder="Bv. Tijdstip van oppikken/terugbrengen - vraag aan de mediatheek - ..." ></textarea></td></tr></table>
<input type="checkbox" name="terms" value="on" /> Hiermee verklaar ik me akkoord met het <a target="_blank" href="reglement.php">reglement</a> dat geldt voor het gebruik van deze tablets.<span class="required">*</span>
<p><input type="submit" name="submit" value="Reserveer"/></p>
</form>
<?php }
?>
DATABASE reservaties
resid int(9) PRIMARY KEY
oplid int(9)
naam varchar(55) latin1_swedish_ci
datum date
ios varchar(3)
android varchar(3)
windows varchar(3)
emailname
opmerking varchar(512) latin1_swedish_ci
As per OP's original posted question
You have a missing quote for your query:
$query = "INSERT INTO base(mail,name) VALUES ('$maila','$name') ;
// right there --^
do:
$query = "INSERT INTO base(mail,name) VALUES ('$maila','$name')";
Using error reporting would have helped shown the error http://www.php.net/mysqli_error
Since no error was thrown (at you), this tells me that you are not using error reporting.
if (!mysqli_query($link,$query))
{
die('Error: ' . mysqli_error($link));
}
These or die(mysql_error()) need to be changed to or die(mysqli_error()) since mysql_* and mysqli_* based functions do not mix with each other.
Try this, You have missed to close "
$query = "INSERT INTO `base` (`mail`,`name`) VALUES ('$maila','$name')";
you have missed end " in your query string.
replace this line:
$query = "INSERT INTO base(mail,name) VALUES ('$maila','$name');
by this:
$query = "INSERT INTO base(mail,name) VALUES ('$maila','$name')";

Image not showing (broken image) but search works

i'm new in programming and have been working on a searchable database which can retrieve images by typing in keywords and after pressing submit will show results and the picture.
But so far i have no luck in getting the picture to show(broken link/image) but my search form does work and does correctly retrieve the name or result.
My table in phpmyadmin name is shoes , and i have 3 columns, 1 id (int15 PRI) ,2 brand/model (varchar 50), 3 picture (longblob).
My code is relative simple and hope you can help me out =)
File name: search.php
<form action="search.php" method="POST">
Name: <input type ="text" name="search_name"> <input type="submit" value="Search">
<?php
if (isset($_POST['search_name'])) {
$search_name = $_POST['search_name'];
if (!empty($search_name)){
if (strlen($search_name)>=3) {
$query = "SELECT * FROM `shoes` WHERE `brand/model` LIKE '%".mysql_real_escape_string($search_name)."%'";
$query_run = mysql_query($query);
$query_num_rows = mysql_num_rows($query_run);
if ($query_num_rows>=1) {
echo $query_num_rows.' Results found:<br>';
while ($query_row = mysql_fetch_array($query_run)) {
$picture = $query_row['picture'];
echo "</br>";
echo $query_row ['brand/model'];
echo "</br>";
echo "</br>";
//header("content-type: image/jpeg");
echo "<img src=image.php?id=".$row['id']." width=300 height=200/>";
echo "</br>";
}
} else {
echo 'No Results Found.';
}
} else {
echo 'Text field must be more than 3 characters.';
}
} else {
echo 'Text Field Cannot be Empty!';
}
}
?>
i have a image.php here
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$conn = mysql_connect("localhost","root","");
if(!$conn){
echo mysql_error();
}
$db = mysql_select_db("phsdatabase");
if(!$db){
echo mysql_error();
}
$id = $_GET['id'];
$query = "SELECT `picture` FROM shoes where id='$id'";
$query_run = mysql_query("$query",$conn);
if($query_run){
$row = mysql_fetch_array($query_run);
$type = "Content-type: image/jpeg";
header($type);
echo $row['picture'];
} else {
echo mysql_error();
}
?>
storeinfo.php to store new info,
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$conn = mysql_connect("localhost","root","");
if(!$conn)
{
echo mysql_error();
}
$db = mysql_select_db("phsdatabase",$conn);
if(!$db)
{
echo mysql_error();
}
#$brandmodel = $_POST['brand/model'];
#$picture = addslashes (file_get_contents($_FILES['picture']['tmp_name']));
#$image = getimagesize($_FILES['picture']['tmp_name']);//to know about image type etc
//$imgtype = $image['mime'];
if (isset($_POST['brand/model'])){
$brandmodelentry = $_POST['brand/model'];
if (!empty($brandmodelentry)){
if (strlen($brandmodelentry)>=3) {
$query ="INSERT INTO shoes VALUES('','$brandmodel','$picture')";
$query_run = mysql_query($query,$conn);
echo '<br>';
echo "Information Stored Successfully!";
} else {
echo mysql_error();
}
echo '<br>';
echo '<br>';
echo "Thank you for Registering new information to our database!";
} else{
echo 'Text Field cannot be empty!';
}
}
?>
newentry.php which register new info
<form enctype="multipart/form-data" action="storeinfo.php" method="POST">
<center>Shoes Information</center>
Brand and Model Name<input type=text name="brand/model">
Picture of Shoes(Acceptable formats:<br>JPEG,JPG,PNG)<input type="file" name="picture" id ="picture">
<input type=submit name="submit" value="Store Information">
Your code is absolutely correct except single line i.e.
echo "<img src=image.php?id=".$row['id']." width=300 height=200/>";
You have to change the line to :
echo '<img src="data:image/jpeg;base64,'
.base64_encode($image['file_data']).'" width=300 height=200/>";
In my experience, the problem my image was broken when I tried to display it from database is the the length of the image, I mean from the database where you put the length of a varchar you should change it to long text.
Your image source should be image file extension not php extension, Please check :
echo "<img src='any jpg,png or gif exetension path' width='300' height='200' />";
for example:
echo "<img src='imagename.png' width='300' height='200' />";

PHP image upload in admin section only allowing client to upload 19 images

I've been working on a client's admin panel (A photography company uploading images to a client's gallery), when I took on the role as web developer, it only allowed him to upload 30 images, even though there was 100 file upload boxes. This was fixed simply by changing the for loop to run 100 times. This fixed this problem.
But recently, without even touching the code, my client can only upload 19 images.. I haven't changed this form, he has previously uploaded 40+ images, so I don't quite understand what could have happened.. I've checked the code over and over, and can't quite seem to pinpoint the issue. Could this be server side, as I've recently moved from his old developer's host to my hostgator account. Maybe something in the htaccess? I add this because the image label's update, but not the image itself (I can't find it uploaded either, after it has been posted, but my browser shows it uploading)
Here is the edit gallery code itself, if it gives any assistance to the problem:
<?php
require_once("../conn.php");
require_once("access.php");
require_once("GalleryNavigation.php");
require_once("dThumbMaker.inc.php");
/////////////common varilable
$__table = "devbg_gallery";
$__page = $_SERVER['PHP_SELF'];
$__page2 = "AddGallery.php";
$__id = "ItemID";
$__pagetitle = "GALLERY";
$__uploadfolder = "../myimages/";
$__thumbuploadfolder = "../myimages/thumbs/";
$__imageprefix = "Gallery";
$Thumb_Imgwidth = 200;
$Thumb_Imgheight = 77;
/////////////
if(isset($_POST[ds]))
{
if(count($_POST['DelItem']) > '0')
{
while(list(, $value) = each($_POST['DelItem']))
{
$DelInfo = $value;
$r2 = mysql_query("select * from ".$__table." where ".$__id." = '$DelInfo' ") or die(mysql_error());
$a2 = mysql_fetch_array($r2);
for($i=1;$i<=100;$i++)
{
if(file_exists($__uploadfolder.$a2['ItemImage'.$i]))
{
unlink($__uploadfolder.$a2['ItemImage'.$i]);
unlink($__thumbuploadfolder.$a2['ItemImage'.$i]);
}
}
//delete the product
mysql_query("delete from ".$__table." where ".$__id." = '".$DelInfo."' ") or die(mysql_error());
}
}
}
if(isset($_POST[s100]))
{
$MyProductName = mysql_escape_string(trim(stripslashes(strip_tags($_POST[ProductName]))));
$Description = mysql_escape_string(trim(strip_tags(stripslashes($_POST['Description']))));
$Link = trim(strip_tags(stripslashes($_POST['Link'])));
$TopLabel = cleaninput($_POST['TopLabel'],"mres|he|tr");
$status = $_POST['status'];
$NewTopLabelName = $TopLabel;
if(!empty($_FILES['TopImage']['name']))
{
$NewTopImageName = $__imageprefix.$t.$_FILES['TopImage']['name'];
if(is_uploaded_file($_FILES['TopImage']['tmp_name']))
{
move_uploaded_file($_FILES['TopImage']['tmp_name'], $__uploadfolder.$NewTopImageName);
$NewTopImageName = $NewTopImageName;
$NewTopLabelName = $TopLabel;
//lets make the thumb
$tm = new dThumbMaker;
$load = $tm->loadFile($__uploadfolder.$NewTopImageName);
if($load === true)
{ // Note three '='
$tm->cropCenter($Thumb_Imgwidth, $Thumb_Imgheight);
$tm->build($__thumbuploadfolder.$NewTopImageName);
}
else
{
// Error returned.
$error .= "Could not open the file '".$NewTopImageName."'.\n";
$error .= "The error returned was: ";
$error .= $load;
}
}
}
else
{
$NewTopImageName = $_POST['OldTopImage'];
$NewTopLabelName = $NewTopLabelName;
}
for($i=1;$i<=100;$i++) //This is where I believe the problem is --------------------------------------------------------------------
{
${'NewsItemLabel'.$i} = cleaninput($_POST['ItemLabel'.$i],"mres|he|tr");
$ItemLabels .= "ItemLabel".$i ." = '". cleaninput($_POST['ItemLabel'.$i],"mres|he|tr") ."',";
if(!empty($_FILES['ItemImage'.$i]['name']))
{
${'NewImageName'.$i} = $__imageprefix.$t.$_FILES['ItemImage'.$i]['name'];
if(is_uploaded_file($_FILES['ItemImage'.$i]['tmp_name']))
{
move_uploaded_file($_FILES['ItemImage'.$i]['tmp_name'], $__uploadfolder.${'NewImageName'.$i});
//lets make the thumb
$tm = new dThumbMaker;
$load = $tm->loadFile($__uploadfolder.${'NewImageName'.$i});
if($load === true)
{ // Note three '='
$tm->cropCenter($Thumb_Imgwidth, $Thumb_Imgheight);
$tm->build($__thumbuploadfolder.${'NewImageName'.$i});
$ItemImages .= "ItemImage".$i ." = '". ${'NewImageName'.$i} ."',";
}
else
{
// Error returned.
$error .= "Could not open the file '".${'NewImageName'.$i}."'.\n";
$error .= "The error returned was: ";
$error .= $load;
}
} else { }
}
else
{
${'NewImageName'.$i} = $_POST['OldItemImage'.$i];
}
}
if(empty($error))
{
//update the database
$q1 = "update ".$__table." set
ItemName = '".$MyProductName."',
Description = '".$Description."',
Link = '".$Link."',
TopImage = '$NewTopImageName',
Toplabel = '$NewTopLabelName',
".$ItemImages.$ItemLabels."
status = '".$status."'
where ".$__id." = '".$_POST[$__id]."' ";
mysql_query($q1) or die(mysql_error());
echo "<br><br><center>Gallery Updated</center>";
}
}
if(!empty($_GET[$__id]))
{
$_POST[$__id] = $_GET[$__id];
}
if(!empty($_POST[$__id]))
{
//get the product info
$r1 = mysql_query("select * from devbg_gallery where ".$__id." = '".$_POST[$__id]."' ") or die(mysql_error());
$a1 = mysql_fetch_array($r1);
echo $error;
?>
<form method=post action=EditGallery.php enctype="multipart/form-data">
<table align=center width=740>
<caption align=center><b>Gallery Name:</b></caption>
<tr>
<td align='right'>Event Name:</td>
<td><input type=text class=input name="ProductName" value="<?php echo $a1['ItemName'];?>"></td>
</tr>
<TR>
<td align='right'>Description:</td>
<td><textarea name="Description"cols=60 rows=10><?php echo $a1['Description'];?></textarea></td>
</TR>
<?php
if(!empty($a1['TopImage']))
{
$v = $a1['TopImage'];
echo "<tr>";
echo "<td></td><td><img src='".$__uploadfolder.$v."' width='72' border='0'><br><a href='DeleteImage.php?".$__id."=".$a1[$__id]."&Type=gallery&file=".$v."&img=top'>Delete Image</a></td>";
echo "</tr>";
}
?>
<tr>
<td align='right'>Top Image:</td>
<td><input type=file name=TopImage></td>
</tr>
<tr>
<td align='right'>Top Image Label:</td>
<td><input type=text name=TopLabel value="<?php echo $a1['TopLabel'];?>"></td>
</tr>
<?php
for($i = 1; $i <= 100; $i++)
{
if($a1['ItemImage'.$i] != "")
{
echo "<tr>";
echo "<td></td><td><img src='".$__uploadfolder.$a1['ItemImage'.$i]."' width='72' border='0'><br><a href='DeleteImage.php?".$__id."=".$a1[$__id]."&Type=gallery&file=".$a1['ItemImage'.$i]."&id=".$i."'>Delete Image</a></td>";
echo "</tr>";
}
echo "<TR><TD align='right'>Image $i: </TD><TD><input type=file name='ItemImage$i'></TD></TR>\n\t";
echo "<TR><TD align='right'>Label $i: </td><TD><input type=text name='ItemLabel".$i."' value='".cleaninput($a1['ItemLabel'.$i],"ss|hd|tr")."' size='79'></TD></TR>\n\t";
echo "<input type='hidden' name='OldImage$i' value='".$a1['ItemImage'.$i]."'>";
echo "<input type='hidden' name='OldLabel$i' value='".cleaninput($a1['ItemLabel'.$i],"ss|hd|tr")."'>";
}
?>
<tr>
<td></td>
<td>
<input type="hidden" name="OldTopImage" value="<?php echo $a1['TopImage'];?>">
<input type="hidden" name="OldTopLabel" value="<?php echo $a1['TopLabel'];?>">
<input type="hidden" name=<?php echo $__id;?> value="<?php echo $_POST[$__id];?>">
<input type="submit" name="s100" value="Edit Gallery">
</td>
</tr>
</form>
<?php
exit();
}
if(!empty($_GET[Start]))
{
$Start = $_GET[Start];
}
else
{
$Start = '0';
}
$ByPage = "10";
//get the products list
$r1 = mysql_query("select * from devbg_gallery order by ordering_id ASC limit $Start,$ByPage") or die(mysql_error());
if(mysql_num_rows($r1) == '0')
{
echo "<center>You have no items at the database!</center>";
exit();
}
?>
<form method=post>
<table align=center width=500 cellspacing="0" cellpadding="3">
<tr style="background-color:#b5c3ce; color:white; font-family:verdana; font-size:11; font-weight:bold">
<td>Title</td>
<td>User</td>
<td align='center'>Edit</td>
<td align='center'>Delete</td>
</tr>
<?php
$col = "white";
$i=0;
while($a1 = mysql_fetch_array($r1))
{
$r2 = mysql_query("select * from tbl_register where GID = '".$a1['ItemID']."'") or die(mysql_error());
$a2 = mysql_fetch_array($r2);
$name = $a2['firstname'] . " " . $a2['lastname'];
$i++;
if($col == "white" )
{
$col = "#f3f6f8";
}
else
{
$col = "white";
}
echo "<tr bgcolor=$col>
<td>".$a1['ItemName']."</td>
<td>".$name."</td>";
echo "<td align=center><input type=radio name='".$__id."' value='".$a1[$__id]."'></td>
<td align='center'><input type='checkbox' name='DelItem[]' value='".$a1[$__id]."'></td>
</tr>\n\n";
}
echo "<tr>
<td colspan=4 align=right><br>\n\t<input class=input type=submit name=ds value='Edit Selected'> <input type='submit' class='input' name='ds' value='Delete Selected'></td>
</tr>
</table>
</form>\n\n";
//build the "next" - "prev" navigatioin
$qnav = "select * from ".$__table." order by ItemName ";
$rnav = mysql_query($qnav) or die(mysql_error());
$rows = mysql_num_rows($rnav);
echo "<br><table align=center width=600>";
echo "<td align=center><font face=verdana size=2> | ";
$pages = ceil($rows/$ByPage);
for($i = 0; $i <= ($pages); $i++)
{
$PageStart = $ByPage*$i;
$i2 = $i + 1;
if($PageStart == $Start)
{
$links[] = " <span class=bodybold>$i2</span>\n\t ";
}
elseif($PageStart < $rows)
{
$links[] = " <a class=bodybold href=EditGallery.php?Start=$PageStart>$i2</a>\n\t ";
}
}
$links2 = implode(" | ", $links);
echo $links2;
echo "| </td>";
echo "</table><br>\n";
?>
<?php include("footer.php");?>
If there's any other information I could provide that would help find a solution, I can post it straight up. This problem has really messed with my head, and my client needs his gallery running! Makes me wish I could have coded this myself and got there before his previous developer. Thanks everybody!
A friend of mine figured out that when I moved host, my max_file_uploads setting in my php.ini was set to 20, and that the code you see above loops each image and tries to upload it, even if there is no image, which explains why even if I only tried to upload 1 by itself, it wouldn't upload any after 19. Just a simple setting overlooked.
Changed this to max_file_uploads = 100 in my ini, everything works fine now, client happy!

Categories