I have a delete button which when clicked it prompts user for conformation. It suggets it is working but when I check the database the data is still there.
How do I get my delete button to remove data from the database?
<?php
// build query
$sql= "SELECT blogID, title, made_by, description FROM blogs";
// execute query
$res=$mysqli->query($sql);
// get multiple results
while($row = $res->fetch_assoc()){
$blogID=$row['blogID'];
$title=$row['title'];
$made_by=$row['made_by'];
$description=$row['description'];
?>
<form action = "post_action.php" method="POST">
<div style="text-align:left">
<div class="row">
<div class="leftcolumn">
<div class="card">
<td><?php print($title);?></td><br>
<td> <?php print($description);?> </td> <br>
<td><?php print($made_by);?> </td><br>
<?//Create edit, comment and delete buttons for each blog?>
<button onclick="window.location.href = 'edit_blog.php';">Edit Blog </button>
<input type = "hidden" name="blogID" value= "<?php print($blogID);?>" >
<input type="submit" name="action" value="Insert Comment"/>
<input type="submit" onclick="deleteme(<?php echo $row['blogID']; ?>);" name="action" value="Remove Blog"/>
<? //Javascript code?>
<script language="javascript"> //inserts javascript code
function deleteme(delid)
{
if(confirm("You're about to delete this blog. Click OK to continue or click cancel.")){ //opens an alert window asking the user if they're they want ot remove the blog
window.location.href='post_action.php?del_id=' +delid+''; //If they click OK then it'll run the delete function on post_action.php
return true;
}
}
</script> <?//ends javascript code ?>
</form>
</div>
This is post_action.php
<?php
include("_config.php");
debug($_POST);
if($_POST['action'] == "Remove Blog"){
$query = "DELETE FROM blogs WHERE blogID={$_POST['blogID']} LIMIT 1";
header ("Location: blog_test.php");
}
?>
Because you did not execute your delete action. Execute your delete query to remove the data to your database.
$mysqli -> query($query)
The problem is in $_POST['blogID'].
You are redirecting the user and passing the blog id in the query string, so it should be $_GET. Also the key is del_id and not blogID.
So in post_action.php, do
<?php
include("_config.php");
debug($_POST);
if($_POST['action'] == "Remove Blog"){
$query = "DELETE FROM blogs WHERE blogID={$_GET['del_id']} LIMIT 1";
header ("Location: blog_test.php");
}
?>
PS: I am really worried about if you should delete something this way.
Related
I am working on project and came across the problem: When i click a button on the e.g. //website/manageuser.php I want the value of the button in the //website/edituser.php
I tried using the <value> tag in a button but failed. I wasn't able to manage to transfer the value through the files.
My manageuser.php looks like this:
After i press the e.g. "Delete" button, i get forwarded to the /deleteuser.php where I want to print the value behind the button. Unfortunatly, it isn't working with a StackOverflow Javascript script.
Image of my /deleteuser.php:
Code of the important part of manageuser.php:
<table>
<tr>
<?php
$query = "select * from users";
$records = mysqli_query($con, $query);
while($data = mysqli_fetch_array($records))
{
?>
<th>
<p/>
<?php
print($data["full_name"]);
?>
<button type="button" value=" <?php print($data['full_name']) ?>" onclick="window.location.href='./edituser.php'">Edit</button>
<button type="button" onclick="window.location.href='./deleteuser.php'"> Delete </button>
</th>
<?php
}
?>
</tr>
</table>
Code of the important part of deleteuser.php:
<!DOCTYPE html>
<html>
<body>
<script>
var str1 = document.getElementById("btn").innerHTML;
var str2 = document.getElementById("btn").value;
document.write("Button text: "+str1);
document.write("<br>Button value: "+str2);
</script>
</body>
</html>
You don't need the value. Just append the value from $data as a query parameter to the URL.
<button type="button" onclick="window.location.href='./deleteuser.php?id=<?php echo $data['id'] ?>"> Delete </button>
Then in deleteuser.php you can use $_GET['id'].
I made ajax script for delete button and have data attribute based on id on the table in database. This is the HTML :
<textarea name="komentar" id="komentar" cols="30" rows="10"></textarea><br>
<input type="submit" name="submit" id="submit" value="Submit"><br>
<br><br><hr><br>
<!-- Komentar akan ada di dalam sini -->
<div id="komentar_wrapper">
<?php
include_once 'db.php';
$query = "SELECT * FROM komentar ORDER BY id DESC";
$show_comments = mysqli_query($db, $query);
foreach ($show_comments as $comment) { ?>
<p id="komentar_<?php echo $comment['id']; ?>"><?php echo $comment['komentar']; ?>
<!-- data-id-> data attribute, buat spesifik id mana yang mau di hapus -->
<button id="button_hapus" class="hapus_komentar" data-id="<?php echo $comment['id']; ?>">Delete</button>
</p>
<?php } ?>
</div>
And when i try to console the data-id, it wont show the value on console. This is the script :
$(".hapus_komentar").on("click", function() {
console.log($(this).attr("data-id"));
});
When i click the button it say undefined, i think it should print the id based on button data-id
try this i have prepared a demo code for you and runs ok
<?php
$as = array(1,2,3,4,5,6,7);
foreach ($as as $comment) { ?>
<p id="komentar_<?php echo $comment ?>"><?php echo $comment; ?>
<button id="button_hapus" class="hapus_komentar" data-id="<?php echo $comment; ?>">Delete</button>
</p>
<?php
}
?>
<script type="text/javascript">
$(".hapus_komentar").on("click", function() {
alert($(this).attr("data-id"));
//console.log($(this).attr("data-id"));
});
</script>
use Jquery.data(). and use event delegation since your button is generated dynamically.
$(document).on("click",".hapus_komentar",function() {
console.log($(this).data("id"));
});
You can use $(this).data("id") to get the id.
Your code is correct. Just check in HTML weather data-id will have value or not. Maybe that's the reason you are not getting proper value. As well you have taken that button in the loop so make sure on individual button click you will get all buttons data-id.
$(".hapus_komentar").on("click", function() {
console.log($(this).data("id"));
});
now use this.
$(document).on("click",".hapus_komentar",function() {
console.log($(this).attr("data-id"));
});
I'm working on a project of a website which shows a chart. User should be able to change a displayed chart (without changing the website) by clicking one of 'Available sensors' from dropdown options. Dropdown connects to MySQL database with used sensors. The sensor's id is assigned to HTML-input ID and its name is assigned to input value.
My intension is to use sensor ID in another data.php file which is responsible for connecting to tables (MySQL) with data collected by sensors. This ID would tell to which of the tables this programm should connect.
At the moment JS script's task is to alert an ID of the chosen sensor when it's clicked on the dropdown menu. Instead of a number I get a message saying 'undefined'. Eventually it would transfer the stored id to the mentioned data.php file.
Could you please tell me whether it's necessary to use AJAX in this case or what's a possible reason of this error in my code?
I also tried to use button insted of input. When clicking on sensors names on dropdown I've received only messages with '1'. However assigning sensorName worked out in both cases. Sensors ID is stored as INT, name as VARCHAR in MySQL table.
Thank you in advance for your help :)
<div id="header_btn" class="dropdown">
<input type="submit" id="btn" value="Available sensors" class="btn btn-success" />
<div class="dropdown-content">
<?php
include("config.php");
$sql = "SELECT * FROM sensors";
$result = $db->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$sensorID = $row["id"];
$sensorName = $row["WebName"];
?>
<input onclick="changeSensorID(this.value)" onmouseover="this.style.textDecoration='underline'" onmouseout="this.style.textDecoration='none'" class="btn_drop" id="<?php echo $sensorID ?>" value="<?php echo $sensorName ?>" /></a>
<?php
}
}
?>
</div>
<script>
function changeSensorID() {
var sensorID = document.getElementsByClassName("btn_drop").id;
alert(sensorID);
};
</script>
</div>
please check this code, working fine
<input type="submit" id="btn" value="Available sensors" class="btn btn-success" />
<div class="dropdown-content">
<?php
include("config.php");
$sql = "SELECT * FROM sensors";
$result = $db->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$sensorID = $row["id"];
$sensorName = $row["WebName"];
?><input onclick="changeSensorID(event)" onmouseover="this.style.textDecoration='underline'"
onmouseout="this.style.textDecoration='none'" class="btn_drop" id="<?php echo $sensorID ?>"
value="<?php echo $sensorName ?>" /></a>
<?php
}
}
?>
</div>
<script >
function changeSensorID(event){
var sensorID = event.target.id;
alert(sensorID);
}
</script>
</div>
getElementsByClassName returns array of at least one item if found any. You have to provide index of element that you want to use.
Example
var sensorID = document.getElementsByClassName("btn_drop")[0].id;
I have been working on this for weeks now trying to find the fix. Here is my problem I have a dropdown bar on my navigation which contains my login. I need it to disappear and be replaced with the welcome message. I can't even get it to disappear the simple way with just the forum
if(session is on) {
view welcome and disappear form
}
else
{
this is suppose to bring up the form but it doesn't disapear in the first place.
}
I don't know if I'm doing this all wrong. Below is the code for my navigation on my php will not post the css. Also the welcome and logout text is within all the other text in the page and I can't seem to move it. It would be nice if I could replace it with the login dropdown. The code is below.
//this is the navigation and the dropdown login with the login fourm contained.
<ul>
<li><a class="active" href="index.php">Home</a></li>
<li>Messages</li>
<li>ASK</li>
<li>Cloud Access</li>
<li>Gallery</li>
<ul style="float:right;list-style-type:none;padding-right:150px;">
<div class="dropdown">
Login
<div class="dropdown-content">
<div id="Register">
<form action="" method="POST">
<p><label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" /></p>
<p><label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" /></p>
<a class="btn" href="register.php">Signup</a>
<input class="btn register" type="submit" name="submit" value="Login" />
</form>
</div>
</div>
</div>
<li>About</li>
</ul>
</ul>
// this is the php which should make a session and make the fourm disapear. I need the fourm and the dropdown to disapear and be placed with text.
<?php
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
<?php
session_start();
require('connect.php');
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM `user` WHERE username='$username' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
will be created for the user.
if ($count == 1){
$_SESSION['username'] = $username;
}else{
echo "<p id='btn' >sorry please cheach if that is correct .</p>";
}
}
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo '<div id="password">';
echo "Welcome " . $username . " ";
echo "<p>This is the Members Area<p>";
echo "<a href='logout.php'>Logout</a>";
echo '</div>';
}else{
}
?>
I hope I'm clear of what I said. But if there are any questions please reply below. Thank you and it all make my week if I can get this little problem resolved.
You can output the form only if the session variable is not set using PHP,
Example:
Login
<?php
if (!isset($_SESSION['username'])) // the session variable is not set
{
?>
<div class="dropdown-content">
<div id="Register">
<form>
// form content here
</form>
</div>
</div>
<?php
}
?>
I have a script that I would like to have run using jQuery and PHP. After a user logs in, they fill out a form and hit the 'save' button. The jQuery attaches a click event which runs the PHP script. I've got console logs at certain break points and I'm showing that my script is actually stopping at a certain point, however, I have no idea why.
TABLE CREATION AND DATABASE CONNECTION
$create_table_scenarios = "CREATE TABLE IF NOT EXISTS $scenarios(id VARCHAR(25), PRIMARY KEY(id))";
mysqli_query($connect, $create_table_scenarios);
I know that the connection is being made and the table is being created because it shows up in the database.
THE FORM
<form id="scenario_builder" method="post" action"../php/processing.php">
<div id="form_general" class="form_view">
<h3>General Info</h3>
<div class="half">
<fieldset for="center_menu">
<label>Center:</label>
<div class="select" name="center_menu" id="center_menu">
<div class="arrow"></div>
<div class="option-menu">
<div class="option"></div>
<?php
$query = "SELECT * FROM $centers";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($result)){
$center_name = "{$row['center']}";
echo "<div class='option'><input type='hidden' name='center' id='center' value='" .$center_name ."' />" .$center_name ."</div>";
}
?>
</div>
</div>
</div>
</fieldset>
</div>
</div>
<input type="submit" name="save" id="save" class="button" value="Save" />
</form>
PROCESSOR
ob_start();
require("../includes/header.php");
if($_SERVER["REQUEST_METHOD"] == "POST"){
$center = $_POST["center"];
$query = "INSERT INTO `$scenarios`(`id`) VALUES('" .$center ."')";
mysqli_query($connect, $query);
}
ob_clean();
echo json_encode(array("success" => 1));
jQUERY
$("input[id='save']").on("click", function(){
console.log("Save clicked");
$.post("..php/processing.php", {}, function(response){
if(response.success == "1"){
console.log("Data entered.");
}
else{
console.log("Data not entered.");
}
}, "json");
})
The only console message I'm getting is the "Save clicked" one. So, for some reason, the $.post function isn't running. Can someone show me why based on the code I've provided? On a different note, yes, I understand that my queries are vulnerable to injection, I'm just trying to get the basics to work right now.
From what i see you are double submitting the form. You once submit the form due to the form's submit button push and the second time you submit the form with the AJAX request due to the event handler you added to the button. You either let the form submit with a regular POST, or on the submit button press you prevent the event's default behavior and submit the data by AJAX.