check if file input field is empty using foreach loop - php

I have 7 file input fields namely:
<input type="file" accept="image/*" name="imgreq1">
<input type="file" accept="image/*" name="imgreq2">
<input type="file" accept="image/*" name="imgreq3">
<input type="file" accept="image/*" name="imgreq4">
<input type="file" accept="image/*" name="imgreq5">
<input type="file" accept="image/*" name="imgreq6">
<input type="file" accept="image/*" name="imgreq7">
How can I check if the other input fields are empty if I for example uploaded a file in the first and the second input fields. Then submit the form leaving the other fields empty?
Update:
<?php
if(isset($_POST['sumit'])){
$count = count($_FILES);
for($i = 1; $i <= $count; ++$i){
if(is_uploaded_file($_FILES['imgreq'.$i]['tmp_name']) || !file_exists($_FILES['imgreq'.$i]['tmp_name'])){
echo "$i";
// your code
}else{
//to retrieve user_id to stored in the request table in the database
$query = "SELECT * FROM dummyclients_tbl WHERE user_id = '".$_SESSION['user']."'";
if (!$result = mysql_query($query)) {
exit(mysql_error());
}
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_assoc($result)){
$sid= ''.$row['user_id'].'';
$coll=''.$row['college'].'';
$stat="Pending";
//$query="SELECT document_name FROM document_tbl WHERE document_id = '$passed_id'";
//$dn=mysql_query($query);
//$getname=mysql_fetch_assoc($dn);
//var_dump($getname);
//to analyze the contents of the image selected in filebrowser1
$image1=addslashes($_FILES['imgreq1']['tmp_name']);
$name1=addslashes($_FILES['imgreq1']['name']);
$image1=file_get_contents($image1);
$image1=base64_encode($image1);
//to analyze the contents of the image selected in filebrowser2
$image2=addslashes($_FILES['imgreq2']['tmp_name']);
$name2=addslashes($_FILES['imgreq2']['name']);
$image2=file_get_contents($image2);
$image2=base64_encode($image2);
//to analyze the contents of the image selected in filebrowser3
$image3=addslashes($_FILES['imgreq3']['tmp_name']);
$name3=addslashes($_FILES['imgreq3']['name']);
$image3=file_get_contents($image3);
$image3=base64_encode($image3);
//to analyze the contents of the image selected in filebrowser4
$image4=addslashes($_FILES['imgreq4']['tmp_name']);
$name4=addslashes($_FILES['imgreq4']['name']);
$image4=file_get_contents($image4);
$image4=base64_encode($image4);
//to analyze the contents of the image selected in filebrowser5
$image5=addslashes($_FILES['imgreq5']['tmp_name']);
$name5=addslashes($_FILES['imgreq5']['name']);
$image5=file_get_contents($image5);
$image5=base64_encode($image5);
//to analyze the contents of the image selected in filebrowser6
$image6=addslashes($_FILES['imgreq6']['tmp_name']);
$name6=addslashes($_FILES['imgreq6']['name']);
$image6=file_get_contents($image6);
$image6=base64_encode($image6);
//to analyze the contents of the image selected in filebrowser7
$image7=addslashes($_FILES['imgreq7']['tmp_name']);
$name7=addslashes($_FILES['imgreq7']['name']);
$image7=file_get_contents($image7);
$image7=base64_encode($image7);
//function nga defined sa dalum para i insert ang uploaded files sa databasess
saveimage($sid,$passed_id,$image1,$image2,$image3,$image4,$image5,$image6,$image7,$stat,$coll);
}
}
}
}
}
function saveimage($sid,$passed_id,$image1,$image2,$image3,$image4,$image5,$image6,$image7,$stat,$coll){
$con=mysql_connect("localhost","root","");
mysql_select_db("dummy",$con);
$qry="INSERT INTO request_tbl (user_id,document_id,imgreq1,imgreq2,imgreq3,imgreq4,imgreq5,imgreq6,imgreq7,request_status,college) VALUES ('$sid','$passed_id','$image1','$image2','$image3','$image4','$image5','$image6','$image7','$stat','$coll')";
$result=mysql_query($qry,$con);
if($result){
?>
<script>alert('Requirements Successfully Submitted!');</script>
<?php
}else{
?>
<script>alert('Error while submitting form!');</script>
<?php
}
}
?>

