PHP deleting variable after new form - php

In my code, I have two forms for users to select options. The first variable will save but as soon as the user submits the second form, the variable from the first form is no longer saved.
<div class = "school">
<h3>Please select the university you previously attended</h3>
<form action = "" method = "post" name = "school_form">
<select name="school" size ="10">
<?php
//shows options for $selected_school
$sql = "SELECT DISTINCT school FROM data;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0){
while($row = mysqli_fetch_assoc($result)){
// inserts all data as array
echo "<option>". $row['school'] ."</option>";
}
}
?>
</select>
<br>
<input type ="submit" name = "submit_school" value = "Enter">
</form>
<?php
//saves selected option as $selected_school
if(isset($_POST['submit_school'])){
$selected_school = mysqli_real_escape_string($conn, $_POST['school']);
echo "You have selected: " .$selected_school;
}
?>
</div>
<div class ="courses">
<h3>Please select the courses you took</h3>
<form action = "" method ="post" name ="course_form">
<?php
//user shown options for courses
$sql2 = "SELECT transfer_course, transfer_title FROM data WHERE school = ? ORDER BY transfer_course ASC";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql2)) {
echo "SQL statement failed";
} else {
mysqli_stmt_bind_param($stmt, "s", $selected_school);
mysqli_stmt_execute($stmt);
$result2 = mysqli_stmt_get_result($stmt);
while($row2 = mysqli_fetch_assoc($result2)){
echo "<input type='checkbox' name ='boxes[]' value = '" . $row2['transfer_course'] . "' >" . $row2['transfer_course'] . "<br>";
}
}
?>
<br>
<input type ="submit" name = "submit_courses" value = "Enter">
</form>
<br>
<?php
//saved selected option(s) as $selected_course
if(isset($_POST['submit_courses'])){//to run PHP script on submit
if(!empty($_POST['boxes'])){
foreach($_POST['boxes'] as $selected_course){
echo "You have selected: " . $selected_course . "</br>";
}
}
}
?>
</div>
<div class = "output">
<h3>Course Equivalency</h3>
<?php
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " . $selected_school . " AND transfer_course = " . $selected_course . "";
$result3 = mysqli_query($conn, $sql3);
if($result3)
{
while($row3 = mysqli_fetch_assoc($result3)){
echo $row3['arcadia_course'] . " " . $row3['arcadia_title'] . "<br>";
}
} else {
echo "failed";
echo $sql3;
}
?>
So by the time I get to my next sql statement
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " . $selected_school . " AND transfer_course = " . $selected_course . "";
When the school is selected, it saves the variable, but when the course is selected, $selected_school becomes blank again.
I already have session_start() at the top of the page.

You can used session variable ,it will help to make data accessible across the various pages .
So,whenever form get submitted you can save that value in session and retrieve it anytime.In top of your php file you need to start session i.e session_start(); .Then in your code
<?php
//saves selected option as $selected_school
if(isset($_POST['submit_school'])){
$_SESSION['selected_school ']=$selected_school;// here you are storing value to session
$selected_school = mysqli_real_escape_string($conn, $_POST['school']);
echo "You have selected: " .$selected_school;
}
?>
Same you can do with your $selected_course also .Then you can passed value to your query like below :
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " .$_SESSION['selected_school ']. " AND transfer_course = " .$_SESSION['selected_course']. "";
For more information refer here

It looks like your option doesn't have a value it is passing. Try this in your first form while loop:
echo '<option value="' . $row['school'] . '">' . $row['school'] . '</option>';
It looks like there may be some more issues you are having as well. If this doesn't fix your issue, I'll dig deeper.
EDIT: Then, yes, as others have suggested, you probably want to add a hidden input field to pass that variable value on the second form submit as well.
What we are saying about the hidden input field is this:
<input type="hidden" name="selected_school" value="<?php if(isset($selected_school) echo $selected_school; ?>">

Related

My php variable reverts back to original value after resetting its value in a foreach loop

