How to delete multiple rows from mysql database with checkbox using PHP? - 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>

Related

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']."'");
}

Pass PHP array through Select Option Fields

I am writing a basic CMS system and have come across something which should be seemingly simple -but is beginning to frustrate me.!
I am trying to pass an array through a select option field to populate a list of categories in which I can save a post.
I have a 'posts' form which comprises of 3 fields. Title, content and Category ID (CatID).
When the user creates a post, they can select the category they wish to assign the post assigned to by using a drop down list - (this is populated by using a different form).
So the technical bit; -
MySQL DB:-
categories = catname (char60 PRIMARY), catid (INT10, AI)
posts = id (bigint20 PRIMARY), catid (int10 PRIMARY), title (text), content (varchar255)
Example of categories populates: catname = Home / catid = 1 ...etc
Output.php ;
<?php
function display_post_form($post = '') {
$edit = is_array($post);
?>
<form action="<?php echo $edit ? 'edit.php' : 'add.php' ; ?>" method="post">
<table border="0">
<tr>
<td> Title:</td>
<td> <input type="text" name="title" value="<?php echo $edit ? $post['title'] : '' ; ?>" size="60" /> </td>
</tr><tr>
<td> Content:</td>
<td> <textarea id="editor1" name="content" value="<?php echo $edit ? $post['content'] : '' ; ?>"> </textarea> </td>
</tr><tr>
<td> Category:</td>
<td><select name="catid">
<?php
$cat_array = get_categories($catid, $catname);
foreach($cat_array as $thiscat) {
echo "<option value=\"".$thiscat['catid']."\" ";
if (($edit) && ($thiscat['catid'] == $post['catid'])) {
echo " selected";
}
echo ">".$thiscat['catname']."</option>";
}
?>
</select>
</td>
</tr><tr>
<td> Button:</td>
<td <?php if (!$edit) { echo "colspan=2"; } ?> align="center">
<?php
if ($edit)
echo "<input type=\"hidden\" name=\"_id\" value=\"". $post['id'] ."\" />";
?>
<input type="submit" value="<?php echo $edit ? 'Update' : 'Add' ; ?> Post" />
</form></td>
</td>
</tr>
</table>
</form>
<?php
}
?>
Functions.php ;
function get_categories($catid, $catname) {
$conn = db_connect();
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL " .mysqli_connect_error();
}
$sql = "SELECT catname, catid FROM categories";
$result = mysqli_query($conn, $sql) or die(" Could not query database");
while($row = mysqli_fetch_assoc($result)) {
printf("\n %s %s |\n",$row["catname"],$row["catid"]);
}
mysqli_close($conn);
}
I am able to call in the 'get_cattegories()' function which generates a flat data of categories and their respective id's. I then combined this with the Select Option Field in the Output.php file and it doesn't generate anything.
Can anyone give some useful tips or advice? Many thanks :)
You are not returning the array but printing a string to the output. Change printf to return:
function get_categories($catid, $catname) {
$conn = db_connect();
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL " .mysqli_connect_error();
}
$sql = "SELECT catname, catid FROM categories";
$result = mysqli_query($conn, $sql) or die(" Could not query database");
$categories = array();
while($row = mysqli_fetch_assoc($result)) {
$categories[] = $row;
}
mysqli_close($conn);
return $categories;
}
Also I agree for the comments to your question. The arguments are useless.
You also may refactor the code, actually... alot. Move the mysql_connect() to the other place, probably at the beginning of your script.
I suggest to use some frameworks. I think KohanaPHP will be a good start. You will learn about architecture and some design patterns. Keep the good work and improve your skills ;-)

php script was working, now second $_POST suddenly not working

