How do I check which input button has been pressed in PHP? - php

so I'm new to php and I have two buttons on this html page here (the id value is included in the url):
<!DOCTYPE html>
<head>
<title>StoryBlox is a Social Story Builder Tool</title>
<meta charset="utf-8">
<!-- these support the header/footer formatting -->
<link type="text/css" rel="stylesheet" href="css/main.css">
<link type="text/css" rel="stylesheet" href="css/header_footer.css">
<script src="js/header.js"></script>
<?php //include_once 'confirm_login.php'
include_once 'story_manager.php';
include_once 'open_connection.php';
//include_once 'functions.php';
//sec_session_start();
if(isset($_GET['id'])){
$str_id = $_GET['id'];
$draft_id = get_story_attribute($str_id, 'draft');
}else{
echo "Invalid story id.";
echo "<br>";
}
?>
</head>
<body>
<div id="wrapper_main">
<div id="wrapper_content">
<?php include_once 'header.php'; ?>
<h1>Welcome to StoryBlox Create Story!</h1>
</div>
<!-- menu -->
<!--<div id="inputs"> -->
<form id="create_form" action="save_story.php?id=<?php echo $str_id?>" method="POST">
<input type="text" name="storyTitle" id="title" placeholder="Enter title." autofocus/><br>
<textarea rows="4" cols="50" name="storyDesc" id="description" placeholder="Enter description here."></textarea>
<div id="footer">
<input type="button" name="draftBtn" onclick="this.form.submit()" value="Save as Draft"/>
<input type="button" name="finalBtn" onclick="this.form.submit()" value="Finished!"/>
</div>
</form>
</div>
</div>
<?php include_once 'footer.php'; ?>
</body>
When I click one of these two buttons, I'm brought to this php document here:
include_once 'open_connection.php';
include_once 'story_manager.php';
$mysqli = open_connection();
if($_SERVER['REQUEST_METHOD'] === 'POST'){
if(isset($_POST['draftBtn'])){
$title = $_POST['storyTitle'];
$desc = $_POST['storyDesc'];
$str_id = $_GET['id'];
update_story_title($str_id, $title);
//update_story_description($str_id, $desc);
header('Location: createStory.php');
}
elseif(isset($_POST['finalBtn'])){
$title = $_POST['storyTitle'];
$desc = $_POST['storyDesc'];
$str_id = $_POST['storyID'];
update_story_title($str_id, $title);
//update_story_description($str_id, $desc);
save_draft_as_completed($str_id);
header('Location: ../home.php');
}else{ echo "failed";}
}?>
And I always get "failed" printed out on my page. I've been Googling this for hours and I don't understand where I'm going wrong here. If anybody could help that would be appreciated. Also, if anyone could shed some light on what the equivalent to
<input type="textarea">
would be that would be great. Thanks!

Use
<input type="submit" name="draftBtn" value="Save as Draft"/>
instead of the button types with their onclick events.

try to use submit tag instead of button.
and if you want to use button tag then you can pass value through hidden field. set value of hidden field on click event.

Related

How do I make a value not reset each page reload?

