PHP rows send 1 mySQLi record to form for edit [duplicate] - php

I have searched all over this website, but not yet found the answer for this. Pr maybe I am not able to apply it correctly. I have a form that grabs all photos with a certain GALLERY_id attached to it. The backend user can then change the title of the photo and change the tags. After submitting the form the query should update all rows. Here is what I have so far which does not doe anyting:
THE FORM
if(isset($_GET['id']))
{
$id=$_GET['id'];
$result = $db->prepare("SELECT * FROM photos WHERE gallery_id = :gallery_id ");
$result->bindParam(':gallery_id', $id);
$result->execute();
echo '<form action="" method="POST">';
echo "<ul id='photos'>";
for ($i = 0; $row = $result->fetch(); $i++)
{
$id = $row['id'];
$title = $row['title'];
$tags = $row['tags'];
$src = $row['src'];
echo "<li><a class='lightbox' href='images/$src'><img src='images/$src' id='$id' alt='$title' /></a><br />";
echo "<input type='text' name='photo_title' value='$title' /><br />";
echo "<input type='text' name='photo_tags' value='$tags' />";
echo "<input type='hidden' name='photo_id' value='$id' />";
echo "</li>";
}
echo "</ul>";
}
?>
<div style="clear:both"></div>
<input type="submit" name="changeTitle" value="Save"/>
</form>
UPDATE QUERY
if (isset($_POST['changeTitle']))
{
foreach ($_POST as $p)
{
$id=$p['photo_id'];
$title=$p['photo_title'];
$tags=$p['photo_tags'];
$sql = "UPDATE photos SET title=?, tags=? WHERE id=?";
$query = $db->prepare($sql);
$query->execute(array($title, $tags, $id));
}
}

Since you have multiple html fields with same names, you have to submit them as an arrays:
echo "<input type='text' name='photo_title[]' value='$title' /><br />";
echo "<input type='text' name='photo_tags[]' value='$tags' />";
echo "<input type='hidden' name='photo_id[]' value='$id' />";
After submitted, loop through any array variable like
foreach ($_POST['photo_id'] as $key => $photo_id) {
$id = $photo_id;
$title = $_POST['photo_title'][$key];
$tags = $_POST['photo_tags'][$key];
$sql = "UPDATE photos SET title=?, tags=? WHERE id=?";
$query = $db->prepare($sql);
$query->execute(array($title, $tags, $id));
}

Related

Having issues updating an SQL table on submit with an HTML form

