Strange behaviours on PHP MYSQL image unlink - php

I have followed several tutorials on here and I can't figure out my mistake.
The Gallery gets displayed correctly, and the check boxes have the right value when I check with Element inspector in Firefox, but this little script I wrote always unlinks the last picture in the loop, and the Database row does not get deleted.
Maybe you have a better eye for what I am missing then myself?
$sql = "SELECT id, title FROM houses ";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
echo $result['title'] . $result['id'];
echo"<br>";
$sql1 = "SELECT * FROM gallery_photos WHERE photo_category=" . $result['id'];
$query1 = mysql_query($sql1);
while ($row = mysql_fetch_array($query1)) {
$photo_filename = $row['photo_filename'];
echo "<form action='' method='post'>
<li style='float:left; list-style-type:none;'>
<img src='houses/" . $photo_filename . "' title='$photo_filename' width='100px'>
<input type='checkbox' name='delete' value='$photo_filename'/> <br>
</li> ";
}
echo "<p style='clear:both' /> <input type='submit' value='Delete Selected' />";
echo" </form>";
echo "<p style='clear:both;'>";
echo "<br><br>";
}
if (isset($_POST['delete']) && is_array($_POST['delete']) && count($_POST['delete']) > 0) {
unlink("THIS/IS/A/WORKING/PATH/houses/" . $photo_filename);
unlink("THIS/IS/A/WORKING/PATH/houses/tb_" . $photo_filename);
mysql_query("DELETE FROM gallery_photos WHERE photo_filename = $photo_filename");
}
?>

You're opening the element each time for the new photo, but the submit button and only one closing tag are outside all of the forms. You may want to fix the html to have this working properly.
EDIT:
The wrong file gets deleted, because you're using $photo_filename variable in the last 3 rows instead of the value from $_POST['delete'].
Side note: this code is really awful and buggy. It's a security nightmare.

something like this should sort it, I have not tested it but hopefully it will work.
foreach ($_POST['delete'] as $filename) {
unlink("THIS/IS/A/WORKING/PATH/houses/" . $filename);
unlink("THIS/IS/A/WORKING/PATH/houses/tb_" . $filename);
mysql_query("DELETE FROM gallery_photos WHERE photo_filename = $filename");
}
echo '<form action='' method='post'>';
$sql = "SELECT id, title FROM houses ";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
echo $result['title'] . $result['id'];
echo"<br>";
$sql1 = "SELECT * FROM gallery_photos WHERE photo_category=" . $result['id'];
$query1 = mysql_query($sql1);
while ($row = mysql_fetch_array($query1)) {
$photo_filename = $row['photo_filename'];
echo "<li style='float:left; list-style-type:none;'>
<img src='houses/" . $photo_filename . "' title='$photo_filename' width='100px'>
<input type='checkbox' name='delete[]' value='$photo_filename'/> <br>
</li> ";
}
echo "<p style='clear:both' /> <input type='submit' value='Delete Selected' />";
echo" </form>";
echo "<p style='clear:both;'>";
echo "<br><br>";
}
notice the [] at the end of the checkbox name, this means that it will create an array of them. You might want to add an additional check around the foreach to prevent it running if the $_POST['delete'] has not been set.

First, just to be sure, you are getting the params, you can use:
echo "<br />Contents of \$_POST:<br />";
foreach ($_POST as $k => $v) {
echo " $k = $v<br />";
}
So you know what params are you getting. And it looks like working.
Also, you can use it, to delete the images,
foreach ($_POST as $k => $v) :
if ( $k == "delete" ) :
// add your code for unlink and delete
endif;
endforeach;
Second, check for permissions before to delete
chmod($this->uploaddir . $this->finalName, octdec(0777)); // Maybe 0666 is enough
#unlink( path_to_file ); // # to avoid see code errors
And just, for you consideration, maybe if you use you don't have to be taking care about float, and clearing
Cheers

Related