I am fairly new to php and have been searching for three days to find my problem. The script below worked for two years, and now suddenly the second POST command never populates (it is the last lines of code, and when I echo $_POST['input']; nothing is ever there.) I have looked at var_dump$[_$POST] and it gets $formType, but never $input.
Why would this suddenly stop working? It goes to the next form, but nothing works because it all counts on $input being passed on.
I am running on a unix server, Network Solutions.
Any help is greatly appreciated!!
here is the code (sanitized names of directories and databases, obviously):
<?php
session_start();
if ($_SESSION['auth'] != "yes") {
header("Location: login.php");
exit();
}
if (isset($_REQUEST['Enter'])) {
header("Location: http://www.mysite.com/subdirectory/nextform.php");
} else if (isset($_REQUEST['Delete'])) {
header("Location: http://www.mysite.com/subdirectory/deleterow.php");
}
########################################
####checks what kind of service request######
#########################################
?>
<form name="form" method="post" action="<?php
echo htmlentities($_SERVER['PHP_SELF']);
?>">
<p><legend>Form Type</legend></p>
<p> <basefont size = "4"></p>
<p><label for="formType" required>*Select Type of Form:</label></p>
<p><select name="formType"></p>
<p><option value="">select</option></p>
<p><option value="Garda">Security Officer</option></p>
<p><option value="Surveil">Surveil</option></p>
<p><option value="EmployApp">Employment Application</option></p>
<p></select></p>
<p><input type="submit" name="Submit" value="Submit" /></p>
</form>
<?php
$formType = $_POST['formType'];
SESSION_register("formType");
if ($formType == Garda) {
// Connects to your Database
include("introGardaform.php");
$database = "Gardaform"; // provide your database name
$db_table = "GardaINQ"; // leave this as is
$db = mysql_connect($hostname, $db_user, $db_password);
mysql_select_db($database, $db);
$data = mysql_query("SELECT * FROM GardaINQ") or die(mysql_error());
// puts the "GardaINQ"database table info into the $info array
//$info = mysql_fetch_array( $data );
Print "<table border cellpadding=15>";
while ($info = mysql_fetch_array($data)) {
Print "<tr>";
Print "<th>Inquiry Number:</th> <td>" . $info['Inquiry_num'] . "</td> ";
Print "<th>Contact Name:</th> <td>" . $info['contactName'] . " </td>";
Print "<th>Contact Number:</th> <td>" . $info['contactNum'] . " </td></tr>";
}
Print "</table>";
}
if ($formType == Surveil) {
// Connects to your Database
include("investfm.php");
$database = "investigateform"; // provide your database name
$db_table = "surveil"; // leave this as is
$db = mysql_connect($hostname, $db_user, $db_password);
mysql_select_db($database, $db);
$data = mysql_query("SELECT * FROM surveil") or die(mysql_error());
// puts the "surveil"database table info into the $info array
//$info = mysql_fetch_array( $data );
Print "<table border cellpadding=15>";
while ($info = mysql_fetch_array($data)) {
Print "<tr>";
Print "<th>Inquiry Number:</th> <td>" . $info['Inquiry_num'] . "</td> ";
Print "<th>Contact Name:</th> <td>" . $info['contactName'] . " </td>";
Print "<th>Contact Number:</th> <td>" . $info['contactNum'] . " </td></tr>";
}
Print "</table>";
}
if ($formType == EmployApp) {
// Connects to your Database
include("introhires.php");
$database = "hires"; // provide your database name
$db_table = "hiresentry"; // leave this as is
$db = mysql_connect($hostname, $db_user, $db_password);
mysql_select_db($database, $db);
$data = mysql_query("SELECT * FROM hiresentry") or die(mysql_error());
// puts the "hiresentry"database table info into the $info array
//$info = mysql_fetch_array( $data );
Print "<table border cellpadding=15>";
while ($info = mysql_fetch_array($data)) {
Print "<tr>";
Print "<th>First Name:</th> <td>" . $info['firstName'] . " </td>";
Print "<th>Last Name:</th> <td>" . $info['lastName'] . " </td>";
Print "<th>Date:</th> <td>" . $info['date'] . " </td></tr>";
}
Print "</table>";
}
?>
<form name="finddata" method="POST" action="<?php
echo htmlentities($_SERVER['PHP_SELF']);
?>">
<p> <basefont size = "4"></p>
<p><label for="finddata" required>Enter Inquiry Number for Garda or Surveil, Last name for Employment
Application:</label></p>
<p><input type = "text" size="20" maxlength="40" required onKeyPress="return noenter()"
name="input"></p>
<p><input type="hidden" value="<?php
echo $formType;
?>" name="formType"></p>
<p><input type="submit" name="Enter" value="Enter" ></p><br/>
<p><input type="submit" style="font-face: 'Comic Sans MS'; font-size: larger; color: red; background-color: #FFFFC0; border: 3pt ridge lightgrey" name = "Delete" value="Delete"></p>
</form>
<?php
$input = $_POST['input'];
SESSION_register("input");
echo $_POST['input'];
?>
You have used SESSION_register("formType"); undefined function and This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
So you can use $_SESSION["formType"]=$formType;, also
Need to wrap " or ' to check the string. Try this,
if($formType=="Garda"){
and if($formType=="EmployApp"){
instead of
if($formType==Garda){
if($formType==EmployApp){
You have a lot of issues on your code.
You are comparing your $formtype variable to a constant instead. It has to be like this. if($formType=="Garda"){ and if($formType=="Surveil"){ and if($formType=="EmployApp"){ add the double quotes to all those if statements as shown.
You are using a deprecated version i.e. session_register
can you try the following:
Remove the action attribute completely from both the forms as by default it is POST to self.
replace the font-face css property to font-family property in the last element of the second form. however that should not be the cause of the issue you are facing.
As there are 2 forms in the page and there are 2 code blocks depending on the form post, I assume that your second form post creates the issue in the first part of the code as the data for the first from will not be posted from the submit button in the second form. so before executing the piece of code you should identify if that piece of code should be executed or not. A simple multi form setup should look something like this:
<form name="form1" method="post">
<input type="text"/>
<input type="submit" name="form1-submit" value="Submit Name" />
</form>
<!-- form1 specific code -->
<?php
if(isset($_POST["form1-submit"]))
{
// do your stuff here
}
?>
<form name="form2" method="post">
<input type="text"/>
<input type="submit" name="form2-submit" value="Submit Name" />
</form>
<!-- form2 specific code -->
<?php
if(isset($_POST["form2-submit"]))
{
// do your stuff here
}
?>
<!-- independent code -->
<?php
// do your common code here.
?>
If you can write the code in above manner you will be able to resolve your problem yourself. please let us know in case above helped.

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

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."'";

when I am selecting multiple checkbox for deletion...only last one checkbox is deleted ! means it can delete 1 data from a database

Below code !Gives me check boxes and a delete button, In input tag all check box have same name (check)!! There check box can be retreive from database with id .
Problem Is:: when I am selecting multiple checkbox for deletion...only last one checkbox is deleted ! means it can delete 1 data from a database.
url like -> http://localhost/demo/delete.php?check=10&check=13&check=14&submit=Delete
I need while I am selecting a checkbox more than 1 checkbox ,check box datas is deleted from database ! Any one help me to overcome this problem thanks
index.php
<?php
$sql = mysql_connect('localhost', 'root', '');
mysql_select_db('database_section', $sql);
?>
<form name="checkbox" method="get" action="delete.php">
<table>
<tr>
<?php
$sql = "select * from data";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
?>
<td><input type="checkbox" name="check" value="<?php echo $row['id']?>"><?php echo $row['data'];?>
</td>
<?php
}
?>
<tr>
<td><input type="submit" name="submit" value="Delete"></td>
</tr>
</table>
</form>
Now, In delete.php..code below...
<?php
$sql = mysql_connect('localhost', 'root', '');
mysql_select_db('database_section', $sql);
if ($_REQUEST['submit']) {
$abc = $_GET['check'];
$sql = "Delete from data where id=$abc";
$result = mysql_query($sql) or die(mysql_error());
if (isset($result)) {
echo "data deleted";
}
else
{
echo "not possible";
}
}
?>
Use check box as an array holder. name it as check[] to hold all selected values. And on post you will get the selected array list.
Now your $abc will be a array, use foreach in delete.php to get the checked ids.
Change name="check" to name="check[]"
See more here: http://www.kavoir.com/2009/01/php-checkbox-array-in-form-handling-multiple-checkbox-values-in-an-array.html
[...]
while ($row = mysql_fetch_array($result))
{
?>
<td>
<input type="checkbox" name="check[]" value="<?php echo $row['id']?>"><?php echo $row['data']; ?>
</td>
<?php
}
?>
[...]

Categories