show single entry on a new page with sending id of row - php

i am very novice to php and mysqli and found a great tutorial but am needing some help.
i am wanting a row to be linkable and send it to another page named single.php?id=ROWID so it will show the single entry
this is what i got so far.
<html>
<head>
<title>MySQLi Tutorial</title>
</head>
<body>
<?php
//include database connection
include 'db_connect.php';
$action = isset($_GET['action']) ? $_GET['action'] : "";
if($action=='delete'){ //if the user clicked ok, run our delete query
$query = "DELETE FROM users WHERE id = ".$mysqli->real_escape_string($_GET['id'])."";
if( $mysqli->query($query) ){
echo "User was deleted.";
}else{
echo "Database Error: Unable to delete record.";
}
}
$query = "select * from users";
$result = $mysqli->query( $query );
$num_results = $result->num_rows;
echo "<div><a href='add.php'>Create New Record</a></div>";
if( $num_results ){
echo "<table border='1'>";//start table
//creating our table heading
echo "<tr>";
echo "<th><a href=\"single.php?id={$id}\">Firstname</></th>";
echo "<th>Lastname</th>";
echo "<th>Username</th>";
echo "<th>Action</th>";
echo "</tr>";
//loop to show each records
while( $row = $result->fetch_assoc() ){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$firstname}</td>";
echo "<td>{$lastname}</td>";
echo "<td>{$username}</td>";
echo "<td>";
echo "<a href='edit.php?id={$id}'>Edit</a>";
echo " / ";
echo "<a href='#' onclick='delete_user( {$id} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{
//if table is empty
echo "No records found.";
}
//disconnect from database
$result->free();
$mysqli->close();
?>
<script type='text/javascript'>
function delete_user( id ){
//this script helps us to
var answer = confirm('Are you sure?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id to the record to be deleted
window.location = 'index.php?action=delete&id=' + id;
}
}
</script>
</body>
</html>
i am right in thinking i would be sending the rows id in the url ?
echo "<th><a href=\"single.php?id={$id}\">Firstname</></th>";
but i am having issues with single.php what code would i have to put to show the single entry?
i have been on this a while and got no were near so i deleted the code and swallowed my pride to seek some help :/
thanks in advance

Thank you for the interesting question.
First, let me inform you that, although you are using a moder-looking database access library, the way you are using it is as ancient as a mammoth fossil.
Several things to consider
Never use mysqli as is, but only in the form of some higher level abstraction library.
Never use real_escape_string in the application code but use prepared statements only.
Never mix your database code with HTML output. Get your data first, then start for output.
Never use GET method to modify the data.
Here goes the example based on the above principles. It does ALL basic CRUD operations:
<?
include 'safemysql.class.php'; // a library
$db = new SafeMysql();
$table = "test";
if($_SERVER['REQUEST_METHOD']=='POST') {
if (isset($_POST['delete'])) {
$db->query("DELETE FROM ?n WHERE id=?i",$table,$_POST['delete']);
} elseif ($_POST['id']) {
$db->query("UPDATE ?n SET name=?s WHERE id=?i",$table,$_POST['name'],$_POST['id']);
} else {
$db->query("INSERT INTO ?n SET name=?s",$table,$_POST['name']);
}
header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
exit;
}
if (!isset($_GET['id'])) {
$LIST = $db->getAll("SELECT * FROM ?n",$table);
include 'list.php';
} else {
if ($_GET['id']) {
$row = $db->getRow("SELECT * FROM ?n WHERE id=?i", $table, $_GET['id']);
foreach ($row as $k => $v) $row[$k]=htmlspecialchars($v);
} else {
$row['name']='';
$row['id']=0;
}
include 'form.php';
}
It is using templates to display the data:
list.php
Add item
<? foreach ($LIST as $row): ?>
<li><?=$row['name']?>
<? endforeach ?>
and form.php
<form method="POST">
<input type="text" name="name" value="<?=$row['name']?>"><br>
<input type="hidden" name="id" value="<?=$row['id']?>">
<input type="submit"><br>
Return to the list
</form>
<? if ($row['id']):?>
<div align=right>
<form method="POST">
<input type="hidden" name="delete" value="<?=$row['id']?>">
<input type="submit" value="Удалить"><br>
</form>
</div>
<?endif?>
here goes the part for display.
if ($_GET['id']) {
$row = $db->getRow("SELECT * FROM ?n WHERE id=?i", $table, $_GET['id']);
foreach ($row as $k => $v) $row[$k]=htmlspecialchars($v);
} else {
$row['name']='';
$row['id']=0;
}
include 'form.php';
if you don't want to show the form - create another template called single.php with whatever markup you wish