I am trying to show people their profiles from my database using PHP.
But every time a button is clicked I want the person_id ($which_person) to go up by 1 so the next person's profile is shown. I don't know how to do that because every time I click a button the page reloads so the variable "which_person" gets reset to 1.
<!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.0">
<link href="assets-putinhouse/css/style1.css" rel="stylesheet" type="text/css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Festive&display=swap" rel="stylesheet">
<title>Put people in a house</title>
</head>
<body>
<?php
include "db/connection.php";
$conn = create_connection();
$which_person = 1; //This resets to "1" every time the page reloads
$getSql = "select * from Person where person_id = 1;";
$data_labels = mysqli_query($conn, $getSql)->fetch_all(MYSQLI_ASSOC);
?>
<div class="pagesize">
<h1>Put people in a house</h1>
<img src="assets-putinhouse/images/create_account.png" alt="profilepic" class="image_person">
<?php
foreach($data_labels as $labels)
{
?>
<li class="labels" data-id="<?php echo $labels['person_id'];?>">
<?php echo $labels["firstname"] ?>
<br>
<br>
<?php echo $labels["secondname"] ?>
<br>
<br>
<?php echo $labels["gender"] ?>
<br>
<br>
<?php echo $labels["descriptie"] ?>
</li>
<?php
}
?>
<br>
<form method="GET">
<input type="submit" class="slytherin_button" value="Slytherin" name="slytherin_button_name">
<br>
<input type="button" class="gryffindor_button" value="Gryffindor" name="gryffindor_button_name">
<br>
<input type="button" class="hufflepuff_button" value="Hufflepuff" name="hufflepuff_button_name">
<br>
<input type="button" class="ravenclaw_button" value="Ravenclaw" name="ravenclaw_button_name">
<br>
<input type="button" class="nextperson_button" value="Go to next person">
<p class="text_firstname">Firstname: </p>
<p class="text_name">Name: </p>
<p class="text_gender">Gender: </p>
<p class="text_info">Info: </p>
<?php
if(isset($_GET['slytherin_button_name'])) {
onFunc($conn, $which_person);
}
if(isset($_GET['gryffindor_button_name'])) {
offFunc();
}
function onFunc($conn, $wich_person){
$sqlUpdate = "UPDATE Person SET slytherin = slytherin + 1 WHERE person_id like '$which_person';"; //this does the value "slytherin" of which_person go up by 1;
mysqli_query($conn, $sqlUpdate);
$wich_person = $wich_person + 1; //which person goes up by 1 so the next person will be shown but gets reset at the start
}
function offFunc(){
echo "Button is clicked";
}
?>
</div>
<script src="assets-putinhouse/js/script.js"></script>
</body>
</html>
ยดยดยด
(Untested) Instead of:
$wich_person = 1;
It seems you could do something like:
if (isset($_GET["id"]) {
$wich_person = (int)$_GET["id"] + 1;
}
else {
$wich_person = 1;
}
and then add the following to your form:
<form action="?<?php echo $wich_person ?>" method="GET">
...
</form>
And also, unless I'm mistaken it seems you've forgot to add </form> to your code.
In any event, this code should add the current ID to your URL every time you press submit, where then it gets increased by 1.
Edit: This is intended as a quick solution based on the code structure you provided, but upon reflection not sure if it's exactly what you're looking for. More robust solutions could be had, such as cookies or sessionStorage.

Getting $_GET variables in other files

I want to get another variable in another file, but I am wondering if this will work since I am trying to get a $_GET variable. In file one (login_check_update.php):
$username = $_GET['username'];
And in file two:
else{
include 'login_check_update.php';
?>
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <b><?php echo $username; ?></b></p>
Would file two try and get the values in the URL on that page or will it get the previous URL in the previous page? As in will file's two $username variable be redundant and cancel each other out?
chat.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Chat - Customer Module</title>
<link type="text/css" rel="stylesheet" href="chat.css" />
</head>
<?php
if(!isset($_SESSION['name'])){
loginForm();
}
else{
include 'login_check_update.php';
?>
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <b><?php echo $username; ?></b></p>
<p class="logout"><a id="exit" href="#">Exit Chat</a></p>
<div style="clear:both"></div>
</div>
<div id="chatbox"></div>
<form name="message" action="">
<input name="usermsg" type="text" id="usermsg" size="63" />
<input name="submitmsg" type="submit" id="submitmsg" value="Send" />
</form>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
// jQuery Document
$(document).ready(function(){
});
</script>
<?php
}
?>
</body>
</html>
Perhaps the following may help you clarify your question:
Two files, same directory.
First file, named one.php:
<?php
$name = $_GET['name'];
Second file named two.php:
<?php
include 'one.php';
echo $name;
If I call file two.php with the following query param: two.php?name=who
This will output:
who
As $name is in the same scope.
Think of the include crudely as it inserting a text snippet of the first file in-place.

PHP Form does not log in and move to next page

I ran into another problem with my website that I can't get around.
I'm trying to make it so when the admin logs in he will be taken to the admin page but for some reason when I enter the correct details into the log in and press the submit button it just brings me back to the admin log in page again.
Here is a Gyazo of my problem
https://gyazo.com/34f133fea4b20ec285ee7ff491053145
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8">
<title>Login</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js" type="text/javascript"></script>
<link href='https://fonts.googleapis.com/css?family=Ubuntu:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/148866/reset.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<body>
<main id="cd-main-content">
<section id="cd-intro">
<h1>Admin Log In</h1>
<header class="cd-header">
<?php
require('db.php');
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
// removes backslashes
$adminusername = stripslashes($_REQUEST['adminusername']);
//escapes special characters in a string
$adminusername = mysqli_real_escape_string($con,$adminusername);
$adminpassword = stripslashes($_REQUEST['adminpassword']);
$adminpassword = mysqli_real_escape_string($con,$adminpassword);
//Checking is user existing in the database or not
$query = "SELECT * FROM `admin` WHERE username='$adminusername'
and password='".md5($adminpassword)."'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $adminusername;
// Redirect user to admin page /////////////////////////////////////////////////////////////////////
header("Location: adminpage.php");
}else{
echo "<div class='form'>
<h3>Username/password is incorrect.</h3>
<br/>Click here to <a href='admin.php'>Login</a></div>";
}
}else{
?>
<div class="form">
<form action="" method="post" name="login">
<input type="text" name="adminusername" placeholder="Username" required />
<input type="password" name="adminpassword" placeholder="Password" required />
<input name="submit" type="submit" value="Login" />
</form>
</div>
<?php } ?>
<a class="cd-menu-trigger" href="#main-nav">Menu<span></span></a>
</header>
<div class="cd-blurred-bg"></div>
</section> <!-- cd-intro -->
</main>
<div class="cd-shadow-layer"></div>
<nav id="main-nav">
<ul>
<li><span>Login</span></li>
<li><span>What's On</span></li>
<li><span>Favourites</span></li>
<li><span>About</span></li>
<li><span>Admin</span></li>
</ul>
Close<span></span>
</nav>
</body>
<script src='js/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
You are doing:
if (isset($_POST['username'])) {
//...
}
Try this
if (isset($_POST['adminusername'])) {
//...
}
As a note, I suggest you to try use a framework, like laravel.
first I would debug by var_dump($_POST) and see what you get. I would bet that since you dont have an ID set for the input value name it is not working. If anything checking for ISSET($_POST['username']) would never work because you do not have a vairable set for that name.
var_dump($_POST) and see what you get. If not add an ID='username' to the input
try this :-
if (isset($_POST['submit'])){
// rest of code...
}