PHP Submit Inputs Foreach() ID

I'm trying to submit a form that contains a schedule for each user ID. So far it looks like this:
$sql = "SELECT * FROM dbtable";
$result = $conn->query($sql);
$name_info = "SELECT udidId, name FROM udid";
$name_result = $conn->query($name_info);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$udidId = $row["udidId"];
echo "<label for='hours' class='schedule'><strong>I want <span>".$row["name"]."</span>";
echo "<input type='text' name='udidId' class='hidden' value='".$row["udidId"]."' />";
echo " to be <br />allowed out between <input type='text' name='outAllowedStartHour' placeholder='8' value='" . $row["outAllowedStartHour"] . "'> - <input type='text' name='outAllowedEndHour' placeholder='8' value='" . $row["outAllowedEndHour"] . "'><br />allowed in between <div class='padd_left'></div><input type='text' name='inAllowedStartHour' placeholder='8' value='" . $row["inAllowedStartHour"] . "'> - <input type='text' name='inAllowedEndHour' placeholder='8' value='" . $row["inAllowedEndHour"] . "'></strong></label>";
}
}
if(isset($_POST["update_schedule"])) {
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value' <br />";
while($row = $result->fetch_assoc()) {
foreach($value as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
$update_pets = "UPDATE v_spottData SET $x_value = $x_value WHERE udidId = $x";
$conn->execute($update_pets);
}
}
}
However is only updating inputs from the last ID in the database, and is not updating the input values at all. Any suggestions?
Execute doesn't execute a query, it executes a prepared statement. You need to use prepare to prepare the query.
Prepared statements should use placeholders. The quoting/escaping will be handled by the driver.
Note columns can't be bound/placeheld.
Your current query is trying to update a column with the same value, that can't be right. Change $updating_column below to whatever column you are trying to update.
$columns = array('outAllowedStartHour', 'outAllowedEndHour', 'inAllowedStartHour', 'inAllowedEndHour'); // whitelist columns
if(in_array($updating_column, $columns)) {
$update_pets = "UPDATE v_spottData SET `$updating_column` = ? WHERE udidId = ?";
$stmt = $con->prepare($update_pets);
$stmt->bind_param("ii", $x_value, $x);
$stmt->execute();
} else {
echo 'Using a Not Allowed Column';
}
You can read more about prepared statements here, http://php.net/manual/en/mysqli.quickstart.prepared-statements.php.
I feel really silly, but for anyone else dealing with the issue, my solution was simple.
Try putting the PHP to handle the form submission at the top of your document, instead of at the bottom. Everything worked fine once I moved it up!
Thank you for all of your help everyone, especially #chris85!

Mysql Field Data not displaying when a link is clicked?

