Confirmation box before running a php script - php

<?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.

Related

Delete all rows from MySQL table using PHP

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") {
}

Update not working PHP MYSQL CRUD

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.

PHP server error 500 when clicking form button

When i select my button in the form with the link to the processing page for the login it just returns a server error 500, i have not encountered this before and have had no luck on google.
Here is my HTML markup on the login page
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="styles.css">
<title>Administrator Login</title>
</head>
<body>
<div class="container">
<div class="header"><img src="IMAGES/LOGO.png" alt="Insert Logo Here" name="Insert_logo" width="" height="90" id="Insert_logo" style="background-color: #; display:block;" />
<!-- end .header --></div>
<div class="content">
<form action="loginProcess.php" method="post" class="loginForm">
<input type="text" id="username" name="username" placeholder="Enter Username" required>
<input type="password" id="password" name="password" placeholder="Enter Password" required>
<button type="submit" id="loginBTN" >Login</button>
</form>
</div>
</body>
</html>
And here is the code for my php process
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
//stores the search data
$username = $_POST['username'];
$password = $_POST['password'];
//checks to see if it is empty or null
if(isset($username) && !empty($username) && (isset($password) && !empty($password))){
require('includes/dbconx.php');
//escapes all special characters that could break database
$pword = mysqli_real_escape_string($con, $password);
$uname = mysqli_real_escape_string($con, $username);
//searchq stores the cleaned up search data
//create a variable to store a wildcard SQL statement
$sql = mysqli_query($con, "SELECT * FROM login WHERE username = '%$uname%' AND password = '%$pword%' ");
}//end statement
//if no data is inserted it will putput this
else{
echo("Please enter Login details!");
//this will kill the connection
die;
}
//end else
$result = $con->query($sql);
//if it finds no matching data it informs the user and kills the DB connextion
if(mysqli_num_rows($result) == 0){
echo("<p>No record found or password doesn't match! </p>");
die;
}
else{
header('Location: adminPage.php');
?>
</body>
</html>
Here is my connection, this works for the other pages as it should this.
<?php
//connects to my music database
$con=mysqli_connect("localhost","root","root","music");
//if it fails to connect it outputs this with an error number
if(mysqli_connect_errno()) {
echo "failed to connet to MYSQL:".mysqli_connect_error();
}
?>
Got time for that Beer?
This query is incorrect, you use the % character only when using the LIKE syntax, so query should be
$sql = mysqli_query($con, "SELECT *
FROM login
WHERE username = '$uname'
AND password = '$pword' ");
If you format your code more consistantly it will also help in spotting errors.
And as in my answer to your last question, check for errors after all mysqli_ calls. During development it will save you much time, as thats when we developers make little bobo's
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// this would be better at the top of the script
require('includes/dbconx.php');
// why do 2 steps when one would do
// also you have not checked these actually exist
// until the IF that follows these 2 lines
//$username = $_POST['username'];
//$password = $_POST['password'];
// empty() does an isset already so you only need the empty()
if( !empty($username) && !empty($password)){
$pword = mysqli_real_escape_string($con, $_POST['password']);
$uname = mysqli_real_escape_string($con, $_POST['username']);
$sql = mysqli_query($con, "SELECT *
FROM login
WHERE username = '$uname'
AND password = '$pword'");
// always check status after mysqli_query and other calls
// and at least output the error message
if ( $sql === FALSE ) {
echo mysqli_error($con);
exit;
}
} else {
echo("Please enter Login details!");
die;
}
$result = $con->query($sql);
if(mysqli_num_rows($result) == 0){
echo("<p>No record found or password doesn't match! </p>");
die;
} else {
header('Location: adminPage.php');
// header Location: shoudl always be followed by an exit;
// as header does not stop execution
exit;
} // add missing closing bracket
?>
</body>
</html>

Session doesn't start when correct login credentials are given

Alright, SO. After about five hours of sifting through potential duplicates and applying would-be solutions to my project and even downloading a PHP IDE to make sure that my syntax is all nice and tidy for everyone.. I am finally at the point where I need some advice.
My two problems (which may be related):
When someone logs in, successfully with the test parameters I have stored in the DB, they are not redirected (maybe my if statement is not correct?)
When the page loads without first attempt, my "wrong password - username combination" message is displaying. I'm fairly certain as to why but not too sure how to fix it.
<?php session_start(); // this line of code has been added by the instruction of a comment.
if(isset($submit)) {
$username = $_POST['username'];
$password = $_POST['password'];
}
$con = mysqli_connect("***","***","***","***");
$S_username = mysqli_real_escape_string($con, $username);
$S_password = mysqli_real_escape_string($con, $password);
if(mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = mysqli_query($con, "SELECT * FROM `users` WHERE `username` = '$S_username' AND `password` = '$S_password'");
if(!$sql) {
die(mysqli_error($con)) ;
}
$check_again = mysqli_num_rows($sql);
if($check_again == 1) {
session_start(); // this line of code has been deleted
$_SESSION['logged in'] = TRUE;
$_SESSION['username'] = $S_username;
header("Location: http://terrythetutor.com/submitvideo.php");
}
else {
echo "Your username and password combination was not recognised. Please try again." ;
}
?>
<html>
<head>
<title>Login Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<?php include_once 'googleanalytics.php'; ?>
<body>
<a href="http://terrythetutor.com">
<div class="banner"> </div>
</a>
<?php include 'menu.php'; ?>
<h1 align="center">Please login to access restricted files</h1>
</br>
</br>
</br>
</br>
<div align="center">
<form action = "login.php" method = "post">
Username: <input type = "text" name = "username"></br></br>
Password: <input type = "password" name = "password"></br></br>
<input type = "submit" value = "Login" name="submit">
</form>
</div>
</body>
</html>
Any and all feedback is welcomed. Thank you.
use session_start(); only once and at the top ..

having issues with php_self

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']?

Categories