why does mymysqli delete button doesn't work? - php

I am trying to delete a product from the table, but it does not work.
Is the script wrong? How can I correct it?
include_once('connection.php');
include_once('functions.php');
if(isset($_POST['delete'])){
mysqli_query( $conDB, "DELETE FROM products WHERE name='$_POST[hidden]'");
};
$page = (int)(!isset($_GET["page"]) ? 1 : $_GET["page"]);
if ($page <= 0) $page = 1;
$per_page = 10; // Set how many records do you want to display per page.
$startpoint = ($page * $per_page) - $per_page;
$statement = "products ORDER BY id DESC";
$results = mysqli_query($conDB, "SELECT * FROM {$statement} LIMIT {$startpoint} , {$per_page}");
if (mysqli_num_rows($results) != 0) {
while ($row = mysqli_fetch_array($results)) {
$name = $row['name'];
?>
<tr>
<td align="left" colspan='2' ><big style="color:red" ><b><?php echo $row['name']?></b></big><td>
</tr>
<tr>
<td align="left" colspan='2'><big style="color:333333"><b><?php echo $row['category']?></b> / <?php echo $row['subcategory']?></big></td>
</tr>
<tr>
<td style="vertical-align:top" >
<?php echo "<img border=3 width= 300px height =250px src=\"products/" . $row['picture']>?>"<br />
</td>
<td style="vertical-align:top">
<?php echo nl2br($row['description'])?>
</td>
</tr>
<tr>
<td> <input type="hidden" name="hidden" value="$name" ><input type="submit" name="delete" onClick='return confirmDelete()' value='Delete Product'></td>
When I delete the "delete product" the confirmation will show if I will delete it. but after the confirmation. it does not delete the selected row from the table.
There is no show of error from php after the confirmation. Why is it happening and
how can I fix it?

Looking at the hidden value, it seems its not written properly in the markup:
<input type="hidden" name="hidden" value="$name" >
<!-- ^ literal string, not a variable value -->
Should be:
<input type="hidden" name="hidden" value="<?php echo $name; ?>" />
Sidenote: Since you're already using mysqli, why not utilize prepared statements.
if(isset($_POST['delete'])) {
$delete = $_POST['delete'];
$del = $conDB->prepare('DELETE FROM products WHERE name = ?');
$del->bind_param('s', $delete);
$del->execute();
}
I suggest do it like this, remove the hidden input and use this instead:
<button type="submit" name="delete" onClick='return confirmDelete()' value="<?php echo $row['id']; ?>">Delete Product</button>

Just correct your input hidden field:
<input type="hidden" name="hidden" value="<?php echo $name; ?>" >

Try
echo "DELETE FROM products WHERE name='$_POST[hidden]'";
and then try executing the sql or modify
"DELETE FROM products WHERE name='".$_POST[hidden]."'"

Related

Using a button to move to the next record

I would like to move to the next record using an HTML button. I have tried for and foreach SQL statements I have also tried using num rows and calling the cells values.
$id=$_get['Badge ID Number'];
$sqlkc = "select * from Badges.BADGEMSTR";
$result = mysqli_query($sqlc, $sqlkc);
if($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$BIDN= $row['Badge ID Number'];
$Fname= $row['First Name'];
$MI= $row['Middle Initial'];
$Lname= $row['Last Name'];
}
$next = next($result);
?>
Thank you in advance for your help.
Forgot to add my current onclick command
onclick='<?php echo $next;?>'
All HTML code as requested
<table style="background-color: tan; margin: auto">
<tr>
<td><input type="text" value="<?php echo $BIDN;?>"/>
<input type="text" value="01"/></td>
</tr>
<tr>
<td>
<input type="text" value="<?php echo $Fname;?>"/>
<input type="text" value="<?php echo $MI;?>"/>
<input type="text" value="<?php echo $Lname;?>"/>
</td>
</tr>
<tr>
<td><input type="button" value="Next" style="float: right" onclick='<?php echo $next;?>'/></td>
<td><input type="button" value="Last" style="float: right" onclick='<?php echo $nextid;?>'/></td>
</tr>
</table>
I hope I understood the question right.
Since you would pass the Badge ID between pages, you should use prepared statements as such. So, taking the Badge ID Number is Integer, your PHP code should look like this:
$link = mysqli_connect(hostname,username,password,dbname);
if (isset($_GET['last_id'])) {
// Last row in the table
$stmt = mysqli_prepare($link, 'SELECT * FROM Badges.BADGEMSTR ORDER BY `Badge ID Number` DESC LIMIT 1');
} elseif (isset($_GET['id'])) {
// Specific row in the table
$stmt = mysqli_prepare($link, 'SELECT * FROM Badges.BADGEMSTR WHERE `Badge ID Number`>? ORDER BY Rb ASC LIMIT 1');
$stmt->bind_param('d',$_GET['id']);
} else {
// First row in the table
$stmt = mysqli_prepare($link, 'SELECT * FROM Badges.BADGEMSTR ORDER BY `Badge ID Number` ASC LIMIT 1');
}
// Execute the query and get the results
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_array();
// Initialize variables from the given $row
$BIDN = $row['Badge ID Number'];
$Fname = $row['First Name'];
$MI = $row['Middle Initial'];
$Lname = $row['Last Name'];
As for the HTML code, it's a bit unclear from the question, but I think something like this would be in order:
<html>
<head></head>
<body>
<table style="background-color: tan; margin: auto">
<tr>
<td><?php echo htmlspecialchars($BIDN, ENT_QUOTES); ?></td>
<td>01</td>
</tr>
<tr>
<td><?php echo htmlspecialchars($Fname, ENT_QUOTES); ?></td>
<td><?php echo htmlspecialchars($MI, ENT_QUOTES); ?></td>
<td><?php echo htmlspecialchars($Lname, ENT_QUOTES); ?></td>
</tr>
<tr>
<td>
Next
</td>
<td>
Last
</td>
</tr>
</table>
</body>
</html>
You also don't have to use inputs to display the results, you could show them between TD elements in the table like <td><?php echo $row['Badge ID Number']; ?>.

Updating a field from an sql table from php

I have a table with more columns. On one column I have 3 buttons for each row with different queries associated. When I click one of the buttons, field in the table from my database should update.The problem is that when I click on a button on any row in the table, it updates only the field from the first row.For example, I have a table with 10 rows.If I click one of the buttons on the 10th row IT will update my first row, not the 10th one as I want. Is there any possibility to solve this?
This is the code..I'm sorry it is too long:
<?php
$query = "SELECT * FROM masculin ORDER BY id_concurent";
$result = mysqli_query($link ,$query);
$row = mysqli_fetch_assoc($result);
if(isset($_POST['locul1']))
{
$sql = "UPDATE masculin SET Premiu=1 WHERE CNP='".$row['CNP']."'";
mysqli_query($link,$sql);
header("Location:administrare.php");
}
else if(isset($_POST['locul2']))
{
$sql = "UPDATE masculin SET Premiu=2 WHERE CNP='".$row['CNP']."'";
mysqli_query($link,$sql);
header("Location:administrare.php");
}
else if(isset($_POST['locul3']))
{
$sql = "UPDATE masculin SET Premiu=3 WHERE CNP='".$row['CNP']."'";
mysqli_query($link,$sql);
header("Location:administrare.php");
} ?>
<u><i><h1 align="center">Administrare concurenti</h1></i></u>
<u><i><h2>MASCULIN</h2></i></u>
<?php
$query = "SELECT * FROM masculin ORDER BY id_concurent";
$result = mysqli_query($link ,$query);
if (mysqli_num_rows($result) == 0) {
echo 'Inca nu s-a inscris niciun concurent.';
} else {
?>
<table width="100%">
<tr>
<th>Nr.<br />concurs</th>
<th>Nume</th>
<th>Prenume</th>
<th>CNP</th>
<th>Categoria</th>
<th>Varsta</th>
<th>Premiu</th>
<th>Modifica<br />rezultat</th>
<th>Descalifica</th>
</tr>
<?php while($row = mysqli_fetch_assoc($result)){ ?>
<tr>
<?php
$query1="SELECT id_concurent FROM concurenti WHERE CNP='".$row['CNP']."'";
$result1=mysqli_query($link,$query1);
$nr_conc=mysqli_fetch_assoc($result1);
?>
<td> <?php echo $nr_conc['id_concurent'] ?> </td>
<td> <?php echo $row['Nume'] ?> </td>
<td> <?php echo $row['Prenume'] ?> </td>
<td> <?php echo $row['CNP'] ?> </td>
<td> <?php echo $row['Categorie'] ?> </td>
<td> <?php echo $row['Varsta'] ?> </td>
<td> <?php echo $row['Premiu'] ?> </td>
<td>
<form action="administrare.php" method="post">
<input type="submit" name="locul1" value="Premiul 1">
<input type="submit" name="locul2" value="Premiul 2">
<input type="submit" name="locul3" value="Premiul 3">
</form>
</td>
</tr>
<?php } ?>
</table> <?php } ?>
for updated the da tbale row when you submit the values related to a html table row you should add and hidden input with the value that let you reach the correct row eg:
<form action="administrare.php" method="post">
<input type="submit" name="locul1" value="Premiul 1">
<input type="submit" name="locul2" value="Premiul 2">
<input type="submit" name="locul3" value="Premiul 3">
<input type="hidden" name="CNP" value="<?php echo $row['CNP'] ?>">
</form>
and in your sql updated query add the POST value related to the row
$sql = "UPDATE masculin SET Premiu=1 WHERE CNP='".$_POST['CNP']. "'";

Insert to database when the button is click

im currently displaying all the information from the table product in a tabular format, i have a button ADD which when click should add only the id, name and price from the table product to the table product_add in the same database. but my problem is that when i click on the button ADD, nothing is entered in the product_add table.
<?php
include'connect.php';
$image =$_GET['image'];
$id =$_GET['id'];
$name =$_GET['name'];
$price=$_GET['price'];
$sql="SELECT * FROM product";
$result = mysql_query($sql);
if($result>0)
{
?>
<form method="post" id="form" name="form">
<table border='1'>
<?php
while ($row = mysql_fetch_array($result))
{
extract($row);
?>
<tr>
<td><?php echo $row['id']?></td>
<td><img src=<?php echo $row['image'] ?> /></td>
<td><?php echo $row['name']?></td>
<td><?php echo $row['price']?></td>
<td><input type='button' value='ADD' id="insert" name="insert"/></td>
</tr>
<?php
}
?>
</table>
</form>
<?php
}
if(isset($_REQUEST['insert']))
{
$insert = "INSERT INTO product_add(id, name, price)
VALUES ('$row[id]','$row['name']','$row['price']')";
$insertQuery=mysql_query($insert);
}
?>
</body>
</html>
I have updated the codes as shown below but the last row from the table product is being added to the table product_add. I want to add only a specific row when i click on the button submit.
<?php
include'connect.php';
$image = isset($_GET['image']) ? $_GET['image'] : "";
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$price= isset($_GET['price']) ? $_GET['price'] : "";
$sql="SELECT * FROM product";
$result = mysql_query($sql);
if($result>0){
?>
<form method="POST" id="form" name="form">
<table border='1'>
<tr>
<th>Id</th>
<th>Image</th>
<th>Name</th>
<th>Price MUR</th>
</tr>
<?php
while ($row = mysql_fetch_array($result)){
extract($row);
?>
<tr>
<td><input name="id" value="<?php echo htmlspecialchars($row['id']); ?>">
</td>
<td><img src=<?php echo $row['image'] ?> width='120' height='100'/></td>
<td><input name="name" value="<?php echo htmlspecialchars($row['name']);
?>"></td>
<td><input name="price" value="<?php echo htmlspecialchars($row['price']);
?>"></td>
<td>
<input id="submit" type="submit" name="submit" value='Add to cart' />
</td>
</tr>
<?php
}
?>
</table>
</form>
<?php
}
if (isset($_REQUEST['submit']))
{
$insert = "INSERT INTO product_add(id, name, price) VALUES ('$id',
'$name','$price')";
$insertQuery=mysql_query($insert);
}
?>
Apart from the method (if your form uses POST, you should use $_POST in php), you do not have any form fields.
For example:
<?php echo $row['id']?>
Should be something like:
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
and:
<?php echo $row['name']?>
should be:
<input name="name" value="<?php echo htmlspecialchars($row['name']); ?>">
etc.
You should also switch to PDO or mysqli and prepared statements as the code you have now is vulnerable to sql injection. And ID's in html need to be unique.
One point is, you have multiple
<input type='button' ...>
with the same id="insert". ids must be unique within a web page.
The other thing is, you need a submit input to send the form
<input type="submit" ...>
From Submit Button state (type=submit)
The input element represents a button that, when activated, submits the form.
With <input type='button' ...> nothing happens, because it has no default action, see Button state (type=button)
The input element represents a button with no default behavior.
If you want an <input type='button' ...> to submit the form, you must do so by using some Javascript code.
One idea is to load content once the button is clicked.
js
$("#button").click(function() {
$("#holder").load("insert.php");
});
insert.php
$db->query("INSERT INTO table VALUES('one','two','three')");

Records not getting inserted in ascending order

I'm having a strange problem. I have a HTML page with PHP code which inserts data to a MySQL database. The data gets saved to the DB without any errors but in an incorrect order.
Here's a screenshot. The table on the right side displays the existing records. The first 2 records are shown correctly.
But when I save more records, it displays like this.
Even in the MySQL table, the records are inserted that way.
I'm not sure where exactly the problem is so I've shown the whole code for the page below. I've commented what each code block does. Please comment if you need me to clarify something.
The Location ID is an auto-generated code.
<html>
<head>
<script language="javascript">
function SelectAll(source)
{ //The code for the 'Select All' checkbox
checkboxes = document.getElementsByTagName("input");
for(var i in checkboxes)
{
if(checkboxes[i].type == 'checkbox')
{
checkboxes[i].checked = source.checked;
}
}
}
</script>
</head>
<body>
<?php
//Database connection initialization
require_once("db_handler.php");
$conn = iniCon();
$db = selectDB($conn);
/* Generating the new Location ID */
$query = "SELECT LID FROM locations ORDER BY LID DESC LIMIT 1";
$result = mysql_query($query, $conn);
$row = mysql_fetch_array($result);
$last_id = $row['LID'];
$id_letter = substr($last_id, 0, 1);
$id_num = substr($last_id, 1) + 1;
$id_num = str_pad($id_num, 3, "0", STR_PAD_LEFT);
//$id_num = sprintf("%03d", $id_num);
$new_id = $id_letter . $id_num;
/* Displaying the exsisting locations */
$query = "SELECT * FROM locations";
$result = mysql_query($query, $conn);
$count = mysql_num_rows($result);
?>
<! The table which displays the existing records >
<div id="display">
<b>Locations</b><br/><br/>
<form name="displayLocs" action="<?php echo $PHP_SELF; ?>" method="post" >
<table border="1">
<tr>
<th>Location ID</th>
<th>Code</th>
<th>Location</th>
<th><i>Delete</i></th>
</tr>
<?php
while($row = mysql_fetch_array($result))
{
?>
<tr>
<td align="center"><? echo $row["LID"]; ?></td>
<td align="center"><? echo $row["Code"]; ?></td>
<td><? echo $row["Location"]; ?></td>
<td align="center"><input type="checkbox" name="checkbox[]" value="<? echo $row["LID"]; ?>" /></td>
</tr>
<?php
}
?>
</table>
<br/>
<div id="buttons2">
<input type="checkbox" onclick="SelectAll(this)" />Select All <input type="reset" value="Clear" /> <input type="submit" value="Delete" name="deletebtn" />
</div>
</form>
</div>
<! New record saving area >
<b id="loc_caption_1">Enter a new location</b>
<div id="loca">
<form name="locForm" action="<?php echo $PHP_SELF; ?>" method="post" >
<table width="300" border="0">
<tr>
<td>Location ID</td>
<td><input type="text" name="lid" readonly="readonly" value="<?php echo $new_id; ?>" style="text-align:right" /></td>
</tr>
<tr>
<td>Code</td>
<td><input type="text" name="code" style="text-align:right" /></td>
</tr>
<tr>
<td>Location</td>
<td><input type="text" name="loc" style="text-align:right" /></td>
</tr>
</table>
</div>
<br/>
<div id="buttons">
<input type="reset" value="Clear" /> <input type="submit" value="Save" name="savebtn" />
</div>
</form>
<?php
//Saving record
if(isset($_POST["savebtn"]))
{
$id = $_POST["lid"];
$code = $_POST["code"];
$location = $_POST["loc"];
$query = "INSERT INTO locations(LID, Code, Location) VALUES('$id', '$code', '$location')";
$result = mysql_query($query, $conn);
if (!$result)
{
die("Error " . mysql_error());
}
else
{
echo "<br/><br/>";
echo "<strong>1 record added successfully!</strong>";
echo "<meta http-equiv=\"refresh\" content=\"3;URL=locations.php\">";
}
mysql_close($conn);
}
//Deleting selected records
if(isset($_POST["deletebtn"]))
{
for($i = 0; $i < $count; $i++)
{
$del_id = $_POST["checkbox"][$i];
$query = "DELETE FROM locations WHERE LID = '$del_id' ";
$result = mysql_query($query, $conn);
}
if (!$result)
{
die("Error " . mysql_error());
}
else
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=locations.php\">";
}
mysql_close($conn);
}
?>
</body>
</html>
Can anyone please tell me what is causing this and how to rectify it.
Thank you.
The records in the database are stored in the database in no particular order (well, there's some order to it, but it's up to the engine to determine it). If you want to get the results in a particular order, then you need to explicitly specify it when querying the data. In your case, make this change:
/* Displaying the exsisting locations */
$query = "SELECT * FROM locations ORDER BY lid";
$result = mysql_query($query, $conn);