I'm trying to get data from a database if a link is clicked.
I used the example codes suggested from this example -Getting mysql field data when a link is clicked?
But it doesn't work when I click on a link nothing comes up.
main.php
<?php
include('conn.php');
$sql2 = "SELECT Title FROM addpromo";
$result2 = mysql_query($sql2);
echo "<div id=\"links\">\n";
echo "<ul>\n";
while ($row2 = mysql_fetch_assoc($result2)) {
echo "<li> <a href=\"fullproject.php?title=\""
. urlencode($row2['Title']) . "\">"
. htmlentities($row2['Title']) . "</a>\n</li>";
}
echo "</ul>";
echo "</div>";
?>
This is displaying correct.but when I click at a link nothing is showing up in fullproject.php, Just a blank page.
fullproject.php
<?php
// Connect to server.
include('conn.php');
$projectname = isset($_GET['Title']);
$sql1 = "SELECT Title FROM addpromo WHERE Title = '$projectname'";
$result1 = mysql_query($sql1);
while ($row1 = mysql_fetch_assoc($result1)) {
echo "Project Name: " . $row1['Title'] . "<br />";
echo "<br /> ";
}
?>
Can someone help me to fix this, or any other way to make this(to get data from a database if a link is clicked) possible?
Change to this
main.php
<?php
include('conn.php');
$sql2="SELECT Title FROM addpromo";
$result2=mysql_query($sql2);
echo '<div id="links">';
echo '<ul>';
while($row2 = mysql_fetch_assoc($result2)){
echo '<li>'.htmlentities($row2['Title']).'</li>';
}
echo '</ul>';
echo '</div>';
?>
fullproject.php
<?php
if(isset($_GET['title'])){
include('conn.php');
$projectname= $_GET['title'];
$sql1="SELECT Title FROM addpromo WHERE Title = '$projectname'";
$result1=mysql_query($sql1);
while($row1 = mysql_fetch_assoc($result1)) {
echo "Project Name: " . $row1['Title']. "<br />";
echo "<br /> ";
}
}
?>
This is storing a boolean value $projectname= isset($_GET['Title']);, whether or not the title is set. Instead use $projectname = $_GET['Title'];
isset returns a boolean value (true/false) and you want the actual value of the variable:
$projectname= $_GET['title'];
Furthermore, you have to pass only the title as the URL parameter, without enclosing it within quotes. So there is an error in this line:
echo "<li> <a href=\"fullproject.php?title=" . urlencode($row2['Title']) . "\">"
Note the lack of \" after title=

PHP Form data not stored when submitted?

I am working on an synonym/alias manager database where the user has the ability to store an association they feel is right. Say the user types in "rabbit" and no synonyms or aliases are found. The user then decides to associate "rabbit" with "bunny" and stores that into a database. Anytime any other user types in "bunny" the results for "rabbit" will appear. However, I am trying to implement a polling system asking the user if they feel the association is correct. If they think "bunny" fits "rabbit" then they vote yes, otherwise no. This is where I am stuck. As soon as I load the poll and press submit everything disappears and nothing gets sent to the database. Code is below:
$query = "SELECT * from searchtestdb where engname in ( SELECT synonyms.synonym FROM words LEFT JOIN synonyms ON synonyms.word_id = words.word_id WHERE word LIKE '%$searchBox%') "; // Query for animals in db
$query = mysql_query($query);
if(mysql_num_rows($query) == 0)
{
echo "<h2>Aliases: </h2>";
echo "Sorry, but we can not find an alias to match your query.";
echo "<br> ";
}
else
{
echo "<h2> Results using Alias: </h2>";
while($result = mysql_fetch_array($query))
{
$query2 = "SELECT * from searchtestdb where engname LIKE '%".$result['engname']."%';";
$result2 = mysql_query($query2);
while($row = mysql_fetch_array($result2))
{
print "<h4>Latin Name: </h4> ";
echo $row["latname"];
echo "<br> ";
print"<h4>English Name:</h4> ";
echo $row["engname"];
echo "<br>";
print "<h4> Species: </h4> ";
echo $row["spectype"];
print "<h4>Characteristics: </h4> ";
echo $row["charc1"];
echo "<br>";
echo $row["charc2"];
echo "<br>";
echo $row["charc3"];
echo "<br>";
}
}
$self = $_SERVER['PHP_SELF'];
print "<form method='post' action='$self' >\n";
print "<h4>Alias Association Correct? : </h4>";
print "<p>" .
"<input type='radio' name='vote' id='vote' value='1' /> \n" .
"Yes" .
"<input type='radio' name='vote' id='vote' value='2' /> \n" .
"No" .
"</p> \n" .
"<p>" .
"<input type='submit'name='submitVote' value='Submit' />" .
"\n </p> \n" .
"</form> \n" .
$vote=htmlentities($_POST['vote']);
echo $vote;
mysql_connect(----------------------) or die(mysql_error());
mysql_select_db("-----------") or die(mysql_error());
if($vote == 1)
{
mysql_query("INSERT INTO items(yes, uNo, word_id) VALUES ('0', '0', bunny');");
mysql_query("UPDATE items SET yes=yes+1 WHERE word_id='bunny';");
echo 'Thanks for voting Yes!';
}
if($vote == 2)
{ mysql_query("INSERT INTO items(word_id) VALUES ('".$result['engname']."'') ");
mysql_query("UPDATE items SET uNo=Uno+1 WHERE word_id='".$result['engname']."'");
echo "changos";
}
}
In a nutshell I made a small mistake:
$self = $_SERVER['PHP_SELF'];
should be
$self = $_SERVER['POST'];
Thanks Anyway.

