I have this code where I get all the rows out of my mySQL database:
<?php
$result = mysql_query("SELECT * FROM `photos` WHERE `photo_category` = 1 AND `photo_active` = 1");
while($row = mysql_fetch_array($result)) {;
?>
<img src="<?php echo $row['thumb_path'] ?>"><br>
Creatie datum: <?php echo $row['photo_date'] ?><br>
Delete picture
<?php }; ?>
I would like to delete the image where my delete button is on. I have no idea how I should start or how I can achieve this. Any help is welcome!
Like others have stated, check out PDO or mysqli for your interface between your database. To your question. You need to issue a MySQL DELETE command. In order for this to work, your mysql user needs to have delete privileges on the table you are deleting the row from. Using your example above, the sql would look like this:
<html>
<img src="<?php echo $row['thumb_path'] ?>"><br>
Creatie datum: <?php echo $row['photo_date']; ?><br>
<form name="photo_<?php echo $row['photo_id']; ?>_delete" action="doDelete.php" method="post">
<input type="hidden" name="photo_id" value="<?php echo $row['photo_id']; ?>">
<input class="delete_button" type="submit" name="submit" value="delete">
</form>
</html>
<?php //doDelete.php
if ($_POST['submit'] == 'delete') {
$photo_id = $_POST['photo_id'];
$sql = "DELETE FROM photos WHERE photo_id = " . $photo_id . " LIMIT 1";
if (mysql_query($sql)) {
//photo deleted.
} else {
//handle errors.
}
}
?>
In order for this to work, you're going to need to add a primary key to your photos table.
Related
I've created a mysql table with two columns. One is ID and other is Heading. I have a textarea on which I run UPDATE code and whenever someone submits a form its being updated in the datebase column under heading. And that works fine but I want to show the last inputted submit inside my textarea.
My code is showing the last inputted value but when I reset the page it all turns out blank and its not showing anymore. I looked out in datebase and the heading is still there so I don't know why its dissapearing from the front end.
My page:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
So for example if I type Aleksa, after submit it will get url like edit.php?heading=Aleksa&submit=Submit. And then when I delete url just to edit.php, the value is missing.
You can test the page here: https://www.easybewussterschaffen.com/admin/edit.php
This is happening, because it's always trying to insert the heading when you refresh the page. You should check to see if the request is GET or the request is POST, and only insert it if they're submitting the form.
Update your form method, specify it to POST, and specifically check the method or check for the existance of $_POST['submit'] as shown below:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
// Use one of the 2 if statements:
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Trying to insert a new heading
if (isset($_POST['submit'])) { // Alternative
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="POST">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
Alternatively, if you still wish to make a GET request, you should check to make sure that the heading is set:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
if (isset($_GET['submit'])) {
$heading = mysqli_real_escape_string($link, $_GET['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="GET">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
I did it like this, is this good tho? Its working
<?php
$sql = "SELECT * FROM content";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo '';
while($row = mysqli_fetch_array($result)){
echo $row['heading'];
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>
so I'm working on a school project to create a portfolio showcase website, one of the main required functions is to create a like button for the images. I'm using xampp to host the files and database. I'm trying to make it so tat each time a person clicks the button, it would add +1 to the 'likes' column in the table, but it doesn't seem to be working. I'm still new to this so thorough explanation would be appreciated.
this is the block of code that as the
<h1><?php echo $_SESSION['name'] ?>'s work </h1>
<?php
$username ="root";
$password ="";
$hostname ="localhost";
//connection to database
$conn = mysqli_connect($hostname,$username,$password)
or die("unable to connect to my SQL");
$lastid = $_SESSION['user'];
$image3 = "SELECT * FROM staff.image WHERE `user`='$lastid' ";
$r=mysqli_query($conn, $image3);
while ($row = mysqli_fetch_array($r))
{
?>
<ul id="rig">
<li>
<a class="rig-cell">
<?php echo '<img src="data:image/jpeg;base64,' . base64_encode( $row['img'] ) . '" align="middle" height=50% " />'; ?>
<span class="rig-overlay"></span>
<span class="rig-text"> <?php echo $row['img_name']."<br>"; ?></span>
</a>
<form method="POST" action="" class="radiowrapper" >
<input class="like" type="submit" name="problem" value="<?php echo $row['img_id']; ?>" id="name_<?php echo $row['img_name']; ?>">
</form>
</li>
</ul>
<?php
if (isset ($_POST['problem']))
{
echo $sql = "UPDATE staff.image SET likes='".$row['likes']."'+1 WHERE img_id='".$row['img_id']."'";
}
}
?>
I have another file that lets the user upload the image of his choice, and writes a name for it, and saves it in staff.image. here some screenshots
I don't really understand the problem and I've been trying different ways to write the UPDATE function but to no avail. if I'm unclear on something r you require more details I'll post it right away.
Thanks in advance !
You're wondering why it's echoing the query?
Simple, you told it to:
if (isset ($_POST['problem']))
{
echo $sql = "UPDATE staff.image SET likes='".$row['likes']."'+1 WHERE img_id='".$row['img_id']."'";
^^^^
}
Plus, you never executed the query.
So,
//added this part after the while loop
if (isset ($_POST['problem']))
{
$sql = mysqli_query($conn, "UPDATE staff.image SET likes=likes+1 WHERE img_id='".$_POST['problem']."'");
if($sql){
echo "Success";
}
else {
echo "<i>Houston, we have a problem:</i> " . mysqli_error($conn);
}
}
Use mysqli_affected_rows() for truthness.
I am trying to use the function mysqli_fetch_field() to get the name of each of my tables in the database. However when i try to output the table name using $fieldInfo->table i get duplicates. How can i select only 1 column from each table so that $fieldInfo->table isnt called for every column of each table?
current sql:
$sql = "SELECT * from administrators, bookings, customers, rooms";
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error($conn));
my code to display the table name in radio buttons:
<?php
while ($fieldInfo = mysqli_fetch_field($results)) {
?>
<input type="radio" name="tableNames" value="<?php echo $fieldInfo->table; ?>"> <?php echo $fieldInfo->table ?> <br>
<?php } ?>
I added 2 temporary table name holder and made an IF condition that only outputs the radio buttons once the 2 temporary name holders are different.
<?php
$tempName2 = "";
while ($fieldInfo = mysqli_fetch_field($results)) {
$tempName = $fieldInfo->table;
if ($tempName != $tempName2) {
$tempName2 = $tempName;
?>
<input type="radio" name="tableNames" value="<?php echo $tempName; ?>" > <?php echo $tempName ?> <br>
<?php }
} ?>
<?php
$query='SHOW TABLES FROM DB_NAME';
$results=mysqli_query($conn,$query);
while ($fieldInfo = mysqli_fetch_array($results)) { ?>
<input type="radio" name="tableNames" value="<?php echo $fieldInfo[0]; ?>"> <?php echo $fieldInfo[0]; ?> <br>
<?php } ?>
I have written code to retrieve all the images from database for a specific city, and I want to be able to delete a specific image or to change the caption.
The problem is:
the code always work on the last image only!
I hope you guys will be able to help me with this problem.
Retrieve code:
<?php
$City_name=$_REQUEST['id'];
$Image_query = "SELECT * FROM image where City_name ='".$City_name."' ";
$Image_result = mysqli_query($dbcon,$Image_query);
echo "<table>";
while ($row = mysqli_fetch_array($Image_result))
{
$image_id = $row['Image_id'];
$image = $row['Image_url'];
$Caption = $row['Caption'];
echo "<tr style='float:right;'>";
echo "<td>"; ?> <img src="<?php echo $image ; ?>"/> <br>
<input type="text" name="caption" value="<?php echo $Caption ;?>" />
<br> <input name="delete" type="submit" value="Delete picture" />
<br> <input name="Update_caption" type="submit" value="change caption" />
<?php echo "</td>";
echo "<td>"; ?> <input class="input-image" type="hidden" name="id" value="<?php echo $image_id ;?>" />
<?php echo "</td>";
} /* End of while loop */
echo "</tr>";
echo"</table>";
?>
Update code :
if (isset($_POST['Update_caption'])) {
$ImageID = $_POST['id'];
$ImageCaption = $_POST['caption'];
$sql = mysqli_query ($dbcon,"UPDATE `image` SET `Caption`='".$ImageCaption."' WHERE `Image_id`='".$ImageID."' ");
if ($sql) {
echo "done";
} else { echo "error"; }
}
Delete code :
if (isset($_POST['delete'])) {
$ImageID = $_POST['id'];
$sql = mysqli_query ($dbcon,"DELETE FROM `image` where `Image_id` = '".$ImageID."' ");
if ($sql) {
echo "done";
} else { echo "error"; }
}
$_POST['id'] (sql injection alert!) contains the contents of the input element that has a name attribute id.
You are echoing out your input elements in a loop, all with the same name so the last one will overwrite all the previous ones.
You should use an array like for example:
<input class="input-image" type="hidden" name="id[<?php echo $image_id ;?>]" value="<?php echo $image_id ;?>" />
So that your $_POST['id'] is an array containing all elements.
The same applies to other input elements like the caption.
An alternative, especially for your delete option, would be to wrap every image in its own form. But keep in mind that you will need valid html for that to work, you can't have a form that opens in a row element and spans different columns.
And note that you should really use a prepared statement to close the sql injection hole you have now.
I am currently displaying the data using a html table in php from mysql database, and i also i am allowing the user to delete only their own data from the table,my problem is how to match the delete button with the respected row,when user clicks the delete buttons only the specified row should be deleted, but it deletes all the records which is connected to the user in the database, please help me how to do this, PS i am a learner and new to php
UPDATED CODE GOES HERE
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>View cart-d2dn</title>
</head>
<body>
<?php
include('header.php'); ?>
<h1>View Cart</h1>
<table border='1'>
<tr>
<th> VIN </th>
<th> Vehicle Description </th>
<th> Price </th>
</tr>
<?php
session_start();
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT vin,description,price FROM products where user_id='".$_SESSION['use_i']."' ";
$result = mysqli_query($conn, $sql);
$uq=mysql_query("select * from td_user where user_id='".$_SESSION['use_i']."' ");
$u_row=mysql_fetch_array($uq);
if(isset($_REQUEST['delete']))
{
$sql_s =" DELETE FROM `products` WHERE user_id='".$u_row['user_id']."' AND vin='".$_REQUEST['vin']."' " ;
$result_s = mysqli_query($conn,$sql_s) ;
if($result_s == true)
{
echo '<script language="javascript">';
echo 'alert("Deleted successfully")';
echo '</script>';
}
else
{
echo '<script language="javascript">';
echo 'alert("Error in deletion")';
echo '</script>';
}
}
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<tr>
<td>'.$row['vin'].'</td>
<td>'.$row['description'].'</td>
<td>'.$row['price'].' </td>
<td> <form method="post"> <input type="submit" name="delete" value="Delete">
<input type="hidden" name="vin" value="'.$row['vin'].'">
</form></td>
</tr>';
}
}
else
{
echo "Your cart is empty!";
}
?>
<?php
echo '</table>';
?>
<form><input type="button" value="Go back" onClick="window.location.href='automobile_list.php'">
<input type="button" value="Submit" onClick="window.location.href='mail.php'">
</form>
<?php
mysqli_close($conn);
?>
<?php
include('footer.php');
?>
</body>
</html>
You can do same only if your MySQL table have primary/unique key OR each row is different...
If VIN is unique then Let me show where you need to change. You need to SEND the unique key with delete request to detect which row selected to be deleted. Change the delete button code to:
<form method="post"> <input type="submit" name="delete" value="Delete">
<input type="hidden" name="vin" value="'.$row['vin'].'">
</form>
And in code of deleting row:
if(isset($_REQUEST['delete']))
{
$sql_s =" DELETE FROM `products` WHERE user_id='".$_SESSION['use_i']."' AND vin='".$_REQUEST['vin']."' ";
}
ALSO Delete the mysql code you are using to retrieve user ID (which is just before the code written above). [AND put this delete-code before displaying table(before selecting from product table-look at comments for more info :p )]
If vin is not the primary key then add primary in table by following mathed:
In mysql workbench: right click -> Alter table -> add column ID as INT and check the PK (primary key), AI (auto increment) -> apply -> finish.
Now use ID in place of VIN
As you said you are new to PHP. Then let me give a suggestion:
Use $_POST in place of $_REQUEST coz POST var contains data which sent by POST method only BUT REQUEST contains both POST & GET data... so anybody can delete via just typing in URL as ?delete=delete&vin=3
BTW, its not the issue here, but will help you in future.
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<tr id="<?php echo $row['id']; ?>" >
<td>'.$row['vin'].'</td>
<td>'.$row['description'].'</td>
<td>'.$row['price'].' </td>
<td> <form method="post"> <input type="submit" name="delete" value="Delete"></form> </td>
</tr>';
$vinrow =$row['vin'] ;
}
}