I have made a MVC site that is displaying a databases records, each record is printed on its own line with a delete button beside it. I am having some issues with the delete button. When I click the delete button I am trying to sending it to my controller to handle.
The issues I am having are
I cant send the row id from the button.php to the controller (Have a strong suspicion that the code is wrong)
The delet function in the controller doesnt work, in the code below I have hard coded in the row ID that I want to delete but when I click the delete button I get the following error
Syntax error in SQL statement.You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'id=27' at line 1
Button.php
<?php
$result=$itemsDAO->getItems();
foreach ($result as $row) {
$uid = $row['id'];
?>
<form action="index.php" method="post">
<fieldset>
<input id='action' type='hidden' name='action' value='deleteItem' />
<p>
<div class="form-group">
<div class="controls">
<input type="hidden" id="fID" name="uid" value="<?php echo $uid; ?>">
<input type="submit" class="btn btn-success" value="Delete">
</div>
</div>
</p>
</fieldset>
</form>
<?php } ?>
Delete function in the controller
function deleteItem($parameters) {
$id = $parameters["fID"];
if ($this->model->deleteItem( $id )) {
$this->model->hasDeleteFailed = false;
$this->model->setDeleteItemConfirmation();
return (true);
}
else
$this->model->deleteItemError ( DELETE_ITEM_ERROR_STR );
}
Delete SQL
public function deleteItem($id) {
$delId = $id;
$sqlQuery = "DELETE FROM items";
$sqlQuery .= " WHERE id=$delId;";
$result = $this->getDbManager () -> executeQuery ( $sqlQuery );
}
Try this steps :
Check whether $parameters is properly passed to the deleteItem function (use echo $parameters or somthing)
If so check the query (DELETE * FROM 'thetable' WHERE id = $id)
Normally in a MVC site parameters pass through (site_url/controller/method/parameter) url. But while you are using a form, it's need to be a mechanism to capture your form variables.
Related
I'm trying to create a form on a webpage, which takes an id number entered by the user, and deletes the corresponding record in a database. I'm unable to get it working.
This is the delete code which isn't working:
<?php
if (isset($_POST['deleteSubmit'])) {
$details = $conn->real_escape_string($_POST['deleteNum']);
$deleteSQL = "DELETE FROM userName WHERE id = '$details'";
$result = $conn->query($deleteSQL);
if (!$result) {
echo 'Error!';
exit($conn->error);
} else {
header('Location: index.php');
exit;
}
}
?>
<h4>DELETE NAME (DELETE)</h4>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<label for="num">Enter User Reference to be Deleted:</label><br>
<input num="deleteNum"type="number"><br>
<input num="deleteSubmit" type="submit" value="Delete">
</form>
For reference, this is the post code which is working (it's being used to add names to the database):
<?php
if (isset($_POST['nameSubmit'])) {
$details = $conn->real_escape_string($_POST['newName']);
$insertSQL = "INSERT INTO userName (name) VALUES ('$details')";
$result = $conn->query($insertSQL);
if (!$result) {
echo 'Error!';
exit($conn->error);
} else {
header('Location: index.php');
exit;
}
}
?>
<h4>ENTER NAME (POST)</h4>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<label for="fname">Enter Name:</label><br>
<input name="newName"type="text"><br>
<input name="nameSubmit" type="submit" value="Submit">
</form>
The database connection file is being called in both programs and is working for the post.php element, which is why I haven't included it or reference to it.
The database has one table called userName which contains two columns id (which is auto incremented) and name.
I've tried changing some of the syntax on the delete.php file with no success. I've ran the $deleteSQL code directly in my database and it works.
I see no error messages when enter an id and click the delete button.
For anyone who reads this in future, the query was solved by #kenlee;
(1) Change num="deleteSubmit" to name="deleteSubmit"
(2) change num="deleteNum" type="number" to name="deleteNum" type="number"
(3) Please use paratemerized prepared statement in your queries
Im trying to create a button like the one in the youtube commentaries but i cant do it, I tried creating a static variable, so every time i press a button to load more the variable will be increased but it just can be increased once, maybe a for loop can help but i dont have any idea of how to implement it.
(Im loading the ids i have saved in a mysql database but i will change the id for the commentaries i have in other database.) Screen shots:
<title>Pruebas</title>
<center>
<?php
require 'conexion.php';
class Ver_prublicaciones extends Conexion{
public function Ver_prublicaciones(){
parent::__construct();
}
public function Ver($num){
$sql="SELECT * FROM USUARIOS";
$resultNum=$this->con->query($sql)->rowCount();
$sql2="SELECT * FROM USUARIOS LIMIT 0,$num";
$resultCon=$this->con->query($sql2);
$array=$resultCon->fetchAll(PDO::FETCH_ASSOC);
foreach ($array as $value){
echo $value['ID'] . "<br>";
}
}
}
$numero;
$numero=2;
if(isset($_POST['cargar'])){
$numero++;
}
$prueba=new Ver_prublicaciones();
$prueba->Ver($numero);
?>
<form method="post">
<input type="submit" name="cargar" value="Cargar más resultados">
</form>
</center>
You need to pass the current value of $numero to be able to increase it on every click.
PHP
// if we got a numero value posted, use that, otherwise set it to 2 as default
$numero = isset($_POST['numero']) ? $_POST['numero'] : 2;
if(isset($_POST['cargar'])){
$numero++;
}
HTML
<form method="post">
<input type="hidden" name="numero" value="<?= $numero ?>" />
<input type="submit" name="cargar" value="Cargar más resultados">
</form>
Here we added the current value of $numero as a hidden field that gets passed on every click.
I've been having some problems with a bit of PHP running when a form is submitted.
I'm trying to have a variable be determined by which submit button is being pressed and grabbing the $_POST['name'] to carry out some SQL select. There are currently two submit buttons in my form, reading YES and NO.
The problem I'm having is that I keep getting the same answer from my query, but when I test in my database it works just fine. It seems to be something in my if/else statement.
<?php
require_once ("/includes/session.php");
require_once ("/includes/db_connection.php");
require_once ("/includes/functions.php");
require_once ("/includes/validation_functions.php");
if ($_POST['answer1']) {
$chosenAnswer = 1;
} else if ($_POST['answer2']) {
$chosenAnswer = 2;
}
$query = "SELECT questionFlow.NxtQ FROM ";
$query .= "questionFlow WHERE area = '{$_SESSION['probArea']}' ";
$query .= "AND ANSid = '{$chosenAnswer}' AND Qid = '{$_SESSION['x']}'";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) {
print_r($row["NxtQ"]);
}
?>
<form action="Assets/ajax/questions.php" id="ajax-questionset" method="post">
<br />
<br />
<?php echo($howmany); ?>
<br />
<br />
<div><?php echo($currentquestion); ?></div>
<span>
<button class="btn btn-hero" type="submit" name="answer1" value="1"/><?php echo($answer1); ?></button>
<button class="btn btn-hero" type="submit" name="answer2" value="2"><?php echo($answer2); ?></button>
</span>
</form>
As per Bug's suggestion below, I've added in the javascript and tested with an alert which is now giving me the right value, but it's messed up my ajax and it's now loading the php page rather than doing this 'blind' (for want of a better word)
Any suggestions?
function buttonB_clickHandler(event) {
document.getElementById('hiddenId').value = 2;
document.getElementById('ajax-questionset').submit();
}
Resolved this by taking out the javascript .submit and applying it to the buttons them self to read type="submit".
Thanks again for all your invaluable feedback guys, I love this site, great community!
Read my comment and try something like this:
<input id="buttonA" type="button" value="do something" onclick="buttonA_clickHandler(event);"/>
function buttonA_clickHandler(event) {
document.getElementById('hiddenId').value = whatever;
document.getElementById('theForm').submit();
}
repeat the code for the other button changing the name of function and other code.
Try adding {} to the else statement and adding isset
if(isset($_POST['answer1'])){
$chosenAnswer = 1;
}
else {
if (isset($_POST['answer2'])){
$chosenAnswer = 2;
}
}
I know its a duplicate one but i'm getting this error while trying to fetch data passed from a link..I dont know how to resolve it.
here is my code:
add_package.php
echo "<td><a href='delete.php?name3=" . $row['package_type']."&id3=".$row['p_id']."'>Delete</a></td>";
echo "<td><a href='edit_package.php?name3=" . $row['package_type']."&id3=".$row['p_id']."'>Update</a></td>";
here the delete link works perfectly but when i click update it takes to the edit_package page where i'm getting an undefined error..
code for edit_package.php:
<?php
include('db.php');
$id4 = $_GET['id3'];//update the page
$name4 = $_GET['name3'];//helps to update the package
echo $id4;
echo $name4;//getting values here correctly..
if(isset($_POST['submit']) )
{
$package=$_POST['package'];
if (ctype_alnum($package) && !empty($id4) && !empty($name4))
{
$sql13="select package_type,id from tbl_package where package_type='".$package."'";
$retvali=mysql_query($sql13,$conn);
$num_rows1 = mysql_num_rows($retvali);
if ($num_rows1 == 0 || $num_rows1=="")
{
$sql = "Update tbl_package set package_type='".$package."' where package_type='".$name4."' and p_id='".$id4."'";
$retval = mysql_query( $sql, $conn );
?><script>alert("Updated Successsfully");window.location ='http://localhost/demo/add_package.php';
</script><?php
}
else
{
?><script>alert("Already Exists");window.location ='http://localhost/demo/add_package.php';
</script><?php
}
}
else
{
?><script>alert("enter only letters and numbers")</script><?php
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<form id="form-validation" action="edit_package.php" method="post" class="form-horizontal" enctype="multipart/form-data" novalidate="novalidate">
<div class="col-md-6">
<div class="block" style="height:500px;">
<div class="block-title">
<h2><strong>State the Package For Tour</strong></h2>
</div>
<fieldset>
<div class="form-group">
<label class="col-md-4 control-label" for="val_username">Update Package <span class="text-danger">*</span></label>
<div class="col-md-6">
<div class="input-group">
<input type="text" id="package" name="package" class="form-control" required >
<span class="input-group-addon"><i class="fa fa-user"></i></span>
</div>
</div>
</div>
<div class="form-group form-actions">
<div class="col-md-8 col-md-offset-4">
<input type="submit" class="btn btn-info btn-primary " value="Update" name="submit">
</div>
</div>
</fieldset>
</form>
When i press update button i'm getting an undefined error i dont know why?..Thanks in advance
I'm attaching an image to it..
Try to change the <form>'s action URL to include your GET varaibles:
<form id="form-validation" action="edit_package.php?id3=<?php echo $_GET['id3']; ?>&name3=<?php echo $_GET['name3']; ?>" method="post" class="form-horizontal" enctype="multipart/form-data" novalidate="novalidate">
PLEASE NOTE: This is extremely unsafe! You need to sanitize ALL user input before using it. My example above, dis-regards security, and simply is to demonstrate my point. GET and POST data, are user variables. A malicious user could put bad code in the URL (ie ?name3=<badcode>) and it would be printed on the page, well in the source code, which they could easily pop out of. Also, in SQL queries, you need to escape the data or use prepared statements.
You should not be using mysql functions, switch to MySQLi or PDO. MySQL has been killed for a while now..
These are just asking for you to get hacked:
$sql13="select package_type,id from tbl_package where package_type='".$package."'";
and..
$sql = "Update tbl_package set package_type='".$package."' where package_type='".$name4."' and p_id='".$id4."'";
You are vulnerable to SQL injections, would could easily allow a malicious attacker to add/edit/view/delete data in your database.
The problem is, you have $package (which is raw data from POST) and $id4 and $name4 (which is raw data from GET) in your SQL query.
You would use mysql_real_escape_string() on them, but you should be using mysqli or PDO anyways...
Example:
$name4 = mysql_real_escape_string($_GET['name3']);
It's confusing, I don't know what the GET variable is called name3 but you assign it the variable $name4.. Whoever (even you) comes along later on will be lost in your code.
Updated:
Try this code. I swapped your GET for POST in your php code, and passed the GET variables from your URL as hidden fields in your form.
<?php
include('db.php');
if(isset($_POST['submit']) )
{
$package = mysql_real_escape_string($_POST['package']);
$id4 = mysql_real_escape_string($_POST['id3']); // why is variable named id4 but its id3??
$name4 = mysql_real_escape_string($_POST['name3']); // why is variable $name4 but its name3??
if (ctype_alnum($package) && !empty($id4) && !empty($name4))
{
$sql13 = "SELECT package_type,id FROM tbl_package WHERE package_type='$package' LIMIT 1";
$retvali = mysql_query($sql13, $conn);
$num_rows1 = mysql_num_rows($retvali);
if ($num_rows1 == 0 || $num_rows1=="")
{
$sql = "Update tbl_package set package_type='$package' WHERE package_type = '$name4' AND p_id='$id4'";
$retval = mysql_query( $sql, $conn );
echo '<script>alert("Updated Successsfully");window.location = "http://localhost/demo/add_package.php";</script>';
} else {
echo '<script>alert("Already Exists"); window.location = "http://localhost/demo/add_package.php";</script>';
}
} else {
echo '<script>alert("enter only letters and numbers");</script>';
}
}
?>
<form action="edit_package.php" method="post" enctype="multipart/form-data" novalidate="novalidate">
<input type="hidden" name="id3" value="<?php echo htmlspecialchars($_GET['id3'], ENT_QUOTES | ENT_HTML5); ?>" />
<input type="hidden" name="name3" value="<?php echo htmlspecialchars($_GET['name3'], ENT_QUOTES | ENT_HTML5); ?>" />
Update Package: <input type="text" id="package" name="package" class="form-control" required >
<input type="submit" class="btn btn-info btn-primary " value="Update" name="submit">
</form>
I removed your HTML formatting from the form. You had div tags that didn't match up.. I can't see your whole code, but it looks like you have a bunch of div's that are messed up (ie: not closed where they should be). I also added mysql_real_escape_string() to the passed variables, and htmlspecialchars() to the GET variables echo'd in the hidden fields of your form. It's a start.
You might be able to make better sense of your code and troubleshoot errors, if you wrote your code a bit cleaner. Not trying to bash you :) Proper indentation, spacing, and formatting go a long way. It makes it easier on your eyes, and on yourself, in times like these..
I left your <script> tags because I assumed there was a reason your wanted to popup a message box.. I would just use header('Location: /path/to/where.php'); and pass your error message through a session variable or something, like an array of errors, which you get, clear, and show on the page the errors.
Im having trouble passing the value id in my code to edit.php.
In displaynews i print out articles from the database. It also creates a link that redirects me to edit.php and sending the $id value with it.
Link to displaynews function
http://snipt.org/zhla8
Here's where im having trouble
<h3>EDIT NEWS ARTICLE</h3>
<form id="EditNews" name="EditNews" method="POST" action="edit.php">
<textarea name="editnewstext"><?php $news=Textarea(1);echo $news ?></textarea> <!--HERE i need to replace the 1 with id passing in displaynews -->
<input type="submit" name="Edit_News" id="Edit_News">
<?php
include 'db.php';
include'editnewsarticle.php';
if(isset($_POST['Edit_News']))
{
$content= $_POST['editnewstext'];
geteditnews(1,$content); //<!--HERE i need to replace the 1 with idpassing in displaynews -->
Header("location:Home.php");
}
Link to Edit.php page
http://snipt.org/zhkj8
Link to GetnewsTextarea function
http://snipt.org/zhlb9
Link To editnewsarticle function
http://snipt.org/zhki2
Please dont comment on how the mysql extension is depreciated and that my code is open for sql injections.
Thanks in advance
EDIT: Here's the solution
if(isset($_GET['id']))
{
$id = $_GET['id'];
$data = mysql_query("SELECT * FROM news WHERE id = '$id' ");
}
?>
Does these changes in edit.php help?
if (isset($_POST['id']))
$id = $_POST['id'];
<?php $news=Textarea($id);echo $news ?>
geteditnews($id, $content);
Add a hidden field for the id right after the form tag. As such:
<form id="EditNews" name="EditNews" method="POST" action="edit.php">
<input type="hidden" name="id" value="<?php echo $id; ?>">