Php - Checkbox does not work

i try to make checkboxes. When i click checkbox it makes isPremium = 1 if i click a checked checkbox it makes isPremium = 0
However: when i click a checked checkbox it does not work..
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
require 'connectDB.php';
$mysql = new mysql();
$mysql->connect();
$dbResult = mysql_query("select * from profiles");
echo "<form action='#' method='post'>";
$dbResult = mysql_query("select * from profiles");
while ($info = mysql_fetch_array($dbResult)) {
if ($info['isPremium'] == 0)
echo "<input type=checkbox name='check2[]' id='check2' value=" . $info['id'] . ">";
else
echo "<input type=checkbox name='check1[]' id='check1' value=" . $info['id'] . " checked>";
echo $info['profileName'] . "<br />";
}
echo "<p><input type='submit' name='btnPremium' /></p>";
echo "</form>";
if (isset($_POST['btnPremium'])) {
if (isset($_POST['check2'])) {
$arrPremium = $_POST['check2'];
foreach ($arrPremium as $result) {
mysql_query("UPDATE profiles set isPremium=1 where id=" . $result . "");
}
}
else
{
$arrPremium = $_POST['check1'];
foreach ($arrPremium as $result2) {
mysql_query("UPDATE profiles set isPremium=0 where id=" . $result2 . "");
}
}
}
?>
when i click a checked checkbox it makes another checkbox unclick.
This is the checkbox page
I have refactored your code into this:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
require 'connectDB.php';
$mysql = new mysql();
$mysql->connect();
$update = (isset($_POST['check']) && is_array($_POST['check']));
$dbResult = mysql_query("select * from profiles");
echo "<form action='#' method='post'>";
while ($info = mysql_fetch_array($dbResult))
{
if ($update)
{
$info['isPremium'] = (in_array($info['id'], $_POST['check']) ? 1 : 0);
mysql_query("UPDATE profiles SET isPremium = " . $info['isPremium'] . " WHERE id = " . $info['id']);
}
echo "<input type=checkbox name='check[]' value=" . $info['id'] . ($info['isPremium'] == 0 ? "" : "checked") . " />";
echo htmlspecialchars($info['profileName']) . "<br />";
}
echo "<p><input type='submit' name='btnPremium' /></p>";
echo "</form>";
?>
There were several problems with your original code:
Several HTML input elements with the same ID. This is wrong. We can have several elements with the same name attribute, but the id attribute should be unique for each element.
The database UPDATE code runs after displaying the form. This is wrong. In this case, we should update the database prior to generating the HTML output.
IMPORTANT: There is no need of two different POST arrays (check1 and check2). We only need one array. The checked boxes will be posted by the browser. The unchecked boxes will not be posted by the browser. As the id is the value, we can use the in_array function to verify if the checkbox for an item was checked or not.
It is a good idea to escape things you will output as HTML from the database. Otherwise, the application is vulnerable for some kinds of attack. The function htmlspecialchars is useful for this purpose.
If I understand correctly what you're trying to achieve, your code is needlessly complicated. You should use isset to check whether the value of a checkbox was included in the $_POST array. If yes, the checkbox was checked.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
require 'connectDB.php';
$mysql = new mysql();
$mysql->connect();
echo "<form action='#' method='post'>";
$dbResult = mysql_query("SELECT * FROM profiles");
$profileid = array();
while ($info = mysql_fetch_array($dbResult)) {
echo "<input type=\"checkbox\" name=\"" . $info['id'] . "\" " . ($info['isPremium'] != 0 ? "checked " : "") . "/>";
echo $info['profileName'] . "<br />";
$profileid[] = $info['id'];
}
echo "<p><input type='submit' name='btnPremium' /></p>";
echo "</form>";
if (isset($_POST['btnPremium'])) {
foreach ($profileid as $id) {
if (isset($_POST[$id])) {
mysql_query("UPDATE profiles SET isPremium=1 WHERE id=" . $id);
} else {
mysql_query("UPDATE profiles SET isPremium=0 WHERE id=" . $id);
}
}
}
?>
Checkboxes typically send the value "on" to the server, regardless of what value attribute is set. If you can, try to use radio buttons instead, as these send the proper value to the server. If that's not an option, have the name of the checkbox be check1[".$info['id']." and access array_keys($_POST['check1']).