php $_get variable gone after submitting form

my problem goes like this:
my home page has tables with rows pulled from the database (while loops)
each row has a - cell in which he can add an event to that specific row
in order to do that i send the row id as a $_GET variable from the home page table
and in the "add event" page i store it as a variable
but when i submit my addevent form without filling it properly (as i coded) it simply refreshes the form only without the row id in the url therefor also the query i do in the beginning of the page for pulling the row data can no longer execute and that pops a PHP error
for the id variable which i sign it the $_GET and the query (mysql fetch array).
also of course all the data which i display in the form from that query is gone.
any suggestions on how to approach this ? thanks in advance, Regards.
EDIT:** kill the new guy! -Sorry i guess
home page where i send the id :
$sql = "SELECT * FROM alarms WHERE alarmstatus = 'OFF' and starttime='::' ORDER BY clientid ASC";
$query = mysql_query($sql);
echo "<table cellpadding='1px' border='1px' bordercolor='#0066FF' cellspacing='0'>
<form action='hpage.php' method='get'>";
while($fetch = mysql_fetch_array($query)) {
echo "<tr>
<td>
".$fetch['clientid']."</td>
<td>".$fetch['controller']."</td>
<td>".$fetch['typeid']."</td>
<td style='color: red'>".$fetch['alarmstatus']."</td>
<td>".$fetch['starttime']."</td>
<td>".$fetch['endtime']."</td>
<td><a href='includes/editalarm.php?id=".$fetch['id']."'>Edit</a></td>
<td><a href='includes/addevent.php?id=".$fetch['id']."'>Add event</a></td>
<td><a href='includes/deletealarm.php?id=".$fetch['id']."'>Delete</a></td>
</tr>";
}
the add event where i get the variable and make the query:
$alarmid = $_GET['id'];
$sql = "SELECT * FROM alarms WHERE id=".$alarmid;
$query = mysql_query($sql);
$fetch = mysql_fetch_array($query);
?>
the form:
<table cellpadding="2px" cellspacing="0" >
<form action="addevent.php" method="post">
<tr>
<td>סניף:</td>
<td><input style="width:200px; background-color: #d6d6d6;" readonly name="client" value="<?php echo $fetch['clientid']; ?>" /></td>
</tr>
<tr>
<td>בקר:</td>
<td><input style="width:200px; background-color: #d6d6d6;" readonly name="controller" value="<?php echo $fetch['controller']; ?>" /></td>
</tr>
<tr>
<td>אזעקה:</td>
<td><input style="width:200px; background-color: #d6d6d6;" readonly name="controller" value="<?php echo $fetch['typeid']; ?>" /></td>
</tr>
<tr>
<td>מוקדן:</td>
<td>
<?php
$sql = "SELECT * FROM users WHERE privilege = '2'";
$query = mysql_query($sql);
echo "<select name='user' style='width:207px;'>";
echo "<option>..</option>";
while ($fetch2 = mysql_fetch_array($query)){
echo "<option>".$fetch2['username']."</option>";
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td>איש קשר:</td>
<td><input type="text" name="contact" /></td>
</tr>
<tr>
<td>הודעה:</td>
<td><input type="text" style="width:200px; height:100px" name="message" /></td>
</tr>
<tr>
<td>תשובה:</td>
<td><input type="text" style="width:200px; height:100px" name="answer" /></td>
</tr>
<tr>
<td>שעה:</td>
<td>
<select name="eventhour">
<option value ="default"></option>
<?php
for($i = 0; $i<60; $i++){
$value = $i;
if($i<=9){
$value= "0".$i;
}
echo "<option>".$value."</option>";
}
?>
</select>
<select name="eventminute">
<option value ="default"></option>
<?php
for($i = 0; $i<24; $i++){
$value = $i;
if($i<=9){
$value= "0".$i;
}
echo "<option>".$value."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" name="save" value="שמור" />
<input type="submit" name="cancell" value="בטל" />
</td>
<td></td>
</tr>
</form>
Your form action is POST. If you change that to GET then you will have the form as $_GET.

Categories