From OP's comment,
But how can you do it using for each loop this feature of php is a deep one ...
Use a simple for loop, in conjunction with is_uploaded_file() function, to check whether user has uploaded a file via HTTP POST or not, like this:
$count = count($_FILES);
for($i = 1; $i <= $count; ++$i){
if(is_uploaded_file($_FILES['imgreq'.$i]['tmp_name'])){
// user has uploaded a file
}
}
Update:
Based on the below discussion with OP, the complete solution would be like this:
<?php
if(isset($_POST['sumit'])){
$count = count($_FILES);
$query = "SELECT * FROM dummyclients_tbl WHERE user_id = '".$_SESSION['user']."'";
if (!$result = mysql_query($query)) {
exit(mysql_error());
}
if(mysql_num_rows($result)){
$row = mysql_fetch_assoc($result);
$sid = $row['user_id'];
$coll =$row['college'];
$query = "INSERT INTO request_tbl (user_id,document_id,imgreq1,imgreq2,imgreq3,imgreq4,imgreq5,imgreq6,imgreq7,request_status,college) VALUES ('$sid','$passed_id'";
for($i = 1; $i <= $count; ++$i){
if(is_uploaded_file($_FILES['imgreq'.$i]['tmp_name']) && $_FILES['imgreq'.$i]['size']){
$query .= ",'" . base64_encode(file_get_contents(addslashes($_FILES['imgreq'.$i]['tmp_name']))) . "'";
}else{
$query .= ",NULL";
}
}
$query .= ",'$stat','$coll')";
saveimage($query);
}
}
function saveimage($qry){
$con = new mysqli("localhost", "root", "", "dummy");
$result=mysqli_query($con, $qry);
if($result){
?>
<script>alert('Requirements Successfully Submitted!');</script>
<?php
}else{
?>
<script>alert('Error while submitting form!');</script>
<?php
}
}
?>
As a sidenote, learn about prepared statement as it prevents your query from any kind of SQL injection attacks. Here's a good read on how you can prevent SQL injection in PHP.

Related

input file Update images inside database