How can I send over multiple check box checks in POST to be deleted from a database?

I've been trying think of a way to do this. I want it to where users can check off items, hit submit and it goes to the code on the next page and deletes all of the checked items from the database. Problem one is that in the post its only sending over the last checked item. Here is how I have it set up right now.
echo "<form name='fm1' METHOD ='POST' ACTION ='displaydelete.php' > ";
//Draws up the table headers
echo "";
echo "";
echo "Fund Number ";
echo "Hours ";
echo "Percentage";
echo "Delete";
echo "";
//While there are query results data is pushed into table cells
while ($row = mysql_fetch_array($queryResult2))
{
$hours = $row['hours'];
$percentage = $hours / 160 * 100;
echo "<tr>";
echo "<td>";
echo $row['funnumber'];
echo "</td>";
echo "<td>";
echo $hours;
echo "</td>";
echo "<td>";
echo $percentage ."%";
echo "</td>";
echo "<td>";
echo "<input type='checkbox' name='id' value='$row[id]'/>";
echo "</td>";
echo "</tr>";
}
//End of tabel
echo "</table>";
echo" ";
echo "";
What I would like to do is push all of the items into a variable and maybe delete them that way. I'm not really sure how you would handle multiple deletes. I'm doing my delete like this for something else if this helps any.
$query = "DELETE FROM users
WHERE ninenumber = '$ninenumber'";
$result = mysql_query($query)
or die("Query Failed: " .mysql_error());
mysql_close($conn);
In your form:
<input type='checkbox' name='id[]' value='$row[id]'/>
Then, in the file you post to:
if(is_array($_POST['id'])){
foreach($_POST['id'] as $id){
...do something to $id;
}
}
Instead of this:
echo "<input type='checkbox' name='id' value='$row[id]'/>";
You need this:
echo "<input type='checkbox' name='id[]' value='$row[id]'/>";
Note the difference. I added [] after the input name. This tells the client and server that there are multiple inputs with that name. $_POST['id'] will be an array you can loop through on the next page.
foreach ($_POST['id'] as $checkbox) {
// DELETE FROM users WHERE ninenumber = $checkbox
}
isset, is_array, and mysql_real_escape_string omitted for brevity.
In the form-generating code, make the name in the html have" []" after it:
...
echo "<input type='checkbox' name='id[]' value='$row[id]'/>";
...
Then, in the form-reading code, your post'ed id will be an array.
$id_array = isset($_POST['id']) && is_array($_POST['id']) ? $_POST['id'] : array();
foreach( $id_array as $id ) {
$query = "DELETE FROM users WHERE ninenumber = '" . mysql_real_escape_string($id) . "'";
// execute the delete query
}
Putting [] after the name of a control will turn it into an array in the superglobal that you can then iterate over to get all the values from.
You need to have the same name for all of your checkboxes, then all values are passed as array POST variable.
<input type='checkbox' name='id[]' value='$row[id]'/>
Change
name=id
to
name=id[]
this will then give you an array.

Categories