I am trying to create a function where a user can edit a preexisting post. When the user is taken to edit.php, they are presented with a form that shows them the existing data associated with that post. They can then make changes to any of the fields (description, category, add additional images, etc.) and, upon hitting a submit button, the updated information will show on the post page.
My issue with this is actually getting it to update the information. The form will show up with the preexisting info, and I can make changes to any of the fields. However, when I press submit, I am taken to the list of posts, yet the changes I made have not been updated in the SQL table.
There aren't any errors that are being returned upon hitting submit. Everything is running smoothly except for the fact things aren't actually being updated in the database.
I have been looking on several different sites for help on the matter, and I have tried several variations of my UPDATE query thinking that maybe I am calling it incorrectly. This is the iteration I am currently working with after attempting several other examples I found:
if($title && $price && $description && $category){
$editquery = "UPDATE post SET title='$title', price='$price', description='$description', category='$category' WHERE post_id='$id'";
$edquery = $db->prepare($editquery);
$edquery->bind_result("ssss", $title, $price, $description, $category);
$edquery->execute();
if($edquery){
echo "Updated!";
}else{
echo "error";
}
}else{
echo "missing data";
}
I am fairly new to PHP, so it is very possible that I am making simple syntax errors that I am not noticing. Or it could be some other portion of my code that I am not executing properly. If anyone could have a look at my code and help point me in the right direction, I would greatly appreciate it.
Also, I would like to add that yes, I know my code is vulnerable to injection. My only concern right now is getting this function to work. Any security measures I will deal with after getting this to work.
PHP
<?php
if(!isset($_GET['id'])){
header('Location: modify.php');
exit();
}else{
$id = $_GET['id'];
}
include('../includes/db_connect.php');
if(!is_numeric($id)){
header('Location: inventory.php');
}
if(isset($_POST['submit'])){
$title = $_POST['title'];
$price = $_POST['price'];
$description = $_POST['description'];
$category = $_POST['category'];
$title = $db->real_escape_string($title);
$price = $db->real_escape_string($price);
$description = $db->real_escape_string($description);
if($title && $price && $description && $category){
$editquery = "UPDATE post SET title='$title', price='$price', description='$description', category='$category' WHERE post_id='$id'";
$edquery = $db->prepare($editquery);
$edquery->bind_result("ssss", $title, $price, $description, $category);
$edquery->execute();
if($edquery){
echo "Updated!";
}else{
echo "error";
}
}else{
echo "missing data";
}
$postid = $db->insert_id;
for($i=0; $i<count($_FILES["images"]["name"]); $i++)
{
$filetmp = $_FILES["images"]["tmp_name"][$i];
$filename = $_FILES["images"]["name"][$i];
$filetype = $_FILES["images"]["type"][$i];
$filepath = "images/".$filename;
move_uploaded_file($filetmp, $filepath);
$sql = "INSERT INTO images (img_name, img_path, img_type, post_id) VALUES
('$filename', '$filepath', '$filetype', '$postid')";
$result = mysqli_query($db, $sql);
}
}
?>
The HTML form This is the only portion of the HTML that pertains to this function.
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST" enctype="multipart/form-data">
<?php
$editsql = "SELECT * FROM post INNER JOIN categories ON categories.category_id=post.category_id WHERE post_id=' ".$id." '";
$editquery = $db->query($editsql);
if($editquery->num_rows !=1){
header('Location: inventory.php');
exit();
}
$editrow = $editquery->fetch_object();
echo "<div class='form-group'>";
echo "<label>Title*</label>";
echo "<input type='text' name='title' class='form-control' value='".$editrow->title."' required>";
echo "</div>";
echo "<div class='form-group'>";
echo "<label>Price*</label>";
echo "<input type='text' name='price' class='form-control' value='".$editrow->price."'required>";
echo "</div>";
echo "<div class='form-group'>";
echo "<label>Category</label>";
echo "<select name='category' class='form-control'>";
echo "<option value='".$editrow->category_id."'>".$editrow->category."</option>";
$catquery = $db->query("SELECT * FROM categories");
while($row = $catquery->fetch_object()){
echo "<option value='".$row->category_id."'>".$row->category."</option>";
}
echo "</select>";
echo "</div>";
echo "<div class='form-group'>";
echo "<label>Description*</label>";
echo "<textarea type='textarea' name='description' class='form-control' required>".$editrow->description."</textarea>";
echo "</div>";
echo "<div class='form-group'>";
echo "<label>Image(s)</label>";
echo "<input type='hidden' name='size' value='1000000'>";
echo "<input multiple='multiple' name='images[]' type='file'/>";
echo "</div>";
echo "<div class='required'>";
echo "* indicates a required field";
echo "</div>";
echo "<button type='submit' name='submit' value='submit' class='btn btn-default'>EDIT POST</button>"
?>
</form>
EDIT
Whatever is happening with my code, I am unable to see any of the echoed statements after I press 'submit':
if($query){
echo "product updated";
}else{
echo "error";
}
}else{
echo "missing data";
}
Could it be possible that this is causing an issue?
if(!isset($_GET['id'])){
header('Location: modify.php');
exit();
}else{
$id = $_GET['id'];
}
Or that I need to use a hidden input along with this?
echo "<button type='submit' name='submit' value='submit' class='btn btn-default'>EDIT POST</button>"
EDIT 2
I've separated this into two files (edit.php and submitedit.php) to keep the $_GET and $_POST separated from one another. However, I am still experiencing the same issue where the database will not update.
edit.php I'm only showing the PHP and relevant HTML form
<?php
session_start();
$msg = "";
if(!isset($_GET['id'])){
header('Location: delete.php');
exit();
}else{
$id = $_GET['id'];
}
include('../includes/db_connect.php');
if (!isset($_SESSION['user_id'])) {
header('Location: login.php');
exit();
}
if(!is_numeric($id)){
header('Location: inventory.php');
}
?>
<!-- WHERE THE HTML STARTS -->
<form action="submitedit.php" method="POST" enctype="multipart/form-data">
<?php
$editsql = "SELECT * FROM post INNER JOIN categories ON categories.category_id=post.category_id WHERE post_id='$id'";
$editquery = $db->query($editsql);
if($editquery->num_rows !=1){
header('Location: inventory.php');
exit();
}
$editrow = $editquery->fetch_object();
echo "<div class='form-group'>";
echo "<label>Title*</label>";
echo "<input type='text' name='title' class='form-control' value='".$editrow->title."' required>";
echo "</div>";
echo "<div class='form-group'>";
echo "<label>Price*</label>";
echo "<input type='text' name='price' class='form-control' value='".$editrow->price."'required>";
echo "</div>";
echo "<div class='form-group'>";
echo "<label>Category</label>";
echo "<select name='category' class='form-control'>";
echo "<option value='".$editrow->category_id."'>".$editrow->category."</option>";
$catquery = $db->query("SELECT * FROM categories");
while($row = $catquery->fetch_object()){
echo "<option value='".$row->category_id."'>".$row->category."</option>";
}
echo "</select>";
echo "</div>";
echo "<div class='form-group'>";
echo "<label>Description*</label>";
echo "<textarea type='textarea' name='description' class='form-control' required>".$editrow->description."</textarea>";
echo "</div>";
echo "<div class='form-group'>";
echo "<label>Image(s)</label>";
echo "<input type='hidden' name='size' value='1000000'>";
echo "<input multiple='multiple' name='images[]' type='file'/>";
echo "</div>";
echo "<div class='required'>";
echo "* indicates a required field";
echo "</div>";
echo "<button type='submit' name='submit' value='submit' class='btn btn-default'>EDIT POST</button>"
?>
</form>
submitedit.php
<?php
if(!isset($_POST['id'])){
header('Location: delete.php');
exit();
}else{
$id = $_POST['id'];
include('../includes/db_connect.php');
if(isset($_POST['submit'])){
$title = $_POST['title'];
$price = $_POST['price'];
$description = $_POST['description'];
$category = $_POST['category'];
$title = $db->real_escape_string($title);
$price = $db->real_escape_string($price);
$description = $db->real_escape_string($description);
if($title && $price && $description && $category){
$editquery = "UPDATE post SET title='$title', price='$price', description='$description', category='$category' WHERE post_id='$id'";
$edquery = $db->prepare($editquery);
$edquery->bind_result("ssss", $title, $price, $description, $category);
$edquery->execute();
if($edquery){
echo "Updated!";
}else{
echo "error";
}
}else{
echo "missing data";
}
$postid = $db->insert_id;
for($i=0; $i<count($_FILES["images"]["name"]); $i++)
{
$filetmp = $_FILES["images"]["tmp_name"][$i];
$filename = $_FILES["images"]["name"][$i];
$filetype = $_FILES["images"]["type"][$i];
$filepath = "images/".$filename;
move_uploaded_file($filetmp, $filepath);
$sql = "INSERT INTO images (img_name, img_path, img_type, post_id) VALUES ('$filename', '$filepath', '$filetype', '$postid')";
$result = mysqli_query($db, $sql);
}
}
?>
You send your form with POST method while you try to read id from GET array. Change it to $_POST['id'], and you're all set

How do I create an edit-option for each row in a table?

I am using the following code to display certain rows from my database table:
<?php
$searchtype=$_POST['searchtype'];
$searchterm=$_POST['searchterm'];
$searchterm= trim($searchterm);
if (!$searchtype || !$searchterm)
{
echo 'Error';
exit;
}
if (!get_magic_quotes_gpc())
{
$searchtype = addslashes($searchtype);
$searchterm = addslashes($searchterm);
}
$db = include "connect2db.php";
$query = "select * from notes where ".$searchtype." like '%".$searchterm."%'";
$result = $db->query($query);
$num_results = $result->num_rows;
echo '<p>Number of rows found: '.$num_results.'</p>';
for ($i=0; $i <$num_results; $i++)
{
$row = $result->fetch_assoc();
echo '<i>';
echo stripslashes($row['date']);
echo '</i><br /> ';
echo '<b>';
echo stripslashes($row['notetitle']);
echo '</b><br /> ';
echo stripslashes($row['note']);
echo '<br /><br /> ';
echo '</p>';
}
$result->free();
$db->close();
?>
Now I would like to display an edit-link for each row displayed, that can open a new page in which it is possible to edit a specific row. I already have the code that lets you edit the row:
<?php
if ($_REQUEST['save']=="Save") { // is data submitted?
// create variables
$noteid = $_REQUEST['noteid'];
$coursename = $_REQUEST['coursename'];
$notetitle = $_REQUEST['notetitle'];
$note = $_REQUEST['note'];
$query = "UPDATE notes SET ";
$query .= "coursename='$coursename', ";
$query .= "notetitle='$notetitle', ";
$query .= "note='$note' ";
$query .= "WHERE noteid='$noteid'";
$result = $db->query($query);
} elseif ($_REQUEST['delete']=="Delete") { // is data to be removed?
$noteid = $_REQUEST['noteid'];
$query="DELETE FROM notes WHERE noteid='$noteid'";
$result = $db->query($query);
}
?>
<div class="formular">
<div class="row1">
<p>Id</p>
<p>Notetitle</p>
<p>Note</p>
</div>
<?php
$query = "SELECT * FROM notes ORDER BY noteid DESC";
$result = $db->query($query);
while ($row = mysqli_fetch_array($result)) {
echo "<form ".$_SERVER['PHP_SELF']." name='edit-form' method='post' class='row1'>\n";
echo "<p class='align_top padding_top'>".$row['noteid']."<input type='hidden' name='noteid' value='".$row['noteid']."' /></p>\n";
echo "<p class='align_top'><input type='text' name='notetitle' value='".$row['notetitle']."' /></p>\n";
echo "<p><textarea name='note' rows='10' cols='50'>".$row['note']."</textarea></p>\n";
echo "<p><input type='submit' name='save' value='Save' /></p>";
echo "<p><input type='submit' name='delete' value='Delete' /></p>";
echo "</form>\n";
}
echo '</div>';
$result->free();
$db->close();
?>
What I am struggling with is how to display an edit-link for each row that lets you open a page where you can edit/delete the content of only that row.
I hope someone can help, I am very new at this.
Thank you!
Add a button next to each row that opens an edit page (or modal) with the id inside, example: <button onclick="edit('randomId')">Edit RandomId </button>
You could implement something different that accepts the unique id of that specific row and open a new page or modal with it.

Post form and update multiple rows with mysql

I have searched all over this website, but not yet found the answer for this. Pr maybe I am not able to apply it correctly. I have a form that grabs all photos with a certain GALLERY_id attached to it. The backend user can then change the title of the photo and change the tags. After submitting the form the query should update all rows. Here is what I have so far which does not doe anyting:
THE FORM
if(isset($_GET['id']))
{
$id=$_GET['id'];
$result = $db->prepare("SELECT * FROM photos WHERE gallery_id = :gallery_id ");
$result->bindParam(':gallery_id', $id);
$result->execute();
echo '<form action="" method="POST">';
echo "<ul id='photos'>";
for ($i = 0; $row = $result->fetch(); $i++)
{
$id = $row['id'];
$title = $row['title'];
$tags = $row['tags'];
$src = $row['src'];
echo "<li><a class='lightbox' href='images/$src'><img src='images/$src' id='$id' alt='$title' /></a><br />";
echo "<input type='text' name='photo_title' value='$title' /><br />";
echo "<input type='text' name='photo_tags' value='$tags' />";
echo "<input type='hidden' name='photo_id' value='$id' />";
echo "</li>";
}
echo "</ul>";
}
?>
<div style="clear:both"></div>
<input type="submit" name="changeTitle" value="Save"/>
</form>
UPDATE QUERY
if (isset($_POST['changeTitle']))
{
foreach ($_POST as $p)
{
$id=$p['photo_id'];
$title=$p['photo_title'];
$tags=$p['photo_tags'];
$sql = "UPDATE photos SET title=?, tags=? WHERE id=?";
$query = $db->prepare($sql);
$query->execute(array($title, $tags, $id));
}
}
Since you have multiple html fields with same names, you have to submit them as an arrays:
echo "<input type='text' name='photo_title[]' value='$title' /><br />";
echo "<input type='text' name='photo_tags[]' value='$tags' />";
echo "<input type='hidden' name='photo_id[]' value='$id' />";
After submitted, loop through any array variable like
foreach ($_POST['photo_id'] as $key => $photo_id) {
$id = $photo_id;
$title = $_POST['photo_title'][$key];
$tags = $_POST['photo_tags'][$key];
$sql = "UPDATE photos SET title=?, tags=? WHERE id=?";
$query = $db->prepare($sql);
$query->execute(array($title, $tags, $id));
}

How to fetch $POST data and put in database

Hi i have a simple form that uploads files and i want to get the id value using $POST and put in the database but my code is incorrect. Here is my code. I just want to ask if im doing the passing and fetching of $POST correctly? thanks
echo "<form action='process.php' method='post' enctype='multipart/form-data' id='uploadfile'>";
echo "<input type='hidden' name='MAX_FILE_SIZE' value='100000' />";
echo "<select name='selectedValue'>";
echo '<option selected="selected">' .'Choose a User'. '</option>';
foreach ($registeredUsers as $key => $value) {
$registered = JFactory::getUser($value);
echo '<option name="id" value="'.$registered->id.'">'.$registered->name.'</option>';
}
echo "</select>";
echo "Choose a file to Upload:";
echo "<input name='uploadedfile' type='file' /> <br/>";
echo '<input type="submit" name="submit" value="Upload">';
echo "</form>";
Here is the process.php file.
if(isset($_POST['selectedValue']))
{
$selectedValue = $_POST['id'];
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query = "INSERT INTO sample_table ('user_id') VALUES ('$_POST[id]')"
$db->setQuery($query);
$result = $db->execute();
}
echo "<form action='process.php' method='post' enctype='multipart/form-data' id='uploadfile'>";
echo "<input type='hidden' name='MAX_FILE_SIZE' value='100000' />";
echo "<select name='id'>";
echo '<option selected="selected">' .'Choose a User'. '</option>';
foreach ($registeredUsers as $key => $value) {
$registered = JFactory::getUser($value);
echo '<option value="'.$registered->id.'">'.$registered->name.'</option>';
}
echo "</select>";
echo "Choose a file to Upload:";
echo "<input name='uploadedfile' type='file' /> <br/>";
echo '<input type="submit" name="submit" value="Upload">';
echo "</form>";
process.php
if(isset($_POST['id']))
{
$selectedValue = $_POST['id'];
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query = "INSERT INTO sample_table ('user_id') VALUES ('$selectedValue')";
$db->setQuery($query);
$result = $db->execute();
}
Okay. So you had some problems, you've set the "name" on the options, which is wrong, you have to set that on the .
Second, you missed a semicolon at the end on $query.
And last, i've chaged to check if the a value has been chosed from the dropdown and to set selectedValue to that, and use that in the query.

PHP - Button to delete Item from MySQL

I am coding some video upload script and I am with the admin panel right now.
There I have a List with all Videos. And each video has one delete button on the right side.
When I click the button then this video should be deleted from database but its not working after I click the button nothing happens.
<?php
$query = mysql_query("SELECT * FROM `videos`");
while($row = mysql_fetch_assoc($query))
{
$id = $row['id'];
$name = $row['name'];
echo "<a href='watch.php?id=$id'>$name</a><br />
<input type='submit' name='remove' value='Delete'<br />";
}
if (isset($_POST['remove']))
{
foreach ($_POST['id'] as $the_id)
{
if (!mysql_query("DELETE FROM videos WHERE id = '$the_id'"))
{
echo mysql_error();
}
}
}
?>
Of course on the header I have the mysql connect query. This is just the php code for listing all videos and try to delete.
Here is an example of doing this with MySQLi, including binding parameters to avoid SQL injection -
if (isset($_POST['remove'])) {
$remove = $mysqli->prepare("DELETE FROM `videos` WHERE `id` = ?");
$vid_id = $_POST['vid_id'];
$remove->bind_param('s', $vid_id);
if(!$remove->execute() === true) {
echo $mysqli->error;
}
}
$query = "SELECT * FROM `videos`";
if ($result = $mysqli->query($query)) {
while($row = $result->fetch_object()){
$id = $row->id;
$name = $row->name;
echo "<a href='watch.php?id=$id'>$name</a><br />";
echo "<form name='delete_vid' method='post'>";
echo "<input type='hidden' name='vid_id' value='$id'>";
echo "<input type='submit' name='remove' value='Delete'<br />";
echo "</form>";
}
} else {
echo mysqli_error($connection);
}
$result->close();
Of course you will have to provide a $connection` to the database, but thsi should get you started not only with MySQLi but with adding a form for each video.
More on SQL Injection
Maybe the problem is in the html, each delete button must be in and independent form, with a hidden input with the id too.
echo "<a href='watch.php?id=$id'>$name</a><br />
<form method='post'><input type='hidden' value='$id'><input type='submit' name='remove' value='Delete'<br /></form>";
<form method="post" >
<?php
$query = mysql_query("SELECT * FROM `videos`");
while($row = mysql_fetch_assoc($query))
{
$id = $row['id'];
$name = $row['name'];
echo "<a href='watch.php?id=$id'>$name</a><br />
<button name='id' value='".$id."' type='submit' >Delete</button>
<br />";
}
if (!mysql_query("DELETE FROM videos WHERE id = '".$_POST['id']."'"))
{
echo mysql_error();
} else {
echo 'successfully deleted';
}
?>
</form>

Categories