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

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.

Related

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

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));
}

Session variable and Dynamic Pagination in php

<form action='movies.php' method='POST'>
Language: <select name="language">
<option selected>hindi</option>
<?php
require("config.php");
$result="SELECT language FROM movies";
$q = mysqli_query($conn,$result) or die(mysql_error());
while ($row=mysqli_fetch_array($q)) {
$s1=$row["language"];
echo "<option>
$s1
</option>";
}
echo "<br>"
?>
</select>
<br /> <br />
<input type='submit' value='Submit' />
</form>
<?php
$lang=#$_POST['language'];
$_SESSION["lang1"]=$lang;
/*
if($lang){
$sql = "SELECT name,language FROM movies WHERE language='$lang'";
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows($result)>0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<div class="query"> <img src="images\tiles\bb.jpg"> ';
echo "<h3> " . $row["name"]."</h3>". "<br>";
echo "</div>";
}
} else {
echo "0 results";
}
}
*/
$page=#$_GET['page'];
if($page==""|| $page=="1")
{
$page1=0;
}
else{
$page1=($page*3)-3;
}
$sql = "SELECT name,language FROM movies WHERE language='". $_SESSION['lang1']."' limit $page1,3 ";
$result = mysqli_query($conn,$sql);
$a= mysqli_num_rows($result);
while ($list=mysqli_fetch_array($result))
{
echo $list['name'] . " : " . $list['language'] . "<br />";
}
$sql = "SELECT name,language FROM movies WHERE language='$lang'";
$result = mysqli_query($conn,$sql);
$a= mysqli_num_rows($result);
$numrows=$a;
$rowsperpage=3;
$totalpages= ceil($numrows/$rowsperpage);
echo "</br>";
for($b=1;$b<=$totalpages;$b++)
{
?><?php echo $b." ";?> <?php
}
?>
I get proper output on movies.php which is the first 3 rows from database,but when i click on the dynamically created pagination link like movies.php?page=2 then there is no output on this page.This code works fine if i manually set the
$_SESSION["lang1"]="English"; then i get proper output but when i take input from the form it doesnt work.

Updating database using php

This code looks horrible and I know. I don't know how to fix it though. When I try and update the table using the edit web page, only the first row in the first column updates but the subtitle is not updating in the second column, first row. Is there a way to change this? Sorry for the terrible explanation.
Update Page
//Home Title
$homeTitleUpdate = $_POST["homeTitleChange"];
$editRow = $_POST["rowID"];
$query = " UPDATE Home SET title = '$homeTitleUpdate' WHERE homeID = '$editRow' ";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if ($result) {
echo "<p> - Title updated succesfully to $homeTitleUpdate.</p>";
} else {
echo "<p> - Title did not update. Something went wrong</p>";
}
//Home Subtitle
$homeSubtitleUpdate = $_POST["homeSubtitleChange"];
$query1 = " UPDATE Home SET subtitle = '$homeSubtitleUpdate' ";
$result1 = mysqli_query($conn, $query) or die(mysqli_error($conn));
if ($result) {
echo "<p> - Subtitle updated successfully to $homeSubtitleUpdate.</p>";
} else {
echo "<p> - Subtitle did not update. Something went wrong</p>";
}
Edit Page
<?php
echo "<h2 style='color:black'>";
echo "<input type'text' name='homeTitleChange' value=$homeTitle>";
echo "<input type='hidden' name='rowID' value=$getID>";
echo "</h2>";
echo "<h4 style='color:black'>";
echo "<input type'text' name='homeSubtitleChange' value=$homeSubtitle>";
echo "<input type='hidden' name='rowID' value=$getID>";
echo "</h4>";
?>
<input type="submit" value="save" />
<?php
echo "<h2 style='color:black'>";
echo "<form action="change to your file" method="post">
echo "<input type'text' name='homeTitleChange' value=$homeTitle>";
echo "<input type='hidden' name='rowID' value=$getID>";
echo "</h2>";
echo "<h4 style='color:black'>";
echo "<input type'text' name='homeSubtitleChange' value=$homeSubtitle>";
echo "<input type='hidden' name='rowID' value=$getID>";
echo "</h4>";
?>
<input type="submit" name="submit" value="save" />
</form>
You did not have a form
//Home Title
if(isset($_POST['submit'])){
if
(
!empty($_POST["homeTitleChange"])
&&
!empty($_POST["homeSubtitleChange"]) &&
!empty($_POST["rowID"])
)
{
$homeTitleUpdate = $_POST["homeTitleChange"];
$homeSubtitleUpdate = $_POST["homeSubtitleChange"];
$editRow = $_POST["rowID"];
$query = "UPDATE Home SET title = '$homeTitleUpdate', subtitle ='$homeSubtitleUpdate' WHERE homeID = '$editRow' ";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if ($result) {
echo "<p> - Title/Subtitle updated succesfully to $homeTitleUpdate.</p>";
} else {
echo "<p> - Title/Subtitle did not update. Something went wrong</p>";
}
}
}
You can change your php and do it all within one query
You need to add 'where' condition while updating subtitle as well
$query1 = " UPDATE Home SET subtitle = '$homeSubtitleUpdate' WHERE homeID = '$editRow' ";
on other hand, you can update both of them in single query, like this
$query = " UPDATE Home
SET title = '$homeTitleUpdate', subtitle = '$homeSubtitleUpdate'
WHERE homeID = '$editRow' ";
wouldn't this be better? unless you have some specific reason

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>