Buttons that affect a function - PHP

Scenario:
I am trying to have a part of my page constently run a function, the function is then affected when the above buttons are clicked.
The buttons call functions that are within the main/constant function; master($selected).
Here is what i have tried.
index.php:
<? session_start();
require("inc.ini.php");
?>
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<meta charset="utf-8">
<title>Buttons to funtions</title>
</head>
<body>
<main>
<header>
<form method="post" action="<?=$_SERVER['php_self']?>">
<button type="submit" name="change" value="insert, <?$selected = "func1";?>">Func 1</button>
<button type="submit" name="change" value="insert, <?$selected = "func2";?>">Func 2</button>
</form>
<!--
I want to press a button and when it is pressed it calls the function selected and gives it the value of which the button represents.
-->
</header>
<figure>
<?
if($_POST['change']){
echo $selected;
master($selected);
}
?>
</figure>
</main>
</body>
</html>
inc.ini.php:
<? session_start();
function master($selected){
if($selected == "func1"){
function func1(){
echo "func 1";
}
}
if($selected == "func2"){
function func2(){
echo "func 2";
}
}
}
?>
Another side question. do i need to do these if statements, can the $selector jump straight to the new function.
Php is a server side language, this means that a request needs to be sent to the server to make your code run.
Also when a form submits all of it's children are sent, so it is not possible to distinguish which has been clicked.
That being said:
<?php
session_start();
require("inc.ini.php");
?>
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<meta charset="utf-8">
<title>Buttons to funtions</title>
</head>
<body>
<main>
<header>
<form method="post" action="<?=$_SERVER['php_self']?>">
<button type="submit" name="change" value="Func1">Func 1</button>
</form>
<form method="post" action="<?=$_SERVER['php_self']?>">
<button type="submit" name="change" value="Func2">Func 2</button>
</form>
</header>
<figure>
<?php
if (isset($_POST['change'])) {
echo $_POST['change'];
master($_POST['change']);
}
?>
</figure>
</main>
</body>
</html>
If you use 2 forms then you get different values for the same name.
Looking at your inc.ini.php file it seems you're defining functions based on which input has been entered. I would suggest not doing this but if your heart is set on it then okay.
Please add a comment to this post if you need more help.
Hope this helps.

passing id on href and submitting form on same page

I am making social project form and im trying to add reply ..the reply button is a link that sends user to reply.php page with post id saved in href...on the reply.php my form action is the same page but when i click button to submit form it doesnot get the id and refreshes page with post and display error undefined id need help..
here is my reply.php
<?php
require('session.php');
$id=$_GET['id'];
//echo $id;
$submit=#$_POST['submit'];
$reply=#$_POST['reply'];
if(isset($submit)){
$id=#$_GET['id'];
$sql=mysqli_query($con,"INSERT INTO REPLY (reply,Username,post_id) VALUES '$reply','$user_check','$id'");
$sql2=mysqli_query($con,"SELECT * FROM REPLY WHERE post_id= '$id'");
while($row=mysqli_fetch_array($sql2)){
echo $row['Username']."<br/>".$row['reply']."<br/>";
}
}
else "error in submission";
?>
<!DOCTYPE html>
<html>
<title>Studhelp</title>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="w3.css">
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<script src="bootstrap/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
<?php
$sql=mysqli_query($con,"select * from posts where post_id='$id'");
while($row=mysqli_fetch_array($sql)){?>
<!-- Middle Column -->
<div class="w3-col m7">
<div class="w3-row-padding">
<div class="w3-col m12">
<div class="w3-card-2 w3-round w3-white">
<div class="w3-container w3-padding">
<h3 class="w3-opacity"><?php echo $row['Username'] ;?></h3>
<?php
echo $row['Posts']."<br/>".$row['date']."<br/>";
}
?>
</p>
</div>
</div>
</div>
</div>
<form action="reply.php" method="post">
<input type="text" name="reply" >
<input type="submit" name="submit" value="reply">
</form>
this is the anchor tag send id to reply.php
Reply
If I understand correct you need to be able to read your "id" variable after you post the form. To achieve this use $_REQUEST instead of $_GET, like this:
$id = $_REQUEST['id'];
And also pass the variable with your form, as a hidden field:
<form action="reply.php" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="text" name="reply" />
<input type="submit" name="submit" value="reply" />
</form>
You didn't check if the fom was submitted
Enclose other PHP code after session.php inside a conditional checker such as:
if ($_POST):
You can use form tags to create a form and put the id field as hidden.
GET requests shouldn't be use to modify data

Categories