I have a table generated with The foreach construct, on each <tr> there is a delete button inside. I want to delete the row containing the button (by the ID) but all I've done is delete the last row (the last ID) that was saved and not the desired.
This is a part of my HTML code:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
<table class="Pizarra" id="pizarra" cellspacing="0px";>
<tr class="trThDos">
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tbody>
<!-- Comienza PHP -->
<?php
$i = 0;
foreach ($resultados as $fila)
{
?>
<tr>
<input type="hidden" name="id" value="<?php echo $fila['ID']; ?>" />
<td class="tdTurno"><?php echo '#' . ++$i ?></td>
<td class="tdImg">
<?php echo $fila ['value'];
switch ($fila['value'])
{
case "0":
echo "<img src='./img/consulta-56-2.png'";
break;
case "1":
echo "<img src='./img/shot-56-2.png'";
break;
case "2":
echo "<img src='./img/ta-56-2.png'";
break;
case "3":
echo "<img src='./img/cert-56-2.png'";
break;
default:
echo "Hubo un error en la selección";
break;
} ?>
</td>
<td>
<?php echo $fila ['nombre']; ?>
</td>
<td class="tdHr">
<?php echo $fila ['hora']; ?>
</td>
<td>
<input type="submit" class="btnBorrar" name="btnBorrar" value="X">
</td>
</tr>
<?php } ?>
</tbody>
</table>
</form>
PHP code:
<?php
// ----------- CONEXIÓN ------------------
try {
$conexion = new PDO('mysql:host=localhost;dbname=farmacia', 'Emm', ' ');
$conexion->exec("set names utf8");
//echo "Conexión OK <br />";
}catch(PDOException $e){
echo "Error: " . $e->getMessage();
die();
}
// ----------- TERMINA CONEXIÓN -----------------
if(isset($_POST['btnBorrar'])){
$id = $_POST['id'];
$statement = $conexion->prepare("DELETE FROM eventos WHERE ID = $id");
$statement->execute();
//fetchAll' es clave para que invoque (llame) TODOS los elementos
$resultados = $statement->fetchAll();
header("Location:index.php");
$conexion = null;
}
?>
Use GET method instead of POST
In your HTML instead of using submit button use link as shown in below
X
In the delete.php do like following
<?php
if(isset($_GET['id'])){
//get the id into php variable like below
$id = $_GET['id'];
//sql query to delete with id variable in where clause
}
?>
Hope this work!!!
Try with below code..
HTML
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
<table class="Pizarra" id="pizarra" cellspacing="0px";>
<tr class="trThDos">
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tbody>
<!-- Comienza PHP -->
<?php
$i = 0;
foreach ($resultados as $fila) {
?>
<tr id="row_id_<?php echo $fila['ID']; ?>">
<td class="tdTurno"><?php echo '#' . ++$i ?></td>
<td class="tdImg"><?php echo $fila ['value'];
switch ($fila['value']){
case "0":
echo "<img src='./img/consulta-56-2.png'";
break;
case "1":
echo "<img src='./img/shot-56-2.png'";
break;
case "2":
echo "<img src='./img/ta-56-2.png'";
break;
case "3":
echo "<img src='./img/cert-56-2.png'";
break;
default:
echo "Hubo un error en la selección";
break;
} ?></td>
<td><?php echo $fila ['nombre']; ?></td>
<td class="tdHr"><?php echo $fila ['hora']; ?></td>
<td><input type="button" class="btnBorrar" name="btnBorrar" value="X" onClick="delete_row(<?php echo $fila['ID']; ?>)"></td>
</tr>
<?php } ?>
</tbody>
</table>
</form>
JavaScript
function delete_row(delete_id) {
$.ajax({
type: "POST",
url: 'delete_row.php',
data: 'delete_id='+delete_id,
success: function(data_respones){
$("#row_id_"+delete_id).remove();
}
});
}
delete_row.php
<?php
// ----------- CONEXIÓN ------------------
try {
$conexion = new PDO('mysql:host=localhost;dbname=farmacia', 'Emm', ' ');
$conexion->exec("set names utf8");
//echo "Conexión OK <br />";
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
die();
}
if(isset($_POST["delete_id"])){
//do delete stuff
$statement = $conexion->prepare("DELETE FROM eventos WHERE ID = $id");
$statement->execute();
}
?>
Instead of using POST method, use GET and give your delete button a link like
yourscript.php?delete={ID}
and handle your id like
$deleteId = (int)$_GET["delete"];
and
if(isset($deleteId)){
//do delete stuff
$statement = $conexion->prepare("DELETE FROM eventos WHERE ID = $deleteId");
$statement->execute();
//fetchAll' es clave para que invoque (llame) TODOS los elementos
$resultados = $statement->fetchAll();
}
Replace your hidden input field with this;
<a href="yourscript.php?delete=<?php echo $fila['ID']; ?>">Delete me</>
Related
Good day folks,
Please I'm trying to implement something simple but I'm not finding the proper solution in PHP. I would like to ask for some advises, please.
I have one list of servers in the Array/Vector called $lines, now I would like to SELECT each server name in a MySQL DB in order to collect additional infos.
Could you please give me ideas regarding how to do a loop from the server names in, to SELECT / QUERY each one ?
Thanks!!
<html>
<head>
</head>
<body>
<form name="form1" method="post">
<textarea rows="10" name="servers[]" cols="50" ></textarea>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
$con=mysqli_connect("hostxxxx","userxxxx","xxxxxxxx","xxxxxxx");
//Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST["submit"]))
{
if(!empty($_POST["servers"]))
{
echo '<h4>You have selected the following Servers:</4><br>';
$submitted_array = array_keys($_POST["servers"]);
$lines = explode(PHP_EOL, $_POST["servers"][$submitted_array[0]]);
foreach($lines as $servers)
{
echo ($servers."<br>");
}
}
else
{
echo 'Please write something';
}
}
?>
</body>
</html>
I've got the result as I needed, I hope it can help:
<body>
<form name="form1" method="post">
<textarea rows="1000" name="servers[]" cols="100" style="width:300px;height:300px;"></textarea>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
$con=mysqli_connect("hostxxxxx:portxx","userx","passxx","msdb");
//Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST["submit"]))
{
if(!empty($_POST["servers"]))
{
echo '<h4>You have selected the following Servers:</4><br>';
$submitted_array = array_keys($_POST["servers"]);
//BREAKING IN AN ARRAY
$lines = explode(PHP_EOL, $_POST["servers"][$submitted_array[0]]);
//foreach($lines as $servers)
//{
//echo ($servers."<br>");
//}
//REMOVING BLANK SPACES:
function trim_value(&$value)
{
$value = trim($value);
}
//ADDING QUOTES BETWEEN THE VALUES
function add_quotes($str) {
return sprintf("'%s'", $str);
}
//REMOVING BLANK LINES
array_walk($lines, 'trim_value');
$VCSAC2 = "VCSAC2";
$LPAR = "LPAR";
$HOSTF = "HOSTF";
$CLASSG = "CLASSG";
$IP = "IP";
$STATUS = "STATUS";
//USING IMPLODE
//$sql=sprintf("SELECT * FROM main WHERE HOSTF IN (".implode(',', $lines).")");
$sql=sprintf("SELECT * FROM main WHERE HOSTF IN (".implode(',', array_map('add_quotes',$lines)).")");
//USED TO CHECK SQL SINTAX
//echo $sql;
$result=mysqli_query($con,$sql);
}
else
{
echo 'Please write something';
}
}
?>
<table id="demo1" cellpadding="0" cellspacing="0" style="width:100%" style="font-size:13px">
<thead>
<tr>
<th align=left>HostName</th>
<th align=left>VCS</th>
<th align=left>LPAR</th>
<th align=left>IP</th>
<th align=left>Class</th>
</tr>
</thead>
<?php while($dado = mysqli_fetch_array($result)) {?>
<tbody>
<tr>
<td align=left style="font-size:14px"><?php echo $dado[$HOSTF]; ?></td>
<td align=left style="font-size:14px"><?php echo $dado[$VCSAC2]; ?></td>
<td align=left style="font-size:14px"><?php echo $dado[$LPAR]; ?></td>
<td align=left style="font-size:14px"><?php echo $dado[$IP]; ?></td>
<td align=left style="font-size:14px"><?php echo $dado[$CLASSG]; ?></td>
</tr>
</tbody>
<?php } ?>
</table> <br><br>
</body>
Today I needed to do some changes on my website so I downloaded the whole site to my computer, changed the IP's and login details and the website is working.
But, when I went to a page, I press the button and nothing happens, and the same button is working on the webhost.
This is the code I'm using (exactly the same on the webhost that is working):
if($serverSettings['itemshop']) {
if(isset($_GET['p']) && checkInt($_GET['p'])) {
$sqlCmdS="SELECT * FROM ".SQL_HP_DB.".is_items WHERE kategorie_id='".$_GET['p']."' AND anzeigen='J' ORDER BY preis ASC, vnum ASC";
}
else {
$sqlCmdS="SELECT * FROM ".SQL_HP_DB.".is_items WHERE anzeigen='J' ORDER BY preis DESC, vnum DESC";
}
?>
<div id="isleft">
<h2>Categorías</h2><br/>
<ul>
<?PHP
$sqlCmd = "SELECT * FROM ".SQL_HP_DB.".is_kategorien WHERE anzeigen='J' ORDER BY id ASC;";
$sqlQry = mysql_query($sqlCmd,$sqlHp);
while($getKats = mysql_fetch_object($sqlQry)) {
echo'<li>'.$getKats->titel.'</li>';
}
?>
</ul>
</div>
<div id="isright">
<table>
<?PHP
$sqlQry = mysql_query($sqlCmdS,$sqlHp);
$counter = 1;
while ($getItems = mysql_fetch_object($sqlQry)) {
$aktItem = compareItems($getItems->vnum);
$aktItem1 = compareItems($getItems->id);
$nome = compareItems($getItems->nome);
$itemStufe = (checkInt($aktItem['stufe'])) ? "+".$aktItem['stufe'] : '';
//$itemStufe1 = (checkInt($aktItem1['stufe'])) ? "+".$aktItem1['stufe'] : '';
?>
<tr>
<th colspan="2" class="topLine"><?= $nome['item'] ?> (<b><?= $getItems->count ?>x</b>) (<b><?= $getItems->preis ?> Coins</b>)</th>
</tr>
<tr>
<td class="isImg">
<?PHP
if(!empty($getItems->bild)) echo'<img src="./is_img/'.$getItems->bild.'.png" title="'.$aktItem['item'].'" alt="'.$aktItem['item'].'"/>';
?>
</td>
<td class="tdunkel"><?= $getItems->beschreibung ?></td>
</tr>
<tr>
<td colspan="2" class="isBuy">
<select id ="escolha<? echo $counter ?>">
<option value="">Escolhe...</option>
<option value="eu">Para mim</option>
<option value="outro">Para outro jogador</option>
</select><button onclick="confirmacao(escolha<? echo $counter; ?>,<? echo $getItems->id ?>,<? echo $getItems->preis; ?>)" title="Vais gastar <? echo $getItems->preis; ?> moedas">Comprar</button>
</td>
</tr>
<?PHP
$counter++;
}
?>
</table>
</div>
<script>
function confirmacao(escolha,id,preco)
{
//var val = escolhida.options[escolhida.selectedIndex].value;
switch(escolha.options[escolha.selectedIndex].value)
{
case "eu":
function confirma_compra(id,preco)
{
var ask = window.confirm("Queres mesmo comprar?\nIrão ser removidas "+preco+" moedas da tua conta!");
if (ask)
{
document.location.href = './is_buy-'+id+'.htm';
}
}
return confirma_compra(id,preco)
break;
case "outro":
document.location.href = './is_buy_outro-'+id+'.htm';
break;
case "":
alert("Tens de selecionar uma opção!");
break;
default:
alert("test");
}
return false;
}
</script>
And, this happens on the button's tooltip: https://prnt.sc/ff9mka
Thanks in advance
As I can see on your screenshot, they're showing you "<? echo ... ?>"
The problem are who newer versions of PHP have deprecated the shorttags. You need to change all tags <? with the complete one: <?php
My purpose is search book type from input keyboard and count it. I have error: counting the number of book is right but when print, it miss some result. For example, I put 'f' it show 7 result( right) however it print only 2 two result. Here is my code:
<form action="" method="POST">
Enter type of book here:<input type="text" size="20" name="sbt"> <br />
<input type="submit" name="sb" value="Search">
</form>
<table align="center" border="1" width="600">
<thead><tr align="center">
<tr align="center">
<td><b>Book ID</b></td>
<td><b>Book Title</b></td>
<td><b>Book Author</b></td>
<td><b>Pulished Year</b></td>
<td><b>Book Type</b></td>
<td><b>Status</b></td>
</tr>
<?php
if (isset($_POST['sb'])) {
$s="";
if ($_POST['sbt'] == null) {
echo "Please re-enter <br>";
} else
{
$s = $_POST['sbt'];
}
$q = "SELECT * FROM book WHERE book_type LIKE '%$s%' ";
$r= mysqli_query($conn,$q);
while($row = mysqli_fetch_array($r)) {
?>
<tr align="center">
<td><?php echo $row['book_no'];?></td>
<td><?php echo $row['book_title'];?></td>
<td><?php echo $row['book_author'];?></td>
<td><?php echo $row['book_year'];?></td>
<td><?php echo $row['book_type'];?></td>
<td>
<?php
if ($row['book_quantity'] == 1) {
echo "Available";
}
else {
echo "Not available";
}
?>
</td>
<?php
$c=" SELECT COUNT(DISTINCT(book_no)) AS totaltype FROM book WHERE book_type LIKE '%$s%'";
$s= mysqli_query($conn, $c);
if (mysqli_num_rows($s)> 0 )
{
$row2= mysqli_fetch_array($s);
echo " Total book type result:"."{$row2['totaltype']}";
}
}
?>
<?php } ?>
</table>
Remove "%" before $s and try.
for example:
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");
I have array which get all E-mails which are invited by the user before. I checking which e-mails are selected by checkbox and then I add them to the table 'zaproszenia'. The array saves the records. When i click the button 'Zapisz'(SAVE) I have error:
Notice: Undefined offset: 1 in D:\xampp\xampp\htdocs\inzynierka\inzynierka\zaproszenia.php on line 91
This line is:
$tabMail=$mail_array[$i];
I want save to the table 'zaproszenia' the e-mail which is select by checkbox. I have no idea how do that. I was trying and trying and nothing.Sorry about my english. I hope that I describing the problem clear.
Code fragment with file: zaproszenia.php - List the emails and checkboxes for them:
<form method="post">
<table class="table table-striped">
<thead>
<tr>
<th>Email_goscia</th>
<th>Imię</th>
<th>Nazwisko</th>
<th>Kod_dostepu</th>
<th>Data ważności kwest.</th>
</tr>
</thead>
<tbody>
<?php
$sqlc=mysqli_connect('127.0.0.1','root','');
if($sqlc)
{
$sql_q="USE aplikacja";
mysqli_query($sqlc,$sql_q);
//wyświetlanie listy gości dodanych przez uzytkownika globalnie tzn. to jest lista z ktrej uzytkownik wybiera ktrych gosci chce zaprosić do konkretnego kwestionariusza
$sql_q=mysqli_query($sqlc, "SELECT * FROM goscie g, uzytkownicy_goscie ug WHERE g.Email_goscia=ug.Email_goscia AND ug.Login='$log' ");
$lp=1;
if(mysqli_num_rows($sql_q) != 0)
{
$licznik=0;
while ($recordG=mysqli_fetch_array($sql_q))
{
?><tr>
<td> <?php echo $mail = $recordG['Email_goscia'];
$mail_array=array($licznik => $mail);
$licznik++; //$_SESSION['tablicaMail']=$mail_array; print_r($_SESSION);
print_r($mail_array);
?></td>
<td> <?php echo $recordG['Imie'];?> </td>
<td> <?php echo $recordG['Nazwisko']; ?> </td>
<td> <?php echo $recordG['Kod_dostepu'];?></td>
<td> <?php echo '<input type="date" name="data_waznosci'.$lp.'" id="data_waznosci'.$lp.'">'; ?> </td>
<td> <?php echo '<td><input type="checkbox" name="zaznaczyc'.$lp.'" id="zaznaczyc'.$lp.'" class="ClassZaznacz" onchange = "zaznacz();"/> <br /></td>'; ?> </td>
</tr>
<?php
$lp++;
}
}
else
{
echo "Użytkownik nie dodał jeszcze żadnych gości";
} ?>
</tbody>
</table>
<input type="submit" class="btn btn-primary" name="zapros" id="zapros" value="Zapisz zmiany" />
</form>
Save the selected emails by checkboxes:
<?php
if (isset($_POST['zapros']))
{
$data_zaproszenia = date("Y-m-d");
$liczba = count(preg_grep('/^data_waznosci[\d]*/', array_keys($_POST)));
echo $liczba;
if(mysqli_num_rows($sql_q) != 0)
{
for ($i=1; $i <= $liczba ; $i++)
{
/*while ($recordG=mysqli_fetch_array($sql_q)) {
$mail = $recordG['Email_goscia'];
$mail_array=array($mail);
} print_r($mail_array); //$mail = $recordG['Email_goscia']; //echo $mail; */
if (isset($_POST["zaznaczyc".$i]))
{
$sql_wyniki = mysqli_query($sqlc, "INSERT INTO wyniki (Data_wypelnienia, ID_kwestionariusza) VALUES (NULL, $id)");
$id_wyniku=mysqli_query($sqlc, "SELECT ID_wyniku FROM wyniki WHERE ID_kwestionariusza=$id");
$id_wyniku2 = mysqli_fetch_assoc($id_wyniku);
$data_waznosci = $_POST['data_waznosci'.$i];
//$tablicaMail1 = $_SESSION['tablicaMail'][$i]; //print_r($_SESSION); // echo $tablicaMail1;
$tabMail=$mail_array[$i];
$sql_zaproszenie=mysqli_query($sqlc, "INSERT INTO zaproszenia (Email_goscia, ID_kwestionariusza, ID_wyniku, Data_zaproszenia, Data_waznosci, Wynik, Ocena, Status)
VALUES ('$tabMail', $id, '$id_wyniku2[ID_wyniku]', '$data_zaproszenia', '$data_waznosci', NULL, NULL, 'Status')"); //dodawanie kolejnych odpowiedzi do bazy
echo "<script type='text/javascript'>alert('Zaproszenie wysłano!');</script>";
}
else
{
echo "<script type='text/javascript'>alert('Zaproszenia NIE wysłano!');</script>";
}
}
}
mysqli_close($sqlc);
}
}
else
{
echo mysqli_connect_errno();
}
?>
Replace below Line. it was crating new array every time with assignment operator
$mail_array=array($licznik => $mail);
//change this line to
$mail_array[$licznik]=$mail;
I want to have the ability to show all the entries in a database table and by each one give the user the ability to delete specific ones.
I am currently using a for each loop that loops through the database showcasing each entry.
$result = mysql_query("SELECT * FROM KeepScores");
$fields_num = mysql_num_fields($result);
echo "<table><tr>";
// printing table headers
echo "<td>Recent Posts</td>";
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
How would to add a delete button that appears by each one and removes the entry from the database table?
You can do it with forms:
//main.php
<?php $result = mysql_query("SELECT * FROM KeepScores"); ?>
<table>
<tr>
<td>Recent Posts</td>
</tr>
<?php while($row = mysql_fetch_array($result)) : ?>
<tr>
<td><?php echo $row['field1']; ?></td>
<td><?php echo $row['field2']; ?></td>
<!-- and so on -->
<td>
<form action="delete.php" method="post">
<input type="hidden" name="delete_id" value="<?php echo $row['id']; ?>" />
<input type="submit" value="Delete" />
</form>
</td>
</tr>
<?php endwhile; ?>
</table>
//delete.php:
<?php
if(isset($_POST['delete_id'] && !empty($_POST['delete_id']))) {
$delete_id = mysql_real_escape_string($_POST['delete_id']);
mysql_query("DELETE FROM KeepScores WHERE `id`=".$delete_id);
header('Location: main.php');
}
Or you can do it with jQuery and AJAX:
//main.php
<?php $result = mysql_query("SELECT * FROM KeepScores"); ?>
<table>
<tr>
<td>Recent Posts</td>
</tr>
<?php while($row = mysql_fetch_array($result)) : ?>
<tr id="<?php echo $row['id']; ?>">
<td><?php echo $row['field1']; ?></td>
<td><?php echo $row['field2']; ?></td>
<!-- and so on -->
<td>
<button class="del_btn" rel="<?php echo $row['id']; ?>">Delete</button>
</td>
</tr>
<?php endwhile; ?>
</table>
<script>
$(document).ready(function(){
$('.del_btn').click(function(){
var del_id = $(this).attr('rel');
$.post('delete.php', {delete_id:del_id}, function(data) {
if(data == 'true') {
$('#'+del_id).remove();
} else {
alert('Could not delete!');
}
});
});
});
</script>
//delete.php
<?php
if(isset($_POST['delete_id'] && !empty($_POST['delete_id']))) {
$delete_id = mysql_real_escape_string($_POST['delete_id']);
$result = mysql_query("DELETE FROM KeepScores WHERE `id`=".$delete_id);
if($result !== false) {
echo 'true';
}
}
It's all untested and sure needs some adjustment for your specific project, but I think you get the idea and I hope it helps.
Next time, please post your schema if you ask stuff about database.
I thought I would improve on this a little bit by wrapping the delete post in a class and function. I was having the same problem. and this worked great for me. Thanks again # Quasdunk
<?php
// Class to hold the remove post function
class someClass{
//Function for removing the post
function removePost(){
if(isset($_POST['delete_id']) && (!empty($_POST['delete_id']))) {
$delete_id = mysql_real_escape_string($_POST['delete_id']);
$result = mysql_query("DELETE FROM post WHERE post_id='".$delete_id."' AND post_member='" . $_SESSION['SESS_USER'] . "'");
if($result !== false) {
echo 'true';
}
}
}
}
if(isset($_SESSION['SESS_MEMBER_ID'])){
$member = $_SESSION['SESS_USER'];
$res = mysql_query("SELECT * FROM post WHERE post_member='$member' ORDER BY timestamp DESC") or die(mysql_error());
$i = new someClass;
while($row = mysql_fetch_array($res)){
echo '<div style="width:100%;margin:0 auto;border-top:thin solid #000;">';
echo '<div style="width:600px;margin:0 auto;padding:20px;">';
echo $row['post_text'] . '<br>';
$postID = $row['post_id'];
echo '<div style="border-top:thin solid #000;padding:10px;margin-top:5px;background-color:#CCC;">';
echo 'You posted this on: ' . $row['post_date'] . '#' . $row['post_time'];
echo '<div style="float:right;">
<form method="post" action="'. $i->removePost() .'">
<input type="hidden" name="delete_id" value="'.$row['post_id'].'" >
<input type="submit" value="Delete Post">
</form>
</div>';
echo '</div>';
echo '</div>';
echo '</div>';
}
}
?>
Produce a key to each table, using jquery,then link it to a php file which an accept the key and delete from the specific table (which also can be passed through jquery)