So im trying to change the image thats already inside the database but i cant seem to make it work i kept looking at tutorials and other related questions but couldnt find the exact solution.
this is what i have in php
// Als de knop van de formulier is ingedrukt update de data dat van de database afkomt
if (isset($_POST['update'])) {
if (isset($_GET['id'])) {
$chauffeurs_id = $_GET['id'];
}
if (isset($_POST['Chauffeurs_foto'])) {
$Chauffeurs_foto = $_POST['Chauffeurs_foto'];
}
$sql = "SELECT * FROM chauffeurs ORDER BY 'chauffeurs_geboortedatum ASC";
$sql = "UPDATE `chauffeurs`
SET `Chauffeurs_foto`=$Chauffeurs_foto
WHERE `id`='$chauffeurs_id'";
$result = $conn->query($sql);
if ($result == TRUE){
echo "Aanpassingen zijn voltooid.";
}else{
echo "Error:" . $sql . "<br>" . $conn->error;
}
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "SELECT * FROM `chauffeurs` WHERE `id`='$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$chauffeurs_foto = $row['chauffeurs_foto'];
}
$backId = $_SESSION['krijgid'];
Here is my html code:
<!-- Formulier waar alles in komt om te veranderen -->
<form action="" method="post" enctype='multipart/form-data' >
<fieldset>
<legend>Gegevens chauffeur:</legend>
<div class="form-group col-md-4">
//I did it like this so i could style the input file
<input type="file" name="file" id="file" class="inputfile" value="data:image/jpeg;base64, <?php.base64_encode($row['chauffeurs_foto']).?>" />
<label class="btn btn primary"for="file">Choose a file</label>
<input type="submit" value="Chauffeur Aanpassen" name="update">
</fieldset>
</form>
</div>
If anyone of you has a solution i would greatly appreciate it cause i need to finish it for my internship if not i'm just going to keep searching.
File uploads can be tricky. May I suggest you start by reading the documentation on file uploading first?
You will see that your upload can best be reached using the $_FILES array. You will need to store the uploaded data in a variable, using the file_get_contents() method. And it's the file data you'll be uploading to your mySQL server.
Your code should look something like this:
$foto = file_get_contents($_FILES['file']['tmp_name']);
$sql = "UPDATE `chauffeurs` SET `Chauffeurs_foto`='{$foto}' WHERE `id`='$chauffeurs_id'";
Finally, it's generally not good practise to store file data in your database, as the database size can get out of hand if the number of files you're storing in it grows. You're better off storing files (and images) separately and only storing a file reference in the database.
You have mistakes in your '. Try this code:
session_start();
include "config.php";
if (isset($_POST['update'])) {
if (isset($_GET['id'])) {
$chauffeurs_id = $_GET['id'];
}
if (isset($_POST['Chauffeurs_foto'])) {
$Chauffeurs_foto = $_POST['Chauffeurs_foto'];
}
$sql = "UPDATE chauffeurs SET Chauffeurs_foto = '$Chauffeurs_foto' WHERE id = '$chauffeurs_id'";
$result = $conn->query($sql);
if ($result == TRUE){
echo "Aanpassingen zijn voltooid.";
}else{
echo "Error:" . $sql . "<br>" . $conn->error;
}
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "SELECT * FROM `chauffeurs` WHERE `id`='$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$chauffeurs_foto = $row['chauffeurs_foto'];
}
$backId = $_SESSION['krijgid'];
}
}
Assuming this is for a real application, you should properly escape SQL values for security reasons. Never trust user input! I'm going to assume you're using mysqli, so I'm using mysql::real_escape_string().
Also, you should properly embed your variables in the query, like so:
if (isset($_GET['id'])) {
$chauffeurs_id = $conn->real_escape_string($_GET['id']);
}
if (isset($_POST['Chauffeurs_foto'])) {
$Chauffeurs_foto = $conn->real_escape_string($_POST['Chauffeurs_foto']);
}
$sql = "SELECT * FROM chauffeurs ORDER BY `chauffeurs_geboortedatum` ASC"; // This statement can you remove, it will never be used in this way
$sql = "UPDATE `chauffeurs` SET `Chauffeurs_foto` = '{$Chauffeurs_foto}' WHERE `id`='{$chauffeurs_id}'";
Succes ermee.

Creating the Name of the checkbox dynamically in PHP