Single.php
I Use PDO if u want you can make it with MySQLi too.
<?php
include("db_connect.php"); // database configuration file
if(isset($_GET['id'])
{
$id = (int) $_GET['id'];
$sql = "SELECT * FROM `users` WHERE id=?";
$query = $conn->prepare($sql); // $conn is PDO object yours can be different
$query->bindValue(1,$id);
$query->execute();
if($query){
$row = $query->fetch(); //
}else{
echo "Error with Database";
}
}
else // Error for the Id selection
{
echo("ID is not selected");
}
?>
No while loop because you want just 1 record. $row variable is just for test because i don't know your fields in your DB
<table border="1">
<tr>
<td>ID</td>
<td>Firstname</td>
<td>Lastname</td>
</tr>
<tr>
<td><?php echo $row['id]; ?></td>
<td><?php echo $row['firstname']; ?></td>
<td><?php echo $row['lastname']; ?></td>
</tr>
</table>

in your single.php
$id=$_GET['id'];
$query="select * from users where id='".$id."'";

Related

Creating multiple form elements in html table to update SQL table

I'm using a SELECT query to generate a html table (screenshot) which displays data from a sql table.
Every <tr> is generating an additional <tr> for the administrator (if ($userUid == "admin") {) with the sql entry's ID + <textarea> to edit the content in the SQL column public.
The second administrator <tr> includes a <form> element to edit the content. I assume the repeating name elements of the multiple <input>s / <button>s in the form element cause the problem, but the script action="includes/update.inc.php" just returns a blank page with the following URL and no php error:
http://localhost:10006/includes/update.inc.php?editId=18&editContent=adsasd&submit-edit=
Generated table:
<?php
<table> ... / table head...
foreach($result as $row) {
echo "<tr class='data-row'>";
echo "<td>".$date_form."</td>
echo "<td>".$time_form."</td>
echo "<td>".$subject_form."</td>
echo "<td>".$private."</td>
echo "<td>".$public."</td>
echo "<td>".$date_form."</td>
echo "</tr>";
if ($userUid == "admin") { ?>
<tr class='admin-row'>
<form action="includes/update.inc.php" type="post">
<td><input name="editId" type="text" value="<?php echo $Id; ?>"></td>
<td class='p-2' colspan="4">
<textarea name="editContent" class="content-update-textarea" type="text"></textarea>
</td>
<td><button name="submit-edit" type="submit">EDIT</button></td>
</form>
</tr>
<?php }}?>
</table>
This is the /includes/update.inc.php script called by the form element which is supposed to update the content using <textarea name="editContent"> of the SQL row with the ID: <input name='editId'>.
<?php
include 'dbh.inc.php';
if (isset($_POST['submit-edit'])) {
$id = $_POST['editId'];
$editContent = $_POST['editContent'];
$sql = "UPDATE lesson SET public = ? WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "Failed to prepare statement.";
exit();
} else {
mysqli_stmt_bind_param($stmt, "ss", $editContent, $id);
mysqli_stmt_execute($stmt);
header ("Location: ../lesson.php?update=success");
}
}
I think you need to change form's attribute "type" to "method".
Your code after: <form action="includes/update.inc.php" method="post">
First, you make sure that your value is correctly transported into the backend section.
<?php
include 'dbh.inc.php';
if (isset($_POST['submit-edit'])) {
$id = $_POST['editId'];
$editContent = $_POST['editContent']; echo $editContent; //Verification step
/*$sql = "UPDATE lesson SET public = ? WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "Failed to prepare statement.";
exit();
} else {
mysqli_stmt_bind_param($stmt, "ss", $editContent, $id);
mysqli_stmt_execute($stmt);
header ("Location: ../lesson.php?update=success");
}*/
}

Can't figure out how to process delete button when it is clicked

I am trying to add a 'delete' button on my item table and have a delete button to delete the item and the information about the both item and the seller. I have the delete button on the table but I cannot figure out how to process that button when it is clicked. Please help! Thank you in advance!!
<?php
require 'authentication.inc';
// connect to the server
$connection = sqlsrv_connect( $hostName, $connectionInfo )
or die("ERROR: selecting database server failed");
// prepare SQL query
$UserID = $_SESSION['userID'];
$query = "SELECT * FROM ITEM WHERE userID= '$UserID'";
// Execute SQL query
$query_result = sqlsrv_query($connection, $query)
or die( "ERROR: Query is wrong");
// Output query results: HTML table
echo "<table border=1>";
echo "<tr>";
// fetch attribute names
foreach( sqlsrv_field_metadata($query_result) as $fieldMetadata)
echo "<th>".$fieldMetadata['Name']."</th>";
echo "</tr>";
// fetch table records
while ($line = sqlsrv_fetch_array($query_result, SQLSRV_FETCH_ASSOC)) {
echo "<tr>\n";
foreach ($line as $cell) {
echo "<td> $cell </td>";
}
echo "<td></td>";
echo "</tr>\n";
}
echo "</table>";
// close the connection with database
sqlsrv_close($connection);
?>
To add a delete feature you need two things, a button and secondly the processing of said button. I am not sure what your unique value is in the table, so I am using this fictitious key: itemID. Update with whatever your unique column name is.
Replace your table loop with:
<table border=1>
<tr>
<?php
// fetch attribute names
foreach( sqlsrv_field_metadata($query_result) as $fieldMetadata)
echo "<th>".$fieldMetadata['Name']."</th>"; ?>
</tr>
<?php
// fetch table records
while ($line = sqlsrv_fetch_array($query_result, SQLSRV_FETCH_ASSOC)) { ?>
<tr>
<?php foreach ($line as $cell) {
echo "<td> $cell </td>";
} ?>
<td>
<form method="post">
<input type="hidden" name="itemID" value="<?php echo $line['itemID']; ?>" />
<input type="submit" name="action" value="DELETE" />
</form>
</td>
</tr>
<?php } ?>
</table>
In the processing portion at the top, add processing:
if(!empty($_POST['action']) && ($_POST['action'] == 'DELETE')) {
// Do some sort of validation here
if(is_numeric($_POST['itemID']))
sqlsrv_query($connection, "delete from ITEM where itemID = '".$_POST['itemID']."'");
}

How to delete multiple rows from mysql database with checkbox using PHP?

I try to delete my data in "admin" database, but the delete button does not function.
This is my top part
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="admin"; // Database name
$tbl_name="admin"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
?>
This is my checkbox code
<tbody>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><?php echo $rows['course_code']; ?></td>
<td><?php echo $rows['course_name']; ?></td>
<td><?php echo $rows['lecture_id']; ?></td>
<td><input name="checkbox[]" type="checkbox"
id="checkbox[]" value="<?php echo $rows['course_code'];?>"></td>
<td><form>
</form>
</td>
</tr>
<?php
}
?>
</tbody>
and, this is my button code
<input type='button' id="delete" value='Delete' name='delete'>
This is my php function code
<?php
if(isset($_POST['delete'])){
for($i=0;$i<$count;$i++){
$del_id = $checkbox[$i];
$sql = "DELETE FROM $tbl_name WHERE course_code='$del_id'";
$result = mysql_query($sql);
}
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=delete.php\">";
}
}
mysql_close();
?>
include all the input elements within your <form> tags: <form> all inputs are here </form>
update:
<input name = "checkbox[]" type="checkbox" id="checkbox[]" value="<?php echo $rows['course_code'];?>">
to (id doesn't matter here):
<input name="checkbox[]" type="checkbox" value="<?php echo $rows['course_code'];?>"/>
and your button code:
<input type='button' id="delete" value='Delete' name='delete'>
to
<input type="submit" value="Delete"/>
set opening <form> tag to <form action="delete.php" method="post">
Note:
I assume below codes are in delete.php file. if not replace "delete.php" with that name in above opening form tag.
your delete.php file:
<?php
$cheks = implode("','", $_POST['checkbox']);
$sql = "delete from $tbl_name where course_code in ('$cheks')";
$result = mysql_query($sql) or die(mysql_error());
mysql_close();
?>
Note:
Since mysql_ will deprecate on future, better is use mysqli extension. But before use that, you have to enable it on your server. mysqli is a part of php and newer version of php has it but not enabled. To enable this, view php info page and find the path of php.ini file in "Loaded Configuration File" row on that page.
You can see php info page by loading below php file in the browser:
<?php
phpinfo();
?>
open that php.ini file in a text editor and un-comment or add a line extension=php_mysqli.dll at the extensions list there.
also search for "extension_dir" and open the directory it says and make sure php_mysqli.dll file is there.
(you may have .so extension if you not use windows OS)
Then restart your server and you are done!
By Fred -ii-
Using mysqli_ with prepared statements is indeed a better and
safer method. However, some will even suggest PDO, but even PDO
doesn't have some of the functionalities that mysqli_ offers;
strangely that. Even PDO needs sanitization. Many think that using PDO will solve injection issues, which is false.
-Thanks Fred.
try this code. it is working well.
connection.php
<?php $hostname_conection = "localhost"; /* this is the server name(assigned to variable) which is localhost since it runs on local machine */
$database_conection = "company"; /* this is the database name( assigned to variable)*/
$username_conection = "root"; /* user name (assigned to variable)*/
$password_conection = ""; /*password (assigned to variable) */
$conection = mysql_connect($hostname_conection, $username_conection, $password_conection) or trigger_error(mysql_error(),E_USER_ERROR); /* Mysql_connect function is used to conncet with database it takes three parameters server/hostname, username,and password*/
mysql_select_db($database_conection,$conection) or die(mysql_error("could not connect to database!")); /* Mysql_select is used to select the database it takes two parameters databasename and connection variable in this case $conection */
?>
multiple_delete.php
<?php require_once('conection.php'); ?>
<?php
in
/* now to display the data from the database which we inserted in above form we */ /* we make the query to select data from the table EMP */
$display = "select * from test_mysql";
$result = mysql_query($display, $conection) or die(mysql_error()); /* the query is executed and result of the query is stored in variable $result */
if ($result == FALSE) {
die(mysql_error()); /* displays error */
} ?> <h1 align="center"> Displaying Recods in Table </h1>
<form method="get" action="" id="deleteform" >
<table width="245" border="1" align="center">
<tr>
<td width="51">
<input type="submit" name="delete" id="button" value="delete" onclick="document.getElementById('deleteform').action = 'delete.php';document.getElementById('deleteform').submit();"/> <!--- here on clicking the button the form is submitted and action is set to delete.php Here we have used javaScript document refers to this whole page and now we can access any tag that has its id with help of getElementById() method and after the we specify the operation we want to perform in this case action and submit. --->
</td>
<td width="50">id</td>
<td width="55">name</td>
<td width="47">lastname</td>
</tr>
<?php
while ($rows = mysql_fetch_array($result))
{ /* here we make use of the while loop which fetch the data from the $result int array form and stores in $row now we can display each field from the table with $row[‘field_name’] as below */
?>
<tr>
<td>
<input type="checkbox" name="empids[]" value="<?php echo $rows['id']; ?>" /> <!--here with each checkbox we send the id of the record in the empids[] array --->
</td>
<td>
<?php echo $rows['id'] ?>
</td>
<td>
<?php echo $rows['lastname'] ?>
</td>
<td><?php echo $rows['name'] ?></td>
<?php } ?>
</tr>
</table>
</form> ?>
</body>
</html>
delete.php
<?php
require_once('conection.php');
?>
<?php
if (isset($_GET['delete'])) /* checks weather $_GET['delete'] is set*/
{
if (isset($_GET['empids'])) /* checks weather $_GET['empids'] is set */
{
$checkbox = $_GET['empids']; /* value is stored in $checbox variable */
if (is_array($checkbox))
{
foreach ($checkbox as $key => $your_slected_id) /* for each loop is used to get id and that id is used to delete the record below */
{
$q="DELETE FROM test_mysql WHERE id=$your_slected_id "; /* Sql query to delete the records whose id is equal to $your_slected_id */
mysql_query($q,$conection) ; /* runs the query */
}
header("location:multiple_delete.php"); /* Goes back to index.php */
}
} else
{
echo" you have not selected reords .. to delete";
}
} ?>
$sql = "SELECT * FROM blacklist";
$result = $link->query($sql);
$count=mysqli_num_rows($result);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc())
{
echo "<table>";
echo "<th>";
echo "<td>" . "ID: " . $row["id"]."</td>";
echo "<td>" . " Dial Target: " . $row["dial_target"]."</td>";
echo "<td>" . " Destination: " . $row["pozn"]."</td>";
echo "<td>" . " Date: " . $row["block_date"] . "</td>";
echo "<td>" . "<div class='background' style='position: relative; top:8px;'>" . "<form>" . "<input action='index.php' method='post' type='checkbox' name='chechbox[]' value='".$row["id"]."'/>" ."</form>" . "</div>" . "</td>";
echo "</th>";
echo "</table>";
echo "</br>";
}
}
else
{
echo "0 results";
}
if(isset($_POST['Delete']))
{
for($i=0;$i<$count;$i++)
{
$del_id = $checkbox[$i];
$del = "DELETE FROM blacklist WHERE Delete='$del_id'";
$result = $link->query($del);
}
if($result)
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=index.php\">";
}
}
<!-- DELETE BUTTON -->
<form>
<input type='Submit' id="Delete" value='Delete' name='Delete'/>
</form>
<?php
$args1 = array(
'role' => 'Vendor',
'orderby' => 'user_nicename',
'exclude' => $user_id.',1',
'order' => 'ASC'
);
$subscribers = get_users($args1); foreach ($subscribers as $user) {
$fvendorck = $wpdb->get_row("select * from wp_vandor where parent_id = '".$user_id."' and child_id = '".$user->id."'");
$isfavvendor = $fvendorck->child_id;
if(!empty($isfavvendor)) {
?>
<li><input type="checkbox" id="listID" value='<?php echo $user->id; ?>' name="chk1[]" checked=""/><?php echo $user->headline; ?></li>
<?php }else{ ?>
<li><input type="checkbox" id="listID" value='<?php echo $user->id; ?>' name="chk1[]" /><?php echo $user->headline; ?></li>
<?php } }?>
</ul>