Search Data not outputting the correct results

This form is a search form which allows the user to search for an event using the Venue and category fields which are scripted as dropdown boxes and the Price and event title as user input text boxes, as shown via the code if a keyword is entered which matches the fields on the database it should output all the related information for that event if any matches have been made on either search fields, the tickboxes allow the user to identify what criteria they would like to search with, if the tickbox field hasn't been checked then the SQL enquiry will not search for keywords with that corresponding field.
The issue is, it all seems to work fine except no results seem to show up for the Venue and Category fields if they was solely used to search for an event. But if I choose another field everything is outputting correctly including the venue and Category field.
DATABASE: http://i.imgur.com/d4uoXtE.jpg
HTML FORM
<form name="searchform" action ="PHP/searchfunction.php" method = "post" >
<h2>Event Search:</h2>
Use the Check Boxes to indicate which fields you watch to search with
<br /><br />
<h2>Search by Venue:</h2>
<?php
echo "<select name = 'venueName'>";
$queryresult2 = mysql_query($sql2) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult2)) {
echo "\n";
$venueID = $row['venueID'];
$venueName = $row['venueName'];
echo "<option value ='$venueName'";
echo ">$venueName</option>";
}# when the option selected matches the queryresult it will echo this
echo "</select>";
echo" <input type='checkbox' name='S_venueName'>";
mysql_free_result($queryresult2);
mysql_close($conn);
?>
<br /><br />
<h2>Search by Category:</h2>
<?php
include 'PHP/database_conn.php';
$sql3 ="SELECT catID, catDesc
FROM te_category";
echo "<select name = 'catdesc'>";
$queryresult3 = mysql_query($sql3) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult3)) {
echo "\n";
$catID = $row['catID'];
$catDesc = $row['catDesc'];
echo "<option value = '$catDesc'";
echo ">$catDesc </option>";
}
echo "</select>";
mysql_free_result($queryresult3);
mysql_close($conn);
?>
<input type="checkbox" name="S_catDes">
<br /><br />
<h2>Search By Price</h2>
<input type="text" name="S_price" />
<input type="checkbox" name="S_CheckPrice">
<br /><br />
<h2>Search By Event title</h2>
<input type="text" name="S_EventT" />
<input type="checkbox" name="S_EventTitle">
<br /><br />
<input name="update" type="submit" id="update" value="Search">
</form>
PHP CODE THAT DEALS WITH PROCESSING THE FORM DATA
<?php
include 'database_conn.php';
$venuename = $_POST['venueName']; //this is an integer
$catdesc = $_POST['catdesc']; //this is a string
$Price = $_POST['S_price'];
$EventT = $_POST['S_EventT'];
#the IF statements state if the tickbox is checked then search with these enquires
if (isset($_POST['S_VenueName'])) {
$sql = "SELECT * FROM te_venue WHERE venueName= '$venuename'";
}
if (isset($_POST['S_catDes'])) {
$sql = "SELECT * FROM te_category WHERE catID= '$catdesc'";
}
if (isset($_POST['S_CheckPrice'])) {
$sql = "SELECT * FROM te_events WHERE (eventPrice LIKE '%$Price%')";
}
if (isset($_POST['S_EventTitle'])) {
$sql = "SELECT * FROM te_events WHERE (eventTitle LIKE '%$EventT%')";
}
$queryresult = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult))
{
echo "Event Title: "; echo $row['eventTitle'];
echo "<br />";
echo "Event Description: "; echo $row['eventDescription'];
echo "<br />";
echo "Event Venue "; echo "$venuename";
echo "<br />";
echo "Event Category "; echo "$catdesc";
echo "<br />";
echo "Event Start Date "; echo $row['eventStartDate'];
echo "<br />";
echo "Event End Date "; echo $row['eventEndDate'];
echo "<br />";
echo "Event Price "; echo $row['eventPrice'];
echo "<br /><br />";
}
mysql_free_result($queryresult);
mysql_close($conn);
?>
Try using atleast MySQLi instead of deprecated MySQL. You can try this:
database_conn.php:
<?php
/* ESTABLISH YOUR CONNECTION. REPLACE THE NECESSARY DATA BELOW */
$con=mysqli_connect("YourHost","YourUsername","YourPassword","YourDatabase");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
?>
HTML Form:
<html>
<body>
<?php
include 'PHP/database_conn.php';
$sql2="SELECT venueID, venueName FROM te_venue"; /* PLEASE REPLACE THE NECESSARY DATA */
echo "<select name = 'venueName'>";
$queryresult2 = mysqli_query($con,$sql2);
while($row = mysqli_fetch_array($queryresult2)) {
echo "\n";
$venueID = mysqli_real_escape_string($con,$row['venueID']);
$venueName = mysqli_real_escape_string($con,$row['venueName']);
echo "<option value ='$venueName'>";
echo $venueName."</option>";
} /* when the option selected matches the queryresult it will echo this ?? */
echo "</select>";
echo "<input type='checkbox' name='S_venueName'>";
?>
<br><br>
<h2>Search by Category:</h2>
<?php
$sql3 ="SELECT catID, catDesc FROM te_category";
echo "<select name = 'catdesc'>";
$queryresult3 = mysqli_query($con,$sql3);
while($row = mysqli_fetch_array($queryresult3)) {
echo "\n";
$catID = mysqli_real_escape_string($con,$row['catID']);
$catDesc = mysqli_real_escape_string($con,$row['catDesc']);
echo "<option value = '$catDesc'>";
echo $catDesc."</option>";
}
echo "</select>";
?>
<input type="checkbox" name="S_catDes">
<br><br>
<h2>Search By Price</h2>
<input type="text" name="S_price" />
<input type="checkbox" name="S_CheckPrice">
<br><br>
<h2>Search By Event title</h2>
<input type="text" name="S_EventT" />
<input type="checkbox" name="S_EventTitle">
<br><br>
<input name="update" type="submit" id="update" value="Search">
</form>
</body>
</html>
PHP:
<?php
include 'database_conn.php';
$venuename = mysqli_real_escape_string($con,$_POST['venueName']); /* this is an integer */
$catdesc = mysqli_real_escape_string($con,$_POST['catdesc']); /* this is a string */
$Price = mysqli_real_escape_string($con,$_POST['S_price']);
$EventT = mysqli_real_escape_string($con,$_POST['S_EventT']);
/* SHOULD PRACTICE USING ESCAPE_STRING TO PREVENT SOME OF SQL INJECTIONS */
/* the IF statements state if the tickbox is checked then search with these enquires */
if (isset($_POST['S_VenueName'])) {
$sql = "SELECT * FROM te_venue WHERE venueName= '$venuename'";
}
if (isset($_POST['S_catDes'])) {
$sql = "SELECT * FROM te_category WHERE catID= '$catdesc'";
}
if (isset($_POST['S_CheckPrice'])) {
$sql = "SELECT * FROM te_events WHERE (eventPrice LIKE '%$Price%')";
}
if (isset($_POST['S_EventTitle'])) {
$sql = "SELECT * FROM te_events WHERE (eventTitle LIKE '%$EventT%')";
}
$queryresult = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($queryresult))
{
echo "Event Title: "; echo $row['eventTitle'];
echo "<br />";
echo "Event Description: "; echo $row['eventDescription'];
echo "<br />";
echo "Event Venue "; echo "$venuename";
echo "<br />";
echo "Event Category "; echo "$catdesc";
echo "<br />";
echo "Event Start Date "; echo $row['eventStartDate'];
echo "<br />";
echo "Event End Date "; echo $row['eventEndDate'];
echo "<br />";
echo "Event Price "; echo $row['eventPrice'];
echo "<br /><br />";
}
mysqli_close($conn);
?>
What if user checks all the check box? What would happen is, the last condition will be used. The first three conditions will be overwritten by the last condition.
If you use ELSE IF in those conditions, the first condition will be implemented.
My advice is to use radio button instead of check box and hope you gets the idea along the way.
Have you tried printing out your $sql query for debugging?
Try <input type="checkbox" name="S_catDes" value="checked">.
From memory checkboxes need a value field but I could be wrong. Hope this helps.

Categories