I am having an issue where I need to be able to delete multiple records using checkboxes.
Here is the code that I currently have.
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#############################################################################################
?>
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<table width=50%>
<form method="post" action="insert_ticket.php">
<table width border='0'>
<tr><td> Date:<input type="text" name="date"/></td>
<td>Ticket #:<input type="text" name="ticket"/></td></tr>
<table>
<tr><td>Description:<TEXTAREA COLS=50 name="description"></TEXTAREA></td></tr>
<tr><td> Result :<TEXTAREA COLS=50 name="result"></TEXTAREA></td></tr>
<tr><td><input type="submit" name="submit" value="Add"/></td></tr>
</table>
</table>
</form>
<form method="post" action="delete_ticket.php">
<input type="submit" name="delete" value="Delete"/>
</form>
</table>
<?php
print "<table width=80% border=1>\n";
$cols = 0;
while ($get_info = mysql_fetch_assoc($result)){
$id = $get_info->id;
if($cols == 0)
{
$cols = 1;
print "<tr>";
print "<th>Select</th>";
foreach($get_info as $col => $value)
{
print "<th>$col</th>";
}
print "<tr>\n";
}
print "<tr>\n";
print "<td><input type='checkbox' name='selected[]' id='checkbox[]' value=$id></td>";
foreach ($get_info as $field)
print "\t<td align='center'><font face=arial size=1/>$field</font></td>\n";
print "</tr>\n";
}
print "</table>\n";
mysql_close();
?>
<!------------------------------------------------------------!>
</BODY>
</HTML>
Delete.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#####################################
if($_POST['delete']) {
$checkbox = $_POST['selected'];
$countCheck = count($_POST['selected']);
for($i=0;$i<$countCheck;$i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM ticket_history WHERE Auto = $del_id";
$result = mysql_query($sql);
}
}
?>
I just want to be able to delete rows checked. How would I go about doing this effectively and efficiently?
Thank you in advance.
The simple answer to your question would be to use:
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN ()',
implode(',', $checkbox));
However as people will jump in and tell you, you are vulnerable to SQL injection. You should never trust user input. You are deleting using an ID, which I'm assuming must be an integer.
Using something like this will validate that:
$ids = array();
foreach($_POST['selected'] as $selected) {
if (ctype_digit($selected)) {
$ids[] = $selected;
}
else {
// If one is invalid, I would assume nothing can be trusted
// Depends how you want to handle the error.
die('Invalid input');
}
}
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN (%s)',
implode(',', $ids));
Other issues:
You seem to be using id's, but have not selected that field in your initial query.
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
Then you reference:
$id = $get_info->id;
Check the HTML output is actually what you expect.
In your delete query, you are referencing the field Auto. Is that your ID field?
And lastly, there no checking if the user has permission to do so. If this is a public site anyone can delete from that table.
Example of using two submit buttons within one form:
<?php
if (isset($_POST['create'])) {
echo "Create!";
}
elseif (isset($_POST['delete'])) {
echo "Delete!";
}
?>
<html>
<form method="post">
<input type="submit" name="create" value="Create"/>
<input type="submit" name="delete" value="Delete"/>
</form>
</html>
Related
I'm using easyPHP. I'm trying to update the records in my database but I keep getting <?php echo $btitle; ?> and <?php echo $bauthor; ?> written in the text boxes in my HTML form and data isn't updated but it does print "Updated data successfully".
Here's my form code:
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Update Book</title>
</head>
<body>
<h1>Update Your Library</h1>
<form method = "post" action = "editBook.php">
<?php
$conn = mysql_connect ("localhost", "root", "");
$db = mysql_select_db ("library", $conn);
$query = "select * from Books where No = ". $_GET['bid'];
$result = mysql_query($query, $conn);
while ($row = mysql_fetch_assoc($result))
{
$bid = $row ['bid'];
$btitle = $row ['btitle'];
$bauthor = $row ['bauthor'];
}
mysql_close($conn);
?>
<table>
<input type="hidden" name="bid" size="5" value="<?php echo $bid;?>">
<tr>
<td>Title:</td>
<td><input type="text" name="btitle" size="100"value="<?php echo $btitle;?>"></td>
</tr>
<tr>
<td>Author:</td>
<td><input type="text" name="bauthor" size="100" value="<?php echo $bauthor;?>"></td>
</tr>
</table>
<p>
<input type="submit" value="Update">
</p>
</form>
</body>
</html>
<?php
$dbhost = '127.0.0.1';
$dbuser = 'root';
$dbpass = '';
$bid=$_POST['bid'];
$btitle=$_POST['btitle'];
$bauthor=$_POST['bauthor'];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db('library');
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = "update books
set Title='$btitle',
Author='$bauthor'
where book_id='$bid'";
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
print "updated data successfully\n";
mysql_close($conn);
?>
It seems like the files does not get parsed by PHP. The problem may be a filename extention not defined in configuration.
On other hand I see another problem which may raise when the first issue is solved. Viariables which hold information are out of scope. This will lead to empty answer.
When you read from database:
while ($row = mysql_fetch_assoc($result))
{
$bid = $row ['bid'];
$btitle = $row ['btitle'];
$bauthor = $row ['bauthor'];
}
those 3 variables are created in the while(){} scope and they do not exist outside of it. Just initialize them with empty string before the loop in the main scope:
$bid = $btitle = $bauthor = '';
while ($row = mysql_fetch_assoc($result))
{
$bid = $row ['bid'];
$btitle = $row ['btitle'];
$bauthor = $row ['bauthor'];
}
Try This ::
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Update Book</title>
</head>
<body>
<h1>Update Your Library</h1>
<form method = "post" action = "save.php">
<?php
$conn = mysql_connect("localhost", "root", "");
$db = mysql_select_db("library", $conn);
$query = "select * from Books where No = " . $_GET['bid'];
$result = mysql_query($query, $conn);
while ($row = mysql_fetch_assoc($result))
{
$bid = $row['bid'];
$btitle = $row['btitle'];
$bauthor = $row['bauthor'];
}
?>
<table>
<input type="hidden" name="bid" size="5" value="<?php echo (isset($bid))?$bid:'';?>">
<tr><td>Title:</td><td><input type="text" name="btitle" size="100" value="<?php echo (isset($btitle))?$btitle:'';?>"></td></tr>
<tr><td>Author:</td><td><input type="text" name="bauthor" size="100" value="<?php echo (isset($bauthor))?$bauthor:'';?>"></td></tr>
</table>
<p><input type="submit" value="Update"></p>
</form>
</body>
</html>
<?php
mysql_close($conn);
?>
I am trying to make a search form on my site which prints all possible things that have come out of the database. However, when I search for something, it always gives me back that it can't find anything. How do I fix this?
PHP code:
$host = 'localhost';
$user = '111042';
$password = 'jcbvrjd8';
$db_name = '111042';
$search = $_POST["search"];
if(isset($search)) {
$db = mysqli_connect($host, $user, $password, $db_name);
$wild_search = "%".$search."%";
$findname = "SELECT `name`,`surname`
FROM `Account`
WHERE `name` LIKE '".$wild_search."'
OR `surname` LIKE '".$wild_search."'
OR CONCAT(`name`, `surname`) LIKE '".$wild_search."'
OR CONCAT(`name`, `surnameprefix`, `surname`) LIKE '".$wild_search."';";
$query = mysqli_query($db,$findname);
$results = mysqli_fetch_all($query);
if($result) {
echo "<div id='searchresult'>\n";
echo "<h1>People Found:</h1>\n";
echo "<table id='searchresult'>\n";
foreach($result as $rowno => $row) {
echo "<tr class='searchtablerow'>\n";
echo "<td>".$row['name'].", ".$row['surname']."</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
} else {
echo "<div id='searchresult'><h1>People Found:</h1>\n";
echo "<p>No one was found...</p>\n";
echo "</div>\n";
}
} else {
}
HTML form:
<div id="searchform">
<h1>Search friends:</h1>
<form name="searchform" method="post" action ="searchlink.php">
<input type="text" name="search" id="search" autofocus placeholder="e.g. John Smith..."></input> <br>
<input type="submit" name="submitsearch" value="Search" id="searchbutton"></input>
</form>
</div>
Thank you guys for helping me.
PS. Please do not roast me, I'm just not as advanced as you are.
$query = mysqli_query($db,$findname);
$results = mysqli_fetch_all($query);
if ($results) {
...
"s" missing at end of result. (or delete the s in $results = mysqli_fetch_all($query);)
I need to create a function which retrieves my data from my database into a drop down list, then choose and remove the selected data. I have my drop down list done & working but I'm experiencing some error with my 'Remove' function.
<body>
<?php
//connecting to database
$server = 'localhost';
$username = 'root';
$password = 'infosys';
$database = 'project';
mysql_connect($server,$username,$password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
//dropdown list to retrieve sentence
$sql = "SELECT words FROM sentence";
$result = mysql_query($sql);
echo "<select name
='dropdownlist'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['words'] ."'>" . $row['words'] ."</option>";
}
echo "</select>";
?>
<form method="post" action="remove.php">
<input type="submit" value="Remove" />
</form>
<a href="index.php" >View list</a>
</body>
Followed by another php file
<?php
$server = 'localhost';
$username = 'root';
$password = 'infosys';
$database = 'project';
mysql_connect($server,$username,$password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
$dropdownlist1 = $_POST['dropdownlist'];
$dropdownlist2 = $dropdownlist1.value;
if(isset($_GET['id'])) {
$mysql_query("DELETE FROM 'words' WHERE id = $dropdownlist2");
header("location: index.php");
exit();
}
?>
Move your Select box or dropdown inside the form tag,
<form method="post" action="remove.php">
<select name ='dropdownlist'>
<?php while ($row = mysql_fetch_array($result)) { ?>
<option value='<?php echo $row['words'];?>'><?php echo $row['words'];?></option>
<?php } ?>
</select>
<input type="submit" value="Remove" />
</form>
in php,
if(isset($_POST['dropdownlist'])) {
$dropdownlist1 = $_POST['dropdownlist'];
mysql_query("DELETE FROM `sentence` WHERE `words` = '$dropdownlist1' ");
header("location: index.php");
exit();
}
Note: Use mysqli_* or PDO functions instead of using mysql_* functions(deprecated)
Here is my challange:
I want to update a MySQL table with inputs from a $_POST array.
How is this done? (Spend hours upon hours looking for a solution to this).
In my “table.php” I get the data from MySQL and place it in input forms.
In my “updatesfields.php” I can’t figure out how to update the fields in MySQL.
(I might be way off, but that's no news)
Table.php:
<form method="POST" action="updatefields.php" enctype="multipart/form-data" >
<table border="1"><tr>
<td>ID</td>
<td>Text</td>
</tr>
<?php
$host = "xxx";
$username1 = "xxx";
$password1 = "xxx";
$db_name = "xxx";
$tbl_name = "xxx";
$conn = new PDO("mysql:host=$host;dbname=$db_name",$username1,$password1);
$sql = "SELECT * FROM $tbl_name ORDER BY bilag ASC";
$q = $conn->prepare($sql);
$q->execute(array($title));
$q->setFetchMode(PDO::FETCH_BOTH);
// fetch
while($data = $q->fetch()){
echo "<tr><td>";
// --------------------- ID -----------------------------
$id = $data[0];
if ($id != 0)
{ echo "<center><input type='text' style='font-weight:bold;' value='$id' name='id[]' size='10'>";}
else { echo "<center><input type='text' style='font-weight:bold;' value='' name='id[]' size='10'>"; }
echo "</td>";
// --------------------- ID -----------------------------
echo "<td>";
// --------------------- Text -----------------------------
$text = $data[3];
if ($text != null)
{ echo "<center><input type='text' style='font-weight:bold;' value='$text' name='text[]' size='10'>";}
else { echo "<center><input type='text' style='font-weight:bold;' value='' name='text[]' size='10'>"; }
// --------------------- Text -----------------------------
echo "</td></tr>";
}
?>
</table>
<br>
<input type="submit" value="Update">
</form>
updatefields.php:
<?php
$host = "xxx";
$username1 = "xxx";
$password1 = "xxx";
$db_name = "xxx";
$tbl_name = "xxx";
foreach ($_POST as $number => $text)
{
$conn = new PDO("mysql:host=$host;dbname=$db_name",$username1,$password1);
$sql = "UPDATE $tbl_name SET text=? WHERE id=?]";
$q = $conn->prepare($sql);
$q->execute(array($indsæt,$id));
}
?>
First, in the HTML, we need to change this:
<input type="submit" value="Update">
to this. Names are important attributes because they become keys in the $_POST array.
<input type="submit" name="submit" value="Update">
Then, in updatefields.php:
if (isset($_POST['submit'])){
//how many ids came through in the $_POST array?
$id_count = count($_POST['id']);
//connect only once, before the loop
$conn = new PDO("mysql:host=$host;dbname=$db_name",$username1,$password1);
//this runs once for each id we have
for ($i=0; $i<$id_count; $i++){
$sql = "UPDATE $tbl_name SET text=? WHERE id=?";
$q = $conn->prepare($sql);
$q->bindParam(1, $_POST['text'][$i]);
$q->bindParam(2, $_POST['id'][$i]);
$q->execute();
if ($q) {//execute() returns TRUE on success
//insert success
} else {
//insert failed
}
}//for loop
} else {//submission did not come from form
echo "There was a problem processing this request. Please click here to try again.";
}
You can read more about binding parameters in the PHP documentation.
i want to delete a table row from my database with MySQL and PHP. I have searched on the internet and I can't figure out what I'm doing wrong. I have the feeling I'm close.
If I go over the delete link there is a link showing with the ID number of the row to delete. But if I click it, it isn't working.
This is my code for admin.php
<?php
if(!isset($_COOKIE['E2ingelogd'])) {
header("location:../../index.php");
}
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Kan niet inloggen");
$selected = mysql_select_db("login", $dbhandle);
if(isset($_POST['team'])){
$team = $_POST['team'];
$ID = $_POST['id'];
$query = mysql_query("SELECT * FROM e2teams WHERE Team='$team' and ID='$ID'");
if(mysql_num_rows($query) > 0 ) { //check if there is already an entry for that username
echo "$team bestaat al!";
}
else{
mysql_query("INSERT INTO e2teams (Team) VALUES ('$team')");
header("location:e2admin.php");
}
}
mysql_close();
?>
<html><head>
<link href='http://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'>
<link href="../css/layout.css" rel="stylesheet" type="text/css"></head>
<body>
<div class="wrapper">
<div class="header">
<div class="logo"><img height="140" src="../images/boyslogo.png"> </div>
<div class="titelpagina">Vroomshoopse Boys E2 admin panel</div>
<div class="uitloggen">Uitloggen</div>
</div>
<div class="content">
<div class="teamstoevoegenvak">
<div class="titelbalk">
<h1>Voeg teams toe</h1>
<form style="border:0px; margin:0px; padding:0px"; action="e2admin.php" method="POST">
<input width="400" maxlength="400" type="text" name="team" placeholder="Team naam" /><br>
<input type="submit" value="Toevoegen" />
</form></div>
</div>
<div clas="toegevoegdeteamsvak">
<div class="titelbalktoege">
<h1>Toegevoegde teams</h1>
</div>
<div class="deteams">
<?php
$table = "e2teams";
$sql = "SELECT * FROM e2teams";
$result = mysql_query($sql, $dbhandle);
if(mysql_num_rows($result) > 0){
$team = array();
while($row = mysql_fetch_array($result)) {
echo "<table><tr><td class='styled-td'>";
echo $row['Team']. '</td><td></td><td>Bewerk</td><td><a href="delete.php?del='.$row['ID'].'">Delete<br>';
echo "</td></tr></table>";
$team = $row['Team'];
}
}
mysql_data_seek($result, 0);
?>
</div>
</div>
</div>
<div id="volgendewedstrijd"> <form action="" method="post">
<select name="dropdown">
<?php
mysql_data_seek($result, 0);
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)) {
echo '<option value="">' . $row['Team'] . '</option>';
}
}
?>
</select>
</form></div>
</div>
</body>
</html>
The piece of code where the delete is, is this:
if(mysql_num_rows($result) > 0){
$team = array();
while($row = mysql_fetch_array($result)) {
echo "<table><tr><td class='styled-td'>";
echo $row['Team']. '</td><td></td><td>Bewerk</td><td><a href="delete.php?del='.$row['ID'].'">Delete<br>';
echo "</td></tr></table>";
$team = $row['Team'];
}
}
mysql_data_seek($result, 0);
?>
And this is my delete.php:
<?php
if(!isset($_COOKIE['E2ingelogd'])) {
header("location:../../index.php");
}
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
mysql_query("DELETE FROM e2teams WHERE ID = $_GET[id]");
echo "Team is deleted";
header('location: e2admin.php');
?>
What am I doing wrong?
You are using del as a param in the link
<a href="delete.php?del='.$row['ID'].'">Delete<br>
This needs to be closed as
Delete<br>
And in the delete script you need to get it as
$id = (int)$_GET["del"];
and use in the query as
mysql_query("DELETE FROM e2teams WHERE ID = $id");
This:
mysql_query("DELETE FROM e2teams WHERE ID = $_GET[id]");
Should be:
mysql_query("DELETE FROM e2teams WHERE ID = ".$_GET['del']."");
Because of:
<a href="del.php?del='.$row['ID'].'"> //the get var name is: del
You can access a variable inside a array between quotes:
Change the following line
mysql_query("DELETE FROM e2teams WHERE ID = $_GET[id]");
to
mysql_query("DELETE FROM e2teams WHERE ID = " . $_GET['id']);
This is a security risk and you are acceptable to SQL injections. Please google: "php sql injections".