I have just written this code and assign the name of the check box dynamically and delete the selected checkbox when delete button is pressed. But it isn't working. Can somebody help me??
main.php
$snooverhtml = "select * from songs_list";
$query7 = mysqli_query($con, $snooverhtml);?>
<form method="post" action="delete.php">
<input id="deletebtn" type="submit" name="deletethis" value="Delete"/></br>
<?php while($row = mysqli_fetch_assoc($query7)):?>
<input type="checkbox" name="<?php echo "cb".$row['sno.'];?>"/><?php echo $row['sno.']?> <?php echo $row['songs_name']?></br>
<?php
endwhile;
?>
delete.php
$noofsongs = "select * from songs_list";
$query8 = mysqli_query($con, $noofsongs);
$noio = mysqli_num_rows($query8);
$flag = 0;
if(isset($_POST['deletethis'])){
for($j=0; $j<=$noio ;$j++){
if (isset($_POST['<?php echo"cb".$j;?>'])){
$deletesongsquery = "DELETE FROM `songs_list` WHERE `sno.` = $j" ;
$query4 = mysqli_query($con, $deletesongsquery);
$flag = $flag + 1;
}
}
echo $flag;
}
You are already in PHP so $_POST['<?php echo"cb".$j;?>'] is incorrect. That is looking for <?php echo"cb".$j;?> literally as an index of $_POST which it never finds so isset is false. Use:
$_POST['cb'.$j']
or in your code usage:
if (isset($_POST['cb'. $j])){
You also should use parameterized queries. http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/manual/en/security.database.sql-injection.php

PDO Echoing Duplicate Results

I need to echo a download button if there are certain correct results, but when I echo the download button it decides to echo more than 1. How do I correct this?
heres my code:
<?php
$u = $_SESSION["username"];
$getscripts = $conn->prepare("SELECT * FROM project_sa");
$getscripts->execute();
while ($row = $getscripts->fetch(PDO::FETCH_BOTH)) {
$sec = $conn->query('SELECT * FROM us WHERE username="wafflezzz"');
$sec->execute();
while ($rowx = $sec->fetch(PDO::FETCH_BOTH)) {
$checker = $rowx[$row["script_title"]];
if ($checker == $row["script_title"]) {
$geturl = $conn->prepare("SELECT * FROM project_sa WHERE script_title='$checker'");
$geturl->execute();
while ($row = $geturl->fetch(PDO::FETCH_BOTH)) {
echo '
<form method="post" action="dl.php">
<input name="bname" value="<?php echo $branded_m_img_url; ?>" hidden></input>
<input type="submit" class="ui huge button" value="Download"></input>
</form>';
}
}
}
}
?>
It returns about 2 broken duplicate entries when there is only 1 entry in the database!
"You have nested while loops, that's why you get duplicate entries, you also overwrite $row in the inner while loop – Alon Eitan yesterday"
After I fixed that, it worked!

<input type = "file"> EMPTY

i have this problem regarding file upload on php.
I always get this error msg.
Warning: file_get_contents(): Filename cannot be empty in
C:\xampp\htdocs\omf2\emprecords\add8.php on line 25
this is my line 25
$data = $con->real_escape_string(file_get_contents($_FILES['uploaded_file']['tmp_name']));
But still saves the info on my database.
What i am trying to do is save the rest of the records on my database even if not selecting a file to upload. And yes the records are saved and the Attachment field (mediumblob) is [BLOB - 0 B]
Question: How can i eliminate the error/warning message? (because everything is really fine)
<meta http-equiv="refresh" content="2;URL='emphistory.php'">
<?php
{
echo "<center><font color='#AAA' size='3'><br/>Record Added!</center>";
}
?>
<?php
$con=mysqli_connect("localhost","root","","dbomf");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM valueholder");
$row = mysqli_fetch_array($result);
$count = '';
$IDNUM = $row['Val'];
$NS = addslashes($_POST ['NS']);
$ad = addslashes($_POST ['ad']);
$hr = addslashes($_POST ['HR']);
$name = $con->real_escape_string($_FILES['uploaded_file']['name']);
$data = $con->real_escape_string(file_get_contents($_FILES['uploaded_file']['tmp_name']));
include ('../dbconn.php');
$query = "INSERT INTO tblemphist1 VALUES
('".$count."', '".$IDNUM."', '".$NS."', '".$ad."', '".$hr."', '".$data."', '".$name."')";
$result = $db->query($query) or die($db->error);
$db->close();
here
<form method="post" action="add8.php" enctype="multipart/form-data">
<td><strong>Attachment</strong></td>
<td>:</td>
<td><input type="file" name="uploaded_file"></td>
</tr>
</form>
<input type = "file">
should be
<input name="uploaded_file" type = "file">
also form method should be post and use enctype='multipart/form-data
<form action="" method="post" enctype="multipart/form-data">
<input name="uploaded_file" type = "file">
</form>
also check
$name = ''; $data = '';
if ((is_uploaded_file($_FILES['uploaded_file']['tmp_name']) && !($_FILES['uploaded_file']['error'])) {
$name = $con->real_escape_string($_FILES['uploaded_file']['name']);
$data = $con->real_escape_string(#file_get_contents($_FILES['uploaded_file']['tmp_name']));
}
include ('../dbconn.php');
$query = "INSERT INTO tblemphist1 VALUES ('".$count."', '".$IDNUM."', '".$NS."', '".$ad."', '".$hr."', '".$data."', '".$name."')";
$result = $db->query($query) or die($db->error);
Use an if statement. For example:
if (!empty($_FILES)) {
$data = $con->real_escape_string(
file_get_contents($_FILES['uploaded_file'] ['tmp_name'])
);
}
Before accessing any property of $_FILES['uploaded_file'] you have to check the value $_FILES['uploaded_file']['error']. And yes, it's a good idea to check if such key exists at all - as with anything coming from the user, there is no guarantee that it exists in the request.
Simply check if the variable is not empty
$data = '';
if (!empty($_FILES['uploaded_file']['tmp_name'])) {
$data = $con->real_escape_string(file_get_contents($_FILES['uploaded_file']['tmp_name']));
}
if error doesn't affect your project just ignore it and add this code in top of your php.
<?php ERROR_REPORTING(E_ALL & ~E_NOTICE); ?>
it will ignore and hide the error. :)

Two arrays in foreach loop?

having difficulties because of my noobness, again. I dont know if I am doing this right, but I need to post an id variable with an array through a foreach loop to a mysql db. If that made no sense, its probably due to my lack of ability to articulate with technical jargon, so ill just post the code. Please view the notes in the PHP code.
Any help always appreciated.
Cheers, Lea
FORM:
<form method="post" action="<?php echo $PHP_SELF; ?>" enctype="multipart/form-data">
<?php
$num = 0;
while($num < $num_uploads)
{
?>
<input type="hidden" name="item_id[]" value="<?php echo $stockno; ?>" />
<input type="file" id="myfile" name="userfile[]" size="40">
<?php $num++;
}
?>
<input type="submit" name="Preview" value="Preview" />
</form>
PHP SCRIPT:
if(isset($_POST['Preview']) ) {
// START PHOTO QUERY
if(isset($_FILES['userfile']['tmp_name']))
{
/** loop through the array of files ***/
for($i=0; $i < count($_FILES['userfile']['tmp_name']);$i++)
{
// check if there is a file in the array
if(!is_uploaded_file($_FILES['userfile']['tmp_name'][$i]))
{
$messages[] = 'No file uploaded';
}
/*** check if the file is less then the max php.ini size ***/
elseif($_FILES['userfile']['size'][$i] > $upload_max)
{
$messages[] = "File size exceeds $upload_max php.ini limit";
}
// check the file is less than the maximum file size
elseif($_FILES['userfile']['size'][$i] > $max_file_size)
{
$messages[] = "File size exceeds $max_file_size limit";
}
else
{
// copy the file to the specified dir
if(#copy($_FILES['userfile']['tmp_name'][$i],$upload_dir.'/'.$_FILES['userfile']['name'][$i]))
{
/*** give praise and thanks to the php gods ***/
$messages[] = $_FILES['userfile']['name'][$i].' uploaded';
$name[] = $_FILES['userfile']['name'][$i];
$id[] = $_POST['item_id'];
// HAVING DIFFICULTIES HERE
foreach( $name as $value ) {
$sql = "INSERT INTO stock_photos (photo_filename) VALUES ('$value')";
mysql_query($sql);
foreach( $id as $val ) {
$sql2 = "UPDATE stock_photos SET photo_item_id = '$val' WHERE photo_filename = '$value'";
mysql_query($sql2) or die(mysql_error());
}
}
// END DIFFICULTIES HERE
}
else
{
/*** an error message ***/
$messages[] = 'Uploading '.$_FILES['userfile']['name'][$i].' Failed';
}
}
}
}
// END PHOTO QUERY
}
I think you have a flaw in your logic. You don't want to have a nested foreach loop. Think about it:
You are looping over each filename. For each filename, you are looping over all IDs and update the filename ID with with each value from the ID array. You are basically overwriting the ID in the database with every UPDATE call, eventually setting the value to the last value of the $id array.
Thus, you actually should have the loops one after each other.
Assuming your $name and $id are filled properly and both contain the same number of items, you can do even better, using a normal for loop:
for($i = 0; $i < count($name); $i++ ) {
$sql = "INSERT INTO stock_photos (photo_filename, photo_item_id) VALUES ('". mysql_real_escape_string($name[$i]) . "', '" . mysql_real_escape_string($id[$i] . "')";
mysql_query($sql);
}
Note: Never never never trust user input, so take precautions through filtering and escaping like I did with mysql_real_escape_string().
Update:
And you can do even better with just one MySQL query by inserting multiple values at once:
function prepare($name, $id) {
return sprintf("'%s', '%s'",
mysql_real_escape_string($name),
mysql_real_escape_string($id));
}
$values = array_map('prepare', $name, $id);
$sql = 'INSERT INTO stock_photos (photo_filename, photo_item_id) VALUES (' . implode('),(', $values) . ')';
mysql_query($sql);
Reference: sprintf, array_map, implode

Categories