I have a php page that interacts with a database. I am trying to display data from the database as options for a user to select. I am trying to record which option a user selects but the variable I use ($a_game_id) to record which button is clicked gets reverted back to its original value after submitting another form. I have tried declaring the variable as global within the loop and using session variables.
$a_game_id = 9;//starting value - it changes from 9 as desired, but reverts back when another form is submitted
$sql = "SELECT * FROM nbagames WHERE date = '" .$date ."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
global $a_game_id;
// output data of each row
$results = $conn->query($sql);
$resultset = array();
while($a_row = $results->fetch_assoc()){
$resultset[] = $a_row;
}
foreach ($resultset as $row){
echo "<form action='display_lines.php' method='POST'>
<br>" . $row["away"] . " " . $row['away_spread'] . "---TOTAL AVAILABLE: " . $away_sum_array[$row['game_id']].
" <input type='submit' value='Bet " . $row['away'] ."' name='" . $row['game_id']."A' />
at " . $row["home"] . " " . $row['home_spread'] . "---TOTAL AVAILABLE: " .$home_sum_array[$row['game_id']]. "
<input type='submit' value= 'Bet " . $row['home'] ."' name='" . $row['game_id']."H' /> " . $row['date'] . "
</form>
<br>";
///HERE $a_game_id has gets the desired value
if(isset($_POST[$row['game_id'].'H'])){
$a_game_id = intval($row['game_id']);
}else if(isset($_POST[$row['game_id'].'A'])){
$a_game_id = intval($row['game_id']);
}
}
} else {
echo "<br> 0 results";
}
$sql = "SELECT * FROM nbagames WHERE date = '" .$date ."'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
if(isset($_POST[strval($row['game_id']).'H'])){
echo '<h3>'.$row['game_id'].'<br>';
echo $row['home'].' '.$row['home_spread'].'<br>';
$team = $row['home'];
$team_spread = $row['away_spread'];
echo '<form action="display_lines.php" method="post">
<input type="text" name="new_bet_amount" placeholder="Enter Bet Amount">
<input type="submit" name="new_bet_submit" value="Submit Bet">
</form></h3>';
}
else if(isset($_POST[strval($row['game_id']).'A'])){
echo '<h3>' .$row['game_id'].'<br>';
echo $row['away'].' '.$row['away_spread'].'<br>';
$team = $row['away'];
$team_spread = $row['away_spread'];
echo '<form action="display_lines.php" method="post">
<input type="text" name="new_bet_amount" placeholder="Enter Bet Amount">
<input type="submit" name="new_bet_submit" value="Submit Bet">
</form></h3>';
}
}
if(isset($_POST['new_bet_submit'])){
//HERE $a_game_id reverts back to its original value which is undesirable
$sql3 = "INSERT INTO placed_bets (user_id, game_id, bet_amount, game_date) VALUES ('".$_SESSION['id']."', '".$a_game_id."', '".$_POST['new_bet_amount']."', '".$date."')";
echo $a_game_id.'<br>';
if ($conn->query($sql3) === TRUE) {
echo "<br><h3>BET PLACED SUCCESSFULLY</h3><br>";
} else {
echo '<h3>Error placing bet<br>';
echo $conn->error;
echo '</h3>';
}
}
Thank you for taking a look
Do you mean "when I make another request all my global variables get reset?" If so, yes, that's how they work. Each request is completely independent of others. They do not share variables or other data. All you get is what's in $_SESSION, $_GET, $_POST and $_COOKIE.
If you need to persist between requests you must put that in the session, the database, or something persistent.
If you're used to code where the process persists and the variables stick, like in client-side situations, that's a mode of thinking you need to completely abandon.

PHP problem with insert into database in while loop

