I know this has been asked many times and I have read through a lot of the answers but I cannot get this to work. I am trying to create a button (PHP/HTML) to delete all records from a table in MySQL. I have a table in my database called tvdbase. I would like to delete all the records from that table but keep the structure. There will not be more than 10 rows in the table at any given time.
This is my code (I have removed all the unnecessary HTML code for this example)
<?php include('includes/database.php'); ?>
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
if($_POST){
//Delete records
$query = "DELETE FROM tvdbase";
$mysqli->query($query) or die($mysqli->error.__LINE__);
// Also tried replacing the 2 lines above with:
// mysqli_query( "DELETE FROM tvdbase" );
$msg = "Entries Deleted Successfully";
header('Location:home.php?msg='.urlencode($msg).'');
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- FORM START -->
<form role="form" method="post" action="delete_all.php">
<!-- BUTTONS START -->
<a class="btn btn-default" href="home.php" role="button">Cancel</a>
<input type="submit" class="btn btn-danger" value="Delete" />
<!-- BUTTONS END -->
</form>
<!-- FORM END -->
</body>
</html>
When I click the delete button is just reloads the same page and the data is still in the table. I am still new to PHP and MySQL so please forgive the errors. Can anyone shed some light as to where I'm going wrong?
I have this working for single rows where I have a delete button in an HTML table on each row with the following code:
<?php include('includes/database.php'); ?>
<?php
//Variable
$id = $_GET['id'];
//Create room select query
$query ="SELECT * FROM tvdbase
WHERE id = $id";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($result = $mysqli->query($query)){
//Fetch object array
while($row = $result->fetch_assoc()) {
$tvDate = $row['tvDate'];
$tvCourse = $row['tvCourse'];
$tvRoom = $row['tvRoom'];
}
$result->close();
}
?>
<?php
if($_POST){
//ID Variable
$id = $_GET['id'];
//Delete room
$query = "DELETE FROM tvdbase WHERE id = $id";
$mysqli->query($query) or die($mysqli->error.__LINE__);
// $msg="Entry Deleted";
$msg = "<div class='alert alert-danger'>
Entry Deleted Successfully
</div>";
header('Location:home.php?msg='.urlencode($msg).'');
exit;
}
?>
The form action is delete_room.php?id=<?php echo $id; ?>
Try to print something in your IF statement, to check if the code pass through.
If not, try adding in your form:
<input type='hidden' name='flag' value='pass'>
Then changes your IF in this way:
if ($_POST['flag'] == "pass") {
}
Related
<?php
//Connect to Database
$link = mysqli_connect('localhost', 'xxxxxxx', 'xxxxxxx', 'xxxxxxx');
mysqli_set_charset($link,'utf8');
$delistpost= htmlspecialchars($_GET["delistpost"]);
//$request = $_SERVER['QUERY_STRING'];
$request = $delistpost;
//Error message on unsuccessful connection (connection failure)
if ($link==false){
//Print error information
echo(" ERROR: Could not connect.<br>".mysqli_connect_error());
}
//Successful connection message
else{
//Split the query string taking '=' as the delimiter
if (strpos($request, '='))
{
$n=split("=",$request);
// $queryStringType=$n[0];
$offset =$n[1];
}
$userchar = substr($offset,0,2);
$key = ltrim(substr($offset, 2, -1), '0');
$status = substr($offset,-1,1);
$query = "SELECT postid FROM userwisePost WHERE postid = $key AND user_email like '$userchar%' AND status = '$status'" ;
$updatequery = "UPDATE userwisePost SET post_status = 'draft' WHERE postid = $key AND user_email like '$userchar%' AND status = '$status'" ;
//Print the confirmation of SQL query
$verify = mysqli_query($link,$query);
if(mysqli_num_rows($verify) > 0){
$updateresult = mysqli_query($link,$updatequery);
if($updateresult==true){
RUN FUNCTION TO SHOW SUCCESS UPDATION.
}
else RUN FUNCTION TO SHOW FAILURE.
?>
Here I'm connecting to a database. I decrypt the query-string as per my requirement. After i decrypt the query-string, I match it with a record in the database, if everything matches, I need to run an update query.
Currently my program is updating it without confirmation. I need the user to press a confirmation button to run the update query.
I know I require javascript to track user button click. I need to display a HTML page on button click if the user confirms else the page should redirect to the homepage.
<?php
//Connect to Database
include "dbconnect.php";
$delistpost= htmlspecialchars($_GET["delistpost"]);
//$request = $_SERVER['QUERY_STRING'];
//$request = $delistpost;
//Split the query string taking '=' as the delimiter
$userchar = substr($delistpost,0,2);
$key = ltrim(substr($delistpost, 2, -1), '0');
$status = substr($delistpost,-1,1);
$query = "SELECT postid FROM userwisePost WHERE postid = $key AND user_email like '$userchar%' AND status = '$status'" ;
$verify = mysqli_query($dbconnect,$query);
if($verify==true){
if(mysqli_num_rows($verify) > 0)
{
echo '<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Confirmation</title>
<link rel="stylesheet" href="alertstyle.css">
</head>
<body>
<div class="container">
<form id="contact" action="changepoststatus.php?delistpost='.$delistpost.'" method="post">
<center><h3>Confirmation</h3>
<h4>Are you sure you want to delist your post?<br>If you wish to activate the post again, please contact the system administrator or email us at xxxxxxxxxx.</h4>
</center>
<fieldset>
<center>
<button name="delistpost" type="submit" id="contact-submit" style="width: 49%;">Confirm</button>
</center>
</fieldset>
</form>
</div>
</body>
</html>';
}
else {
echo '<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Failure</title>
<link rel="stylesheet" href="alertstyle.css">
</head>
<body>
<div class="container">
<form id="contact" action="https://xxxxxxxxxx" method="post">
<center><h3>Failure</h3>
<h4>Something went wrong<br>Please contact the system administrator or email us at xxxxxxxxxx.</h4>
</center>
<fieldset>
<center>
<button name="delistpost" type="submit" id="contact-submit" style="width: 49%;">Homepage</button>
</center>
</fieldset>
</form>
</div>
</body>
</html>';
}
}
?>
This is how I did it. I call another link on press of the button. changepoststatus.php has almost the same code but with update query instead of the select query.
i am trying to create a crud.
i wrote php query to delete the fetched data . but i dont know what to write after ID= "" in Delete query. my code given below
index file
<html>
<head>
<title>crud system</title>
</head>
<body>
<?php include 'connect.php';?>
<form method="post" action="postdata.php">
username:
<input type="text" name="name">
<input type="submit" name="submit">
</form>
</body>
</html>
postdata.php
//postdata.php
<?php
mysql_connect('localhost','root','') or die("cannot to database");
mysql_select_db('users');
$name = $_POST['name'];
$sql="INSERT into add_data (name) values('$name')";
$query=mysql_query($sql);
if(!$query){
echo"data entrance failed".mysql_error();
}
else{
echo "data added successfully !";
}
?>
fetchint data select.php
<!DOCTYPE html>
<html>
<body>
<?php
include 'connect.php';
$result = mysql_query("SELECT * FROM add_data");
while($row = mysql_fetch_array($result)) {
echo $row["name"]."delete"."<br/>";
}
?>
</body>
</html>
delete.php
<?php
include_once 'connect.php';
mysql_query("DELETE FROM add_data WHERE **id=2"**);
header('location:select.php');
?>
now in delete file i dont want to write id=2 because it will only delete 2nd record i want to delete whatever i click on.
In select.php
while($row = mysql_fetch_array($result))
{
echo $row["name"].'Delete<br/>';
}
In delete.php
$del_id = '';
if(!empty($_GET['del_id']))
{
$del_id = $_GET['del_id'];
include_once 'connect.php';
mysql_query("DELETE FROM add_data WHERE id = '$del_id' ");
header('location:select.php');
}
Provide the id to the delete.php script and retrieve it with $_GET then perform your delete with a where clause using the retrieved id
echo $row["name"]."delete"."<br/>";
And in delete.php
$id = isset($_GET['id']) ? (int)$_GET['id']) : 0;
I have this PHP code, when I try to click the yes button and check the database.The value remains the same. Is there something I am doing wrong? I also check my SQL query and it seems to be working fine but when I incorporate it in the php code . It is not working anymore?
<?php
require 'database.php';
$id = 0;
if ( !empty($_GET['gpx_field_id'])) {
$id = $_REQUEST['gpx_field_id'];
}
if ( !empty($_POST)) {
// keep track post values
$id = $_POST['gpx_field_id'];
// delete data
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE field_info SET verify = '1' WHERE gpx_field_id = ? ";
$q = $pdo->prepare($sql);
$q->execute(array($id));
Database::disconnect();
header("Location: index.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="assets/bootsrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Verify a Field</h3>
</div>
<form class="form-horizontal" action="verify.php" method="post">
<input type="hidden" name="gpx_field_id" value="<?php echo $id;?>"/>
<p class="alert alert-error">Are you sure to verify this field ?</p>
<div class="form-actions">
<button type="submit" class="btn btn-danger">Yes</button>
<a class="btn btn-danger" href="index.php">No</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
Here I assume your query is working fine so
Please change your php code as below...
<?php
require 'database.php';
$id = 0;
if ( !empty($_GET['gpx_field_id'])) {
$id = $_REQUEST['gpx_field_id'];
}
if ( !empty($_POST)) {
try {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE field_info SET verify = '1' WHERE gpx_field_id IN :id ";
$q = $pdo->prepare($sql);
$q->execute(array($id));
Database::disconnect();
header("Location: index.php");
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
Hope it will help you.
You specify $id = 0 at the top, but it is never updated to some 'real' value. Therefore, the form is populated with
<input type="hidden" name="gpx_field_id" value="0"/>
and thus gpx_field_id always remains 0. Then, your query will update all rows with WHERE gpx_field_id = 0. Most probably, those rows will not exist...
You do need to get a proper value for $id before you insert it in the form.
On a side-note, since you are using html5 (<!DOCTYPE html>), the closing tag for input should be omitted. Write instead: <input type="hidden" ... >, leaving out the forward slash, just as you did with the meta and link tags in the head section.
so I am trying to display multiple results from a database when a query is searched, the query is passed from a search box on another page.
I have it displaying one result, but that is all it will display.
I need it to display all the results that are relevant to the search query.
the php code is below
<meta charset="UTF-8">
<?php
$mysqli = new mysqli('localhost', 'scott', 'tiger','courses');
if ($mysqli->connect_errno)
{
die('Database connection failed');
}
//$m->set_charset('utf8');
$search_sql = "
SELECT title, summary, id
FROM course
WHERE title LIKE '%".$_POST['searchBar']."%'";
$result = $mysqli->query($search_sql) or die($mysqli->error);
$search_result = $result->fetch_assoc();
?>
<!doctype html>
<head>
<meta charset="utf-8">
<h1>Search Results</h1>
</head>
<body>
<h3><?= $search_result['title'] ?></h1>
<p><?= $search_result['summary'] ?></p>
</body>
and the code for the search bar
<!doctype html>
<html>
<Head>
<meta charset = "utf-8">
<title>Search</title>
</head>
<body>
<h2>Search</h2>
<form name="search" method="post" action="SearchResultsPage.php">
<input name="searchBar" type="text" size="40" maxlength="60" />
<input type="submit" name="Submitsearch" value="Search" />
</form>
</body>
Does anyone have any suggestions?
Thanks in advance;
You will need to place it in a while loop to show multiple results, the fetch function you're using will only retrieve one row, if you place it in a loop you can keep fetching until there is nothing to fetch:
//$m->set_charset('utf8');
$search_sql = "
SELECT title, summary, id
FROM course
WHERE title LIKE '%".$_POST['searchBar']."%'";
$result = $mysqli->query($search_sql) or die($mysqli->error);
?>
<!doctype html>
<head>
<meta charset="utf-8">
<h1>Search Results</h1>
</head>
<body>
<?PHP while($search_result = $result->fetch_assoc()) { ?>
<h1><?= $search_result['title'] ?></h1>
<p><?= $search_result['summary'] ?></p>
<?PHP } ?>
</body>
P.S. your code is vulnerable to SQL injection, you should read about prepared statements. More Info on that
You can iterate over your query results with a while loop. To complete the example I added the necessary data cleaning.
<?php
// function to clean post data
function cleanPost(&$value) {
if (is_array($value)) {
foreach ($value as $k => $v) {
$value[$k] = cleanPost($v);
}
return $value;
}
else {
$value = mysql_real_escape_string($value);
return trim(htmlentities(strip_tags($value)));
}
}
// search function
function search() {
// check if post data is set
if (isset($_POST['searchBar'])) {
// make link with db
$link = mysqli_connect('localhost', 'scott', 'tiger','courses');
if (!$link)
return false;
}
// clean your post data
$cleanPostData = cleanPost($_POST);
// query
$sql = "SELECT title, summary, id FROM course WHERE title LIKE '%".$cleanPostData['searchBar']."%'";
$result = mysqli_query($link, $sql);
// iterate over results
if (isset($result) && mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
// here is your data
echo $row['title'] . "< br/>";
echo $row['summary'] . "< br/>";
echo $row['id'] . "< br/>";
}
}
}
}
// call search function
search();
?>
I am trying to implement a page where a user enters a comment and it gets displayed right in the same page. The problem i am having is that every time you go to the page there are no comments in the page(there are actually comments).
This is my sceneario i am having:
I go to the page and there are no comments, i enter a comment 'hello' and it gets displayed right away.
I go to a different page and then i come back to the comments page and there are no comments.(the comment "hello" should be already displayed)
I enter a comment "hi" and both comments "hello" and "hi" get displayed
I cant resolve this issue..
This is my code, its pretty long
<?php
session_start(); //starts or continues the session
require_once('functions.php'); //needed for some function calls
error_reporting(E_ALL ^ E_NOTICE);
?>
<!DOCTYPE html>
<html lang = "en">
<head>
<script type = "text/javascript" src = "functions.js"></script>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<?php
GetUserLayout($_SESSION['userId'], $_SESSION['superUser']);
?>
<div id = "shareyouridea_form" class = "post">
<h1> Share your post</h1>
<!-- used for the form -->
<form id = "idea_form" method = "post"
action = "<?php echo $PHP_SELF;?>"
onkeypress = "return DisableEnterKey(event);">
<table>
<caption>
<strong>
<br /> Share post form:
</strong>
</caption>
<tr class = "spacearound"> <!-- input for bright idea -->
<td> Post: </td>
<td>
<textarea form = "idea_form" name = "b_idea" rows = "12"
cols = "85" title = "Please describe your product idea"
id = "bright_idea" maxlength = "1000"
onkeypress =
"return InputLimiter(event, 'lettersSpacePunctuation');">
</textarea>
</td>
</tr>
</table>
<p>
<input type = "reset" value = "Reset" />
<input type = "submit" value = "Share Idea!"
title = "complete form first to submit"
id = "submit_button"
name = "add_comment"
onmousedown = "IsIdeaFormCompleted();" />
</p>
</form> <!-- end idea_form -->
</div>
</div> <!-- end of ShareYourIdea_middle -->
<script>
DisplayFooter();
</script>
<?php
if(isset($_POST['add_comment'])){ // if add comment was pressed
// get variables
$name = $_SESSION['firstName'];
$empId = $_SESSION['userId'];
$idea = $_POST['b_idea'];
// CONNECTING TO OUR DATABASE
$db = mysqli_connect(dbHost, dbUser, dbPassword, dbName);
if (mysqli_connect_errno()) { //if connection to the database failed
echo("<p id = 'greatideadescription'>
Connection to database failed: " .
mysqli_connect_error($db) . "</p>");
exit("goodbye");
} //by now we have connection to the database
// WE WRITE OUR QUERY TO INSERT POST INFO TO DATABASE
$query = "INSERT INTO posts(postId,empl_Id,post,postDate)
VALUES('','$empId','$idea',NOW())";
$result = mysqli_query($db, $query);
}
?>
<?php
// WE DO A QUERY TO SHOW ALL COMMENTS IN THE PAGE
$query = "SELECT firstName,lastName, post,
date_format((date_add(postDate,interval -7 hour)),'%a, %M, %d, %Y at %I:%i%p' ) as mydatefield
FROM users INNER JOIN posts ON userId = empl_Id
ORDER BY postDate DESC";
$result = mysqli_query($db,$query);
if (!$result) { //if the query failed
echo("<p id = 'greatideadescription'>
Error, the query could not be executed: " .
mysqli_error($db) . "</p>");
mysqli_close($db);}
if (mysqli_num_rows($result) == 0) { //if no rows returned
echo("<div id = 'blogs'>
<div id ='name'>
No posts detected
</div>
</div>
<div class='fb-like' data-href='http://jacobspayroll.zxq.net/index/blog.php' data-send='true' data-width='450' data-show-faces='true'></div>
");
mysqli_close($db); //close the database
exit("</table></div></form></div></div>
<script>DisplayFooter();</script></body></html>");
} //by now we know that we have some products purchases returned
$numRows = mysqli_num_rows($result); //gets number of rows
$numFields = mysqli_num_fields($result); //gets number of fields
//prints the data in the table
while($row = mysqli_fetch_assoc($result)){
$posted = $row['post'];
$message = wordwrap($posted,5);
echo
'<div id ="blogs">
<table id = "blog_id">
</br>
<div id = "name">
<strong>'.$row['firstName'] . ' ' .$row['lastName'].
'</strong>
: ' .$message .
'<br/>
</div>
<div id ="date">'.
$row['mydatefield'] . '
</div>
<div id ="delete_comment">
Delete this comment
</div>
<p>
</table>
</div>';
}
mysqli_close($db);
?>
</body>
</html>
You have the wrong Usage of PHP_SELF
//You must use Server and execution environment information `$_SERVER[]`
$_SERVER['PHP_SELF'];
// For your form action like this
action = "<?php echo $_SERVER['PHP_SELF'];?>"
as Kail mentioned you got it wrong but you might want to use $_SERVER['SCRIPT_NAME'] instead of $_SERVER['PHP_SELF'] then you might want to add some script to get GET parameters if you use them for your script(s). If you use PHP_SELF you might have a user link to script.php/%22%3E%3Cscript%3Ealert('xss')%3C/script%3E%3Cfoo might look like action="script.php/"><script>alert('xss')</script> or could be a redirect to collect cookies and the alike in other words XSS attack.
$_SERVER['PHP_SELF'] vs $_SERVER['SCRIPT_NAME'] vs $_SERVER['REQUEST_URI']
XSS Woes
What's the difference between $_SERVER['PHP_SELF'] and $_SERVER['SCRIPT_NAME']?