Update echoed data using WHILE loop. Only updates one record

I can't seem to be able to update any records except the first one.
I am not sure how to modify any of the displayed records.
<?php
if(isset($_POST["action"]) == "update")
{
$id = $_POST['m_id'][0];
$type = $_POST['type'][0];
// if I echo $id & $type, it only gives me the first record.**
mysql_query("
UPDATE membership_type
SET mt_type ='$type'
WHERE mt_id = '$id'"
);
}
?>
ALl of this is within the same php page.
<form name=form action='' method='post'>
<?php
$result=mysql_query("SELECT * FROM membership_type;");
while($rows=mysql_fetch_array($result))
{ ?>
<input size=35 class=textField type=text name='type[]' value='<?php echo $rows['mt_type']; ?>'>
<input type=hidden name='m_id[]' value="<?php echo $rows['mt_id']; ?>">
<input type=submit value="Update">
<?php
}
?>
How do I edit any of the displayed records by simply clicking Update button???
First: You should NEVER use the mysql_* functions as they are deprecated.
Second: Try this code:
<?php
// Get a connection to the database
$mysqli = new mysqli('host', 'user', 'password', 'database');
// Check if there's POST request in this file
if($_POST){
foreach($_POST['m_id'] as $id => $type){
$query = "UPDATE membership_type
SET mt_type = '".$type."'
WHERE mt_id = '".$id."'";
// Try to exec the query
$mysqli->query($query) or die($mysqli->error);
}
}else{
// Get all membership_type records and then iterate
$result = $mysqli->query("SELECT * FROM membership_type") or die($mysqli->error); ?>
<form name='form' action='<?php echo $_SERVER['PHP_SELF'] ?>' method='post'>
<?php while($row = $result->fetch_object()){ ?>
<input size='35'
class='textField'
type='text'
name='m_id[<?php echo $row->mt_id ?>]'
value='<?php echo $row->mt_type; ?>'>
<input type='submit' value="Update">
<?php } ?>
</form>
<?php } ?>
Third: In order to add more security (this code is vulnerable), try mysqli_prepare
Only the first record is updated on every form submission because you have set $id = $_POST['m_id'][0], which contains the value of the first type[] textbox. To update all the other records as well, loop through $_POST['m_id'].
Replace it. Hope this works.
<?php
if(isset($_POST["action"]) == "update")
{
$id = $_POST['m_id'];
$type = $_POST['type'];
$i = 0;
foreach($id as $mid) {
mysql_query("UPDATE membership_type
SET mt_type='".mysql_real_escape_string($type[$i])."'
WHERE mt_id = '".intval($mid)."'") OR mysql_error();
$i++;
}
}
?>
Try this :
if(isset($_POST["action"]) == "update")
{
$id = $_POST['m_id'];
$type = $_POST['type'];
$loopcount = count($id);
for($i=0; $i<$loopcount; $i++)
{
mysql_query("
UPDATE membership_type
SET mt_type ='$type[$i]'
WHERE mt_id = '$id[$i]'"
);
}
}
You HTML was malformed and you were passing as an array but then only using the first element. Consider:
<form name="form" action="" method="post">
<?php
$result = mysql_query("SELECT * FROM membership_type;");
while($row = mysql_fetch_array($result))
echo sprintf('<input size="35" class="textField" type="text" name="m_ids[%s]" value="%s" />', $row['mt_id'], $row['mt_type']);
?>
<input type="submit" value="Update">
</form>
Then the server script:
<?php
if(isset($_POST["action"]) && $_POST["action"] == "Update"){
foreach($_POST['m_ids'] as $mt_id => $mt_type)
mysql_query(sprintf("UPDATE membership_type SET mt_type ='%s' WHERE mt_id = %s LIMIT 1", addslashes($mt_type), (int) $mt_id));
}
There are other things you could be doing here, eg. prepared statements, but this should work.

How to edit, delete and add in php mysql without jquery or java script?

I am trying to delete , edit and add new recodes on the same page but it seems am failing to make it work .And I do not want to do it using ajax jquery or java script but only php .I need some help please below are my code :
<?php
include_once('con.php');
$strSQL = "SELECT film_id, name
from
filmsbox";
$rs = mysql_query($strSQL);
echo "<table border='1' ><tr bgcolor='#eeeeee'><td>Name</td> <td colspan='2'>Action</td></tr>";
while($row = mysql_fetch_assoc($rs))
{
$film_id = $row['film_id'];
$name = $row['name'];
$hometeam= mysql_real_escape_string($name);
echo "<tr bgcolor='#eeeee'><td>$name</td> <td><a href='index.php?film_id=$film_id' name ='edit'>Edit</a></td><td><a href='index.php?film_id=$film_id' name ='delete'>Delete</a></td></tr>";
}
?>
<?php
$strSQL = "SELECT film_id, name
from
filmsbox";
$rs = mysql_query($strSQL);
$row = mysql_fetch_assoc($rs);
$film_id= $row['film_id'];
$name = $row['name'];
$name = mysql_real_escape_string($name);
$film_id= $_GET['film_id'];
?>
<?php
if(isset($_POST['edit'])){
?>
<table>
<form action="index.php" method="post">
<tr>
<td>
Name
</td>
<td>
<input type = "text" name = "name" value="<?php echo $name;?>">
</td>
</tr>
<input name="film_id" type="hidden" id="film_id" value="<?php echo $film_id; ?>">
<tr>
<td>
<input type = "submit" name = "submit" value="update">
</td>
</tr>
<?php
$name = (isset($_POST['name']))? trim($_POST['name']): '';
$film_id = $_POST['film_id'];
$sql = "UPDATE filmsbox SET name='$name'
WHERE film_id ='$film_id'";
$result = mysql_query($sql);
if($result)
{
echo "Success";
}
else
{
echo "Error";
}
}
?>
<?php
/*Delete section*/
if(isset($_POST['delete']))
{
$film_id = $_GET['film_id'];
$delete = "DELETE FROM filmsbox WHERE film_id = '$film_id'";
$result = mysql_query($delete);
if($result)
{
echo "Record deleted successfuly ";
}
else
{
echo "No data deleted";
}
}
?>
Couple of pointers:
You only need to escape values before they go into the database, not when they come out and are used in HTML i.e $hometeam = mysql_real_escape_string($name);
You are pulling the same query from the database twice in quick succession which is not needed. You can remove one of the 2 $strSQL = "SELECT film_id, name
from
filmsbox";
$rs = mysql_query($strSQL); sections from the top of your code
You need to run any update/delete queries on the data before you then do your select query to pull out the records for the page, otherwise your changes will not be shown
You should be escaping the values for your update and delete queries to prevent SQL injection
Edit:
To reload the page in an edit mode, you need to change the link URL in the table to something like
<a href='index.php?film_id=$film_id&edit=1' name ='edit'>Edit</a>
Then your edit block needs to be
if ($_GET['edit']) {
I want to be clear this is not in any way a secure method of editing values, as anyone can put ?edit=1 on the url and get to the form

Categories