i try to write a website for library as an exercise. I have while loop to display all books in my database. If user is logged in and state(stan) of book(ksiazka) is free(Wolny) it shows button under book. After clicking it takes all free books to database and update their state as hired not only that one which user want. Here is the code, thanks.
$findbook2 ="select ksiazka.id_ksiazka, ksiazka.tytul, ksiazka.id_stan, autor.id_autor, autor.imie_autor, ksiazka.rok_wydania, autor.nazwisko_autor, stan.id_stan, stan.nazwa_stan FROM ((ksiazka inner join autor ON ksiazka.id_autor = autor.id_autor) inner join stan ON ksiazka.id_stan = stan.id_stan);";
$stan = mysqli_query($connect, $findbook2);
while($row = mysqli_fetch_array($stan))
{
echo "Tytuł:" . " " .$row['tytul']." ". "Autor:" . " " . $row['imie_autor']." ". $row['nazwisko_autor']. " ". "Rok wydania" . " ". $row['rok_wydania'] . " ". "Stan ". $row['nazwa_stan']. " ";
if(isset($_SESSION['id_czytelnik'])){
if($row['nazwa_stan']=='Wolny'){
echo '<form method = "GET" action = "ksiazki.php">';
echo '<input type = "submit" name = "submit" value = "Wypożycz"/>';
echo '</form>';
if(isset($_REQUEST['submit'])){
$id_czytelnik = $_SESSION['id_czytelnik'];
$id_ksiazka = $row['id_ksiazka'];
$data_oddania = date('Y-m-d', strtotime('+30 days'));
$wstaw_ksiazke = "INSERT INTO `wypozyczenie`(`id_wypozyczenie`, `id_czytelnik`, `id_ksiazka`, `id_pracownik`, `data_wypozyczenia`, `data_oddania`) VALUES ('','$id_czytelnik','$id_ksiazka',2,NOW(),'$data_oddania')";
if(mysqli_query($connect, $wstaw_ksiazke)){
$update = "Update ksiazka set id_stan = 3 where id_ksiazka = '$id_ksiazka'";
if(mysqli_query($connect, $update)){
echo "Wypozyczyłeś książkę";
}
}
}
}
}
echo "</br>";
}
Consider the statement if(isset($_REQUEST['submit'])) which is always true inside your while loop after clicking submit as it is not unset anyway.It causes repeated execution of a statement while the Array is not empty.

How do I check 1st $_GET for a value and print or check 2nd and print if value is different?

To clarify title, here's my code. It's not working--I'm sure it's wrong. But I don't know if I'm close or far away from the answer. I have an "Any" option that I want to reveal everything in my database as opposed to the selected option which would only reveal specific rows. I'm not sure how to display the former. Thanks!
$Interest = $_GET['interestId'];
$sql = "SELECT * from User WHERE (Interest1 = '$Interest' OR Interest2 = '$Interest' OR Interest3 = '$Interest' OR $Interest = 'Any Interest');";
$result = mysqli_query($link, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<p>";
echo Name . ": ";
echo $row['Fname'] . " ";
echo $row['Lname'] . "<br><br>";
echo Interests . ": ";
echo $row['Interest1'] . ", ";
echo $row['Interest2'] . ", ";
echo $row['Interest3'] . "<br><br>";
echo Website . ": ";
echo $row['Website'] . "<br><br>";
echo Personal_Statement . ": <br><br>";
echo $row['PersonalStatement'] . "<br><br>";
echo Contact . ": ";
echo $row['Phone'] . "<br>";
echo $row['Email'];
echo "</p>";
}
} else {
echo "<h2>Drat!</h2> There's currently no one with the interest of $Interest!";
}
Now it doesn't return anything for any selection.
So if $Interest is "Any" then there should be no filter at all? You can put that logic in the query. For example, consider something like this:
SELECT *
FROM User
WHERE
(Interest1 = '$Interest' OR Interest2 = '$Interest' OR Interest3 = '$Interest')
OR '$Interest' = 'Any'
Under this logic that last OR will match every record if the variable has the string "Any". So you're basically saying "if the record matches the input, OR if the input is Any".
Also, and this is important, your code is wide open to SQL injection. What that means is that you blindly execute any code your users send you. This answer demonstrates the logic of a solution, but there is more you need to do. Start by learning what SQL injection is here, and some quick information about how to meaningfully prevent it here.
the question that you have written is not clarifying us but the went i through you code and perceived u want to fetch the data from database in four situation
1. for any interest
2. interest1
3. interest2
4. interest3
to achieve desired result u would have to make some change to you submission form as well as in php code. here in am going to write both the code for html as well as php hope it would be helpful to you
<form action="action.php" method="GET">
<select type="text" name="interestID"> --select interest type--
<option value="AnyInterest">Any Interest</option>
<option value="interest1">interest1</option>
<option value="interest2">interest2</option>
<option value="interest3">interest3</option>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
// php code
<?php
if(isset($_GET['submit'])){
$interestId = $_GET['interestID'];
// connect with database query
switch($interestId){
case "AnyInterest":
$data = mysql_query("SELECT * FROM user") or mysql_error();
break;
case "interest1":
case "interest2":
case "interest3":
$data = mysql_query("SELECT * FROM user WHERE interestId = '$interestId '") or mysql_error();
break;
}
$count = mysql_num_rows($data);
if($count > 0){
while ($rows = mysql_fetch_assoc($data)){
// write code here to display the content on webpage
}
}else{
header(Location: action.php);
}
?>
I suppose your form/ajax is this:
<input id="anyInterest" name="nome" type="text" />
In php you can do:
$any = $_GET['anyInterest'];
$sql = "SELECT * FROM user WHERE Interest = " +$any "OR Interest = 'Any Interest'";
$result = mysqli_query($link, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
//do something
}
else {
echo "<h2>Drat!</h2> There's currently no one with the interest of $Interest!";
}
Best choice for security:
$any = $this->input->get('anyInterest');
$sql = "SELECT * FROM user WHERE Interest = " +$any "OR Interest = 'Any Interest'";
$result = mysqli_query($link, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
//do something
}
else {
echo "<h2>Drat!</h2> There's currently no one with the interest of $Interest!";
}
If this is not the right answer, could you explain the process better, your idea?

Possible To Use Insert Query In Fetch Array

I am not sure why this hasn't been answered yet will not that I know of, I am wondering if it's possible to add a insert query with in a while loop I have tried,
but it keeps inserting the comment more then it should (say if it finds 4 status updates it will post the comment in the database 4 times)
I know I have the insert query twice this is not the problem as I had the query where it submits a comment to the database the current query is there for testing purposes.
<?php
require_once ("core/connection.php");
require_once ("core/group_functions.php");
//We need to post the message update in to the database
if(isset($mybb->input['post_message_submit'])) {
$post_message_submit = $mybb->input['post_message_submit'];
$post_message = $mybb->input['post_message'];
$comment_post = $mybb->input['comment_post'];
if(($post_message_submit) && ($post_message)) {
$insert_query = $db->query("INSERT INTO " . TABLE_PREFIX . "groups_posts" . "(posted_by, group_name, post_body)
VALUES ('$mybb_username', '$get_group_url' ,'$post_message')");
} else {
echo "<text style='color:red;'> You Must Specify A Message</a></text>";
}
}
echo "
<form action='' method='POST'>
<textarea name='post_message' id='post_message' placeholder='Whats Going On?'></textarea><br>
<input type='submit' name='post_message_submit' value='Post'>
</form>
";
$fetch_index_query = $db->query("SELECT post_id,posted_by,post_body,post_active,group_name FROM " . TABLE_PREFIX . "groups_posts WHERE group_name='$get_group_url'");
while($fetch_index_groups_array = $db->fetch_array($fetch_index_query)) {
$post_id_row = $fetch_index_groups_array['post_id'];
$posted_by = $fetch_index_groups_array['posted_by'];
$g_name = $_fetch_index_groups_array['g_name'];
$g_body = $fetch_index_groups_array['post_body'];
echo"<br>" . "<a href=''> $posted_by </a>" . "<br>" . $gname
. "<br>____________";
$fetch_comments_query = $db->query("SELECT g_name,post_body,comment_by FROM spud_groups_comments WHERE post_id='$post_id_row'");
while($fetch_groups_comments = $db->fetch_array($fetch_comments_query)) {
$post_body = $fetch_groups_comments['post_body'];
echo ("<br>" . $post_body);
}
$insert_query2 = $db->query("INSERT INTO " . TABLE_PREFIX . "groups_comments" . "(comment_by, post_id, post_body)
VALUES ('$mybb_username', '$post_id_row' ,'$comment_post')");
echo "<br>
<form action='' method='POST'>
<input type='text' name='comment_post' placeholder='Comment then Hit Enter'>
</form>
";
}
//We have done everything we need to do we can now exit and not execute anything beyond this point
exit();
?>
Try to instantiate other $DB object for the insert query. i.e. do not use the same one you are using to fetch the array, as the next use will overwrite the result of the first query that you are looping through.

PHP mysql while not assigning variables in correspondence to the database key

so this was working perfect up until an hour ago and since then i have racked my brain to fix it and got nothing, maybe im missing the obvious (thats usually the case).
The code prints out a list of users and a button to ban them in a table, however the problem is if you click ban on say.. the 34th user it bans the first, then if you click ban on the 56th user it bans the second user. If you see my code you should see that that shouldn't be the case (note all other details are perfectly right except for the uID):
$query = mysql_query("SELECT id, full_name, banned, username from `tblUsers`");
while($row = mysql_fetch_array($query)){
$uID = $row['id'];
if($row['banned'] == '0'){
$banBool = '<form id="ban" method="post" action="ban.php?uid='.$uID.'">
<input type="hidden" name="ban" value="" />
<a onclick="document.getElementById(\'ban\').submit();">Ban</a>
</form>'; }else{
$banBool = '<form id="unban" method="post" action="unban.php?uid='.$uID.'">
<input type="hidden" name="name" value="" />
<a onclick="document.getElementById(\'unban\').submit();">UnBan</a>
</form>' ;
}
if($row['banned'] == '1'){
$status = 'Banned';
}else{
$status = 'Active';
}
echo "<tr><td>" . $row['username'] . " " . $uID . "</td><td>" . $banBool . "</td><td>" . $status . "</td><td>" . $row['full_name'] . "</td></tr>";
}
The issue is in the action="unban.php?uid='.$uID.' as when i trace the path the id is always the lowest number (top result)
ban.php
<?php
include '../../includes/dataBase.class.php';
sql::connect();
if(!sql::checkAdmin() == 1){
header("Location: ../myaccount.php");
}
if(!isset($_GET['uid'])){
header("Location: users.php?action=1");
}
$uid = $_GET['uid'];
$ip = $_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO `uipBan` (`ip`) VALUES ('$ip')")or die(mysql_error());
mysql_query("UPDATE tblUsers SET banned = '1' WHERE id = '$uid'")or die(mysql_error());
//header("Location: users.php?action=1");
echo $uid;
?>
You provide a form for each user which bans/unbans that user. The problem is in your form id because they're not unique. When you click on any Ban/UnBan link, JavaScript searches for the ban/unban element, finds the first one and submits that one.
The solution is very easy:
$query = mysql_query("SELECT id, full_name, banned, username from `tblUsers`");
while($row = mysql_fetch_array($query)){
$uID = $row['id'];
if($row['banned'] == '0'){
$banBool = '<form id="ban' . $uID . '" method="post" action="ban.php?uid='.$uID.'">
<input type="hidden" name="ban" value="" />
<a onclick="document.getElementById(\'ban' . $uID . '\').submit();">Ban</a>
</form>'; }else{
$banBool = '<form id="unban' . $uID . '" method="post" action="unban.php?uid='.$uID.'">
<input type="hidden" name="unban" value="" />
<a onclick="document.getElementById(\'unban' . $uID . '\').submit();">UnBan</a>
</form>' ;
}
if($row['banned'] == '1'){
$status = 'Banned';
}else{
$status = 'Active';
}
echo "<tr><td>" . $row['username'] . " " . $uID . "</td><td>" . $banBool . "</td><td>" . $status . "</td><td>" . $row['full_name'] . "</td></tr>";
}
I just included the User ID on every form and JS call so that they are unique. (Also, your second hidden field had the name as name)
Yes, #MrFusion nailed it (+1). But I still don't see why you aren't simply doing something like this:
<?php
$query = mysql_query("SELECT id, full_name, banned, username from `tblUsers`");
while($row = mysql_fetch_array($query)) {
echo "<tr><td>{$row['username']}</td><td>{$row['id']}</td>";
if($row['banned'] == '0') {
echo "<td>Ban</td>";
}
elseif($row['banned'] == '1') {
echo "<td>Banned (Unban)</td>";
}
else {
echo "<td>Active</td>"; # Not sure what this is for in your original code
}
echo "<td>{$row['full_name']}</td></tr>";
}
?>
Then just make admin.php
<?php
include "../../includes/dataBase.class.php";
sql::connect();
if(!sql::checkAdmin() == 1){
header("Location: ../myaccount.php");
}
if(!isset($_GET['ban']) AND !isset($_GET['unban'])){
header("Location: users.php?action=1");
}
if(isset($_GET['ban'])) {
$uid = mysql_real_escape_string($_GET['ban']);
mysql_query("UPDATE tblUsers SET banned = '1' WHERE id = '{$uid}'") or die(mysql_error());
//I don't know what the following two lines are for
//but they seem to IP-ban the admin himself: you're banning the IP address
//of the user doing the ban, not the IP address of the user you are banning.
$ip = $_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO `uipBan` (`ip`) VALUES ('{$ip}')") or die(mysql_error());
}
elseif(isset($_GET['unban'])) {
$uid = mysql_real_escape_string($_GET['unban']);
mysql_query("UPDATE tblUsers SET banned = '0' WHERE id = '{$uid}'") or die(mysql_error());
}
header("Location: users.php?action=1");
?>
Note the importance of escaping your user input using mysql_real_escape_string, even if it's coming from a trusted user: this prevents SQL injection which could result in you losing your entire database :)

Categories