is it possable to prevent PHP $var from reseting? - javascript

Im fairly new to PHP and I'm currently working on a battle system, kind of like an idle clicker game, and not sure how to handle somethings do to lack of knowledge. What i am attempting right now is a player clicks a button , that POSTs Attack, and the damaged is taken from enemy hp, but what going on is every time i submit the attack, the HP get reset which is to be expected from PHP, I just don't know how avoid it resetting without having the value stored in a database which im trying to avoid just to keep the work load on the server light. I thought maybe moving the $VAR to my header.php but again it still get reset.
<?php
session_start();
include("header.php");
if(!isset($_SESSION['uid'])){
echo "You must be logged in to view this page!";
}else{
if(isset($_POST['attack'])){
$health--;
}
?>
<form action="battlesystem.php" method="post">
<table cellpadding="5" cellspacing="5">
<tr>
<td><input type="submit" name="attack" value="Confirm"</td>
<td><?php echo number_format($health); ?></td>
</tr>
</table>
</form>
<hr />
<?php
}
include("footer.php");
?>

Related

How can I send SQL variable from a HTML table to JS popup and then to PHP variable without jquery? [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 1 year ago.
I'm trying to make software that creates a job board where you can add jobs and maintenance guys can check them off as they go. My problem is getting the request_ID of my table to my SQL query at the bottom in deleteData(). I've tried so much, any tips will be a lot of help.
I have to be making this hard than it needs to be. Im literally just trying to click a button, pop up a form, ask if the user has completed the job, then remove it from the table.
<!DOCTYPE html>
<html>
<head>
<script>
function complete() {
document.getElementById("myForm").style.display = "block";
}
function closeForm() {
document.getElementById("myForm").style.display = "none";
}
</script>
<link rel="stylesheet" href="styles.css">
<title>KCHC Work Orders</title>
</head>
<?php
$host = "localhost";
$user= "";
$password = "";
$database="workorders";
$DBConnect = #new mysqli($host,$user,$password,$database);
if ($DBConnect->connect_error)
echo "The database server is not available at the moment. " .
"Connect Error is " . $DBConnect->connect_errno .
" " . $DBConnect->connect_error . ".";
else{
echo "Connection made";
}
?>
<header>
<div class="menu">
<nav>
Create a Request
</nav>
</div>
</header>
<body>
<?php
$sql = "SELECT request_id, name, date, location, description FROM requests";
$stmt = $DBConnect->query($sql);
if ($stmt->num_rows > 0) {
echo '<div class="request_box">';
echo '<table id="myTable" ><tr><th>ID</th> <th>Name</th> <th>Date</th> <th>Location</th> <th>Description</th> <th>Complete?</th> </tr>';
while (($Row = $stmt->fetch_assoc()))
{
echo "<tr id=";
echo $Row['request_id'] . ">";
echo "<th>" . $Row['request_id'] . "</th> <th>" . $Row['name'] . "</th> <th>" . $Row['date'] . "</th> <th>" . $Row['location'] . "</th> <th>" . $Row['description'] . "</th> <th>" . '<input type="button" onclick="complete()" value="' . $Row["request_id"]. '" />' . "</th></tr>";
}
echo "</table> </div>";
}
else{
echo '<div class="request_error">';
echo "<p> There are no jobs to complete!</p> <br>";
echo "<p> If you think there should be, please contact Matt or his genius son</p>";
echo '</div>';
}
function sendit($i){
$newId = $i;
}
?>
`
<div class="popup" id="myForm" >
<form id="formReal" method="post">
<h1>Would you like to remove this job? </h1>
<input type="submit" class="btn" onclick="" submit="<?php deleteData() ?>" value="Remove from List" />
<button type="button" class="btnCancel" onclick="closeForm()">Cancel</button>
</form>
</div>
</body>
<?php
function deleteData(){
global $DBConnect;
$id_new = $newId;
$sql = "DELETE FROM requests WHERE request_id = 3";
$stmt = $DBConnect->query($sql);
}
?>
You cannot put PHP code inside a javascript event and have it work the way you are intending it to in your code. PHP code is run on the server before the page is sent to the user. PHP can be used to generate javascript code, but PHP cannot be called in-page by javascript. Javascript is run in the browser. If you want javascript code to trigger PHP code, you need to have javascript initiate an HTTP(S) request to a separate PHP script. This can be done either by sending the browser to a new page for that script, or by using AJAX to initiate a background call to that script while keeping the user on the same page. It seems like this latter option is what you are intending.
So what you want here to do this gracefully is the AJAX programming method, which is a whole paradigm of programming that is quite involved; there's no way we could possibly teach you in a single answer. The basic idea is that, in javascript, you need to initiate a request, and then you need event-handling code to listen for the response, do error handling, and then update the HTML on-page to reflect whatever response you got from the script you called.
Then in the PHP script that got called, you put the SQL query to actually delete the appropriate row in the table in the database.
If you look up some basic AJAX tutorials and you feel like you're in over your head, you might want to rethink a simpler way of doing this that is perhaps a bit clunkier or old-fashioned ("Web 1.0") to the user.
You can achieve what you want easily via HTML forms, use a form with action="/path/to/some_script.php" and then send the user to a new page, sending POST variables which are read by the PHP script. And then that page can just redirect back to the original page, displaying a refreshed version of the page after deleting the item. The tradeoff here is that the programming is much easier and less error-prone, and debugging is easier, but you need to send the user around to different pages. So you get less work, but a more clunky user experience.
It's your choice. If I were in your position, and I need to meet a nearby deadline, I would probably put up a quick solution using HTML forms, but I'd start learning AJAX, which is going to take months for you to do well. Then come back and put up a slick AJAX solution when you're ready.

WordPress is_user_logged_in failing with HTML Scripting

Could someone please review why this below added code won't execute correctly? I've escaped the PHP scripting to display the HTML content in WordPress, but I can't get this thing to work!
The results are that, whether the user is logged in or not, the HTML content displays for everything. Strangely, though, I can't get the else { ... } part to render in HTML. I'm not too good with PHP, so please mind if I done something incorrectly.
I've tried debugging via NetBeans, but the IDE failed to detect anything on a fail-safe conditioning.
<?php
if ( is_user_logged_in() ) {
?>
<h2>Welcome to the Portal!</h2>
<p>Here you can manage all information with an authorised account. You can click on the button below to create a new entry.</p>
<button type="button" href="#" onClick="document.location = 'http://www.example.com'">Add Entry</button>
<?php
} else {
echo "<h1>Unauthorised!</h1>";
echo "<javascript>document.location = \'http://example.com\'";
exit;
};
?>
Alright, so I got the coding going. It turned out that, by default, WordPress didn't allow PHP execution in my pages. I installed a plugin named "insert PHP", modified the code to mix html and php and it worked!
[insert_php]
if (is_user_logged_in()){
echo "<h2>Welcome to the Portal!</h2>";
echo "<p>Here you can manage all entries with an authorised account. You can click on the button below to create an entry.</p>";
echo '<button type="button" onClick="document.location = \'http://somesite.com\'">Add Listing</button>';
} else {
echo '<h2>Unauthorized 401</h2>';
echo '<script>document.location = \'http://domain.tld'</script>';
};
[/insert_php]

Common popup form, generated table

My Web page generates a table that shows the results of a search. I want the user to be able to click on one of the results, have a pop up window which allows them to enter a message and have it stored on a database. Then the user clicks the send message button, the popup will then close and let the user continue the search results.
Here is the current code I have.
<h1>
<center>
<u>Casting Call Results</u>
</center>
</h1>
<table border="1"; width="600px"; align="center">
<?php if(empty($results)) {echo "No Data returned";} ?>
<?php foreach($results as $member):?>
<?php $imgloc = "members/".$member['username']."/".$member['photolink'];?>
<tr align="center">
<td width="100px"> <img style="width:100px; height:125px" src="<?php echo $imgloc;?>"></td>
<td><?php echo $member['bio'];?></td>
</tr>
<tr align="center">
<td><?php echo $member['username']?></td>
<td><?php echo $member['email']?></td>
</tr>
<?php endforeach; ?>
</table></div>
<form action="castingcall.php">
<center><input type="submit" value="Search Again"></center>
</form>
Here's the search return. I tried to insert the image but I don't have ten reputation points so here's a link to the search return so you can see what I'm talking about.
http://www.chicagofilmclub.org/screenshot.jpg
As you can see the table is generated by a for each so I am really confused as to how I can have each user an active link that calls the same page in a popup but can still $PASS the proper user name.
Each person would have a link that would look something like this:
Contact Member
I am assuming you will give each memebr an ID in your database.
Then on the contactform.php page you would use something like this:
<?php
$memberId = $_GET['member'];
//lookup memeber in database and do whatever it is you want to do with that info
?>

CSS Template Dropdown Menu Breaks When Adding PHP

I'm using a mobile template for a personal site and I'm using it because of the menu format. The source and demo can be found here http://mobifreaks.com/free-mobile-website-templates/galaxy-mobi/ and all I have done to it is strip some of the content out of the page.
The menu is a CSS menu that is using jquery. I am using PHP to interact with a MySQL database so it is necessary to for me to use a PHP page. If I just save the page as a PHP page it works fine but when I add any PHP code to the page(in the body) both menu items are displayed like a normal list of buttons instead of a dropdown menu.
I add the following PHP to a post-content div:
<?php
while($rows=mysql_fetch_array($result) or die(mysql_error())){
?>
<table align="center" border="4" cellspacing="2" cellpadding="3" width="100%">
<tr><td>Date</td><td>Cateogry</td><td colspan="4">Decription</td><td>Credit</td><td>Debit</td></tr>
<tr><td class="datetable"><? echo $rows['date']; ?></td><td class="category"><? echo $rows['category']; ?></td><td class="description" colspan="4"><? echo $rows['description']; ?></td><td class="amount"><? echo $rows['amount']; ?></td><td class="amount"><? echo $rows['amount']; ?></td></tr>
<tr><td colspan="2" align="center">Back To Top</td></tr>
</table>
<br>
<?php
}
?>
I'm curious if there's any way around this. If you would like any of my code or any more clarification, I'm happy to provide it. Thanks for all of the help.
The or die statement in your while loop is causing your PHP code to stop executing when there are no longer any results left to retrieve. The or die statement executes whenever mysql_fetch_array returns false (the end of your data set).
If you replace it with while(($rows = mysql_fetch_array($result)) !== false) {, then your PHP code will continue to run and should allow everything to execute correctly.
I see you are using the mysql_* functions. Please note that these have been deprecated for quite some time. I would highly recommend you look into MySQLi or PDO MySQL.

javascript and php do not work together

I'm writing the register page for my website.Here is my register page.Can anyone show me why it does not check whether The username is already in use or not.I don't know whether PHP and javascript can work together or not.
The html page is as follows:
<html>
<head>
<title>Register</title>
</head>
<body>
<script language="javascript">
function checkInput()
{
if(document.register.username.value=="")
{
alert("Fill in username");
document.register.username.focus();
return false;
}else if(document.register.password.value==""){
alert("Fill in your password");
document.register.password.focus();
return false;
}else {
<?php
if(isset($_POST['submit'])){
include "connect.php";
$username=$_POST['username'];
$query="SELECT username FROM user";
$result=mysql_query($query);
while($row=mysql_fetch_array($result)){
$arr[]=$row['username'];
}
if(in_array($username,$arr)){
?>
alert("Username is already in use");// this part does not work!
document.register.username.focus();
return false;
<?php
}
}
?>
}
}
</script>
<form name="register" method="post" action="dangki.php" onsubmit="return checkInput();">
<table width="289" height="185" border="1">
<tr>
<td colspan="2">register</td>
</tr>
<tr>
<td width="83">Username</td>
<td width="190"><input type="text" name="username" id="textfield" ></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" name="password" id="textfield2"></td>
</tr>
<tr>
<td>Re-type Password</td>
<td><input type="text" name="repassword" id="textfield3"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" id="button" value="Submit"> </td>
</tr>
</table>
</form>
</body>
</html>
Not, Javascript and PHP do not "work together" in that way. Javascript runs in your browser, PHP runs on the server before that. Therefore, you cannot use PHP for client side validation, only server side. For a first demonstration of this, just "view source" on what your page looks like to the browser.
You have to think of them separately. You have to have PHP just check what the form submits, and return a new page that indicates whether it was a valid/new username and allows the user to try again if needed.
You can sort of fake it with ajax, but even that is just sending a request to the server, which is run separately, and returns a result to the page, to be processed by a different function. It would get more complicated that your attempt.
PHP is evaluated on the server side. JavaScript is evaluated on the client side. That is to say: when a user makes a request to the server, the php is evaluated on the server, the resulting output is sent to the user, if there is javascript involved, it is evaluated on the client, after the php has evaluated.
This means that PHP can give messages to javascript, but javascript cannot send messages to php. In your code it looks like you want php to evaluate the user input that javascript is taking. This cannot be done because when the javascript is running, the php is already finished.
One way you could provide the functionality you want is to write php code to write the code for an array in javascript, containing all usernames. The javascript could then look through this array to tell the user if the username is taken. This has some flaws though, if you have a lot of users, you will be transmitting a lot of text to a new user. This may be a security problem too because everyone would be able to know all the user names of all the people registered with the site, there is also the potential for someone to load the page, type in their user name, wait a long time, have someone else create an account with their same name, and then the first person come back, submit the page, and then you will have two users with the same user name.
It may be easier, but less fun, to write the whole site in php first, and after it's all working, add the javascript to spruce up functionality.

Categories

Resources