Hello everyone I was trying to create a page for drag n drop in which I want to maintain floor_id when it reloads.
I'm getting floor_id from previous page on click of button, and i'm adding it to session so that the next time the page reloads it doesn't get any error.
But when I select other option from the previous page,same value in the session is stored,the value doesn't get assigned using the post method.Can anyone provide some idea.
this page is from where i get the selected id.
?>
<form action="rooms.php" method="post">
<select name="fl_type" id="ft" >
<option value=0>Select Floor</option>
<?php
while($row=mysqli_fetch_row($result))
{
?>
<option value="<?php echo $row[2];?>"><?php echo $row[2];}?></option>
<input type="submit" name="room" value="generate" />
</form>
<br />
</body>
here I'm fetchig the code and getting id.
<?php
$i=0;
require("config.php");
$id=$_SESSION['restid'];
if(isset($_SESSION['ft'])){
$ft=$_SESSION['ft'];
$query="select floor_id,width,height from floor_m where floor_type='".$ft."' and rest_id='".$id."'";
$res1=mysqli_query($con,$query);
$row1=mysqli_fetch_row($res1);
$fd=$row1[0];
$w=$row1[1];
$h=$row1[2];
//echo $fd;
$query2="select room_as_id,width,height,start_x,start_y,room_id,room_type_id from room_m where floor_id='".$fd."'";
//echo $query2;
$res2=mysqli_query($con,$query2);
while($row2=mysqli_fetch_row($res2))
{
$room_type_id=$row2[6];
$query3="select room_type from room_type where room_type_id='".$room_type_id."'";
$res3=mysqli_query($con,$query3);
$row3=mysqli_fetch_row($res3);
$room='room_id'.$i;
$width='width'.$i;
$height='height'.$i;
$start_x='x'.$i;
$start_y='y'.$i;
$room_id='room'.$i;
$room_type='roomt'.$i;
$response[$room]=$row2[0];
$response[$width]=$row2[1];
$response[$height]=$row2[2];
$response[$start_x]=$row2[3];
$response[$start_y]=$row2[4];
$response[$room_id]=$row2[5];
$response[$room_type]=$row3[0];
//echo $response[$room_id];
$i++;
/*echo '<script>var data1 = '.json_encode($row2[0]).';var data2 = '.json_encode($row2[1]).';var data3 = '.json_encode($row2[2]).';var data4 = '.json_encode($row2[3]).';var data5 = '.json_encode($row2[4]).';//
</script>*/
}
$i--;
$response['count']=$i;
echo '<script> var data='.json_encode($response).'</script>';
$wd=500/$w;
$_SESSION['wd']=$wd;
$_SESSION['ft']=$ft;
$_SESSION['fid']=$fd;
echo '<script>var pf = '.json_encode($_SESSION['wd']).';
var ft='.json_encode($_SESSION['ft']).';
var fid='.json_encode($_SESSION['fid']).';</script>';
$ht=$h*$wd;
}
else{
$ft=$_POST['fl_type'];
//echo $ft;
}
$sql="select width,height,floor_id from floor_m where floor_type='".$ft."' and rest_id='".$id."'";
//echo $sql;
$res=mysqli_query($con,$sql);
$row=mysqli_fetch_row($res);
$w=$row[0];
$h=$row[1];
$fid=$row[2];
$wd=500/$w;
$wd=round($wd);
//echo $wd;
$_SESSION['wd']=$wd;
$_SESSION['ft']=$ft;
$_SESSION['fid']=$fid;
echo '<script>var pf = '.json_encode($_SESSION['wd']).';
var ft='.json_encode($_SESSION['ft']).';
var fid='.json_encode($_SESSION['fid']).';</script>';
$ht=$h*$wd;
//echo $wd,$ht;
?>
To use the $_SESSION variable, you will need to start a session at the top of all your PHP scripts. This can be done as so:
session_start()
Again, it must go at the top of every PHP script you intend to use the $_SESSION variable. If you don't, it will go on without error, but won't save.
Related
I wanted to store list of users from php form in a php session
I defined an empty array at the beginning of the session and tried to
collect the user names at every submit.
session_start();
$persons=array();
if (isset($_POST)) {
$_SESSION['val']=$_POST['val'];
$persons=$_SESSION['val'];
}
foreach($persons as $d){
echo $d;
echo '</br>';
}
<form action="exam.php" method="post">
Enter a new Person: <input type="text" name = "val">
<input type="submit" name = "send">
</form>
I expected to have the list of persons I submitted returned from the
array
but every time I submit, the last submit replaces the first one.
You are overwriting the array each time:
$persons = $_SESSION['val'];
In order to push data to an array in php you must do it this way:
$persons[] = $_SESSION['val'];
If what you want to is store all persons on session, without overwriting them each time you first need to check if session exist, if not, create it.
if(!isset($_SESSION['persons'])){
$_SESSION['persons'] = array()
}
And then change how you store the info in the session, example:
$_SESSION['persons'][] = $_POST['val'];
Then you can do:
foreach($_SESSION['persons'] as $d){
echo $d;
echo '</br>';
}
So the code will look like:
session_start();
$persons=array();
if(!isset($_SESSION['persons'])){
$_SESSION['persons'] = array();
}
if (isset($_POST)) {
$_SESSION['persons'][] = $_POST['val'];
}
foreach($_SESSION['persons'] as $d){
echo $d;
echo '</br>';
}
<form action="exam.php" method="post">
Enter a new Person: <input type="text" name = "val">
<input type="submit" name = "send">
</form>
I did not compile the code, check for syntax errors, but the procedure is right.
Please bear in mind, I'm very new to PHP. I've only started taking it this semester at my school.
Here's what I want to eventually do: I have a senior project where I'm building a computer repair system. In the repair MySQL table, I have a bunch of fields and one of them is CustomerID (so I know which customers had which repair). I want to have a drop drown of customer's names, and then when I click on it, some how attach that customer's ID to a variable so I can do an INSERT statement. In order to partially achieve this, I've done things in smaller parts. The small part I have working is when I select a dropdown value, it outputs it to the screen, but that's in the javascript function.
Here's my code:
<?PHP
include('session.php');
$db_name = "";
$mysql_username = "";
$mysql_password = "";
$mysql_server = "";
$mysqli = new mysqli($mysql_server, $mysql_username, $mysql_password,
$db_name);
$query = "SELECT custID, CONCAT(custFirstName, ' ', custLastName) as
Customer_Name FROM customer";
$result = mysqli_query($mysqli, $query);
echo "<select name ='names' id='myselect' onchange = \"myFunction()\">";
while ($row = mysqli_fetch_array($result)){
echo "<option value = '" . $row['custID'] . "'>" . $row['Customer_Name'] . "
</option>";
}
echo "</select>";
echo "<p>When you select a customer name, a function is triggered which
outputs the ID of the selected customer.</p>
<p id=\"demo\"></p>
<script>
function myFunction() {
var x = document.getElementById(\"myselect\").value;
document.getElementById(\"demo\").innerHTML = x;
}
</script>";
$content = "<script> document.write(x) </script>";
echo "<br> <br> The technician ID = $sTechID <br> <br> The customer ID = $content";
?>
I can output the ID to the screen with the Javascript function, but when I try to store "x" into a php variable, it doesn't work. In chrome, the inspector says that X is undefined.
A side note: I made a test file with this code and it worked:
<?PHP
echo "
<script>
var x = \"hello\"
</script>";
$content = "<script> document.write(x) </script>";
echo "$content <br> <br> $content";
?>
Because the above code worked, I don't understand why my bigger code is not working.
I understand that my code is a mess, but any help will be greatly appreciated. Thanks!
PHP is a back-end language and can't detect front-end events such as click, change, etc.
In your larger code, the value of x will only be defined once the event is fired(onchange), that's when the select input changes. Javascript works that way, but PHP doesn't. Once PHP sends a response the first time, its job is done.
This is when you will want to use forms or Ajax.
Using forms would be a good start.
Quick note, it's good practice to try to keep HTML, CSS and JS separate from PHP as much as possible.
...
$result = mysqli_query($mysqli, $query);
?>
<form method='post' action='insert.php' /> <!-- Link to php file to insert data to database -->
<select name ='names' id='myselect' onchange = "myFunction()">
<?php
while ($row = mysqli_fetch_array($result)){
echo "<option value = '" . $row['custID'] . "'>" . $row['Customer_Name'] . "
</option>";
}
?>
</select>
<input type="submit" value="submit" /> <!-- You will need a button to submit the data -->
</form>
<p>When you select a customer name, a function is triggered which
outputs the ID of the selected customer.</p>
<p id="demo"></p>
And now your insert.php file would look like:
<?php
// Get data from that was posted from the form
$customer_id = $_POST['names'];
// Now do whatever with the customer ID
echo $customer_id;
I think you need a better understanding of PHP in general. PHP is executed BEFORE the browser executes the html/js that you've echo'd to it. The reason this works:
<?PHP
echo "
<script>
var x = \"hello\"
</script>";
$content = "<script> document.write(x) </script>";
echo "$content <br> <br> $content";
?>
is because you are writing JS to the dom and it's being executed once your browser reads it. If you run a var_dump($content); you will see that what you have stored in that PHP variable is not the result of x but actually a literal string that contains the text "<script> document.write(x) </script>".
The line echo "$content <br> <br> $content"; prints "<script> document.write(x) </script> <br> <br> <script> document.write(x) </script>"; to the DOM, which in turn is run as JS in the browser.
If you want your drop down selection to do something in PHP I would suggest triggering a JS function on change of the drop down that in turn sends an AJAX request to a separate PHP file that does what you need to do there and returns it to your function. This way you can update the HTML without navigating to another PHP page.
Im scratching my head once again and need your help.
What I have is a form that submits to a second page, with sessions enabled, i am storing the name value 2 fields on the form and setting their value names in the session so that if a user returns to a page their Username will already be populated in the text field. I have this working ok ..
The second page i am storing
$_SESSION['captured_by'] = $_POST['captured_by'];
$_SESSION['prid'] = $_POST['prid'];
HOWEVER..
Where i am stuck is getting a select option that is populated from a query to have the same functionality, so that when a user returns to the page, the selected option which has been saved in the session will keep that selection in the box rather than having to select it again.
Here is what i have as follows:
Form Page:
This does work and does return the captured_by text when i return to the page
<fieldset><legend>Lesson Added By *</legend>
<p class="multiple">(Required - Logon ID)</p>
<input name="captured_by" maxlength="12" id="searchfield" type="text" value="<?php
if(isset($_SESSION['captured_by'])){print stripslashes($_SESSION['captured_by']);}
else{print " ";} ?>">
</fieldset>
The problem code is this
<select id="searchfield" name="prid">
<?php
$query = "SELECT project_name, project_id FROM ll_project ORDER BY project_name ASC;";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['project_id'].'">'.$row['project_name'].' | '.$row['project_id'].'</option>';
}
?>
</select>
</fieldset>
I need to edit this last section so that it picks up the previously selected option value from the stored session value.
Hope someone can help?
Many Thanks.
Tazzy
Try this,
<select id="searchfield" name="prid">
<?php
$query = "SELECT project_name, project_id FROM ll_project ORDER BY project_name ASC;";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['project_id'].'"'. ((isset($_SESSION['prid']) && !empty($_SESSION['prid']) && ($_SESSION['prid'] == $row['project_id'])) ? 'selected="selected"' : '') .'>'.$row['project_name'].' | '.$row['project_id'].'</option>';
}
?>
</select>
</fieldset>
You could simply use ajax when someone change the selection.
$('select#searchfield').change(function(){
$.ajax({
type: 'GET',
url: 'changeSession.php', // This is the url that will be requested
data: {prid: $('select#searchfield').val()},
success: function(html){
// nothing really happens because you simply update your session
},
dataType: 'html'
});
});
Then in changeSession.php
if(isset($_GET['projectId']{
$_SESSION['captured_by'] = $_POST['prid'];
}
That should do the job. You then add a condition when the form is generated and you add selected='selected' if $_SESSION['prid'] is not empty.
Is it possible to automatically get first item from drop down list to the input on page load? For example, the drop down list have 2 options: happy& sad. When the page loads, I want happy to be in the input on page load. So far, I got an empty input where the user need to select the option on the drop down list.
Jquery code:
<script type="text/javascript">
$(document).ready(function() {
$("#username_select").change(function() {
$("#username_custom").val($(this).val());
});
});
</script>
username_custom id:
<input id="username_custom" name="custom" value="
<?php
if(isset($_POST['getusername'])) {
$getusername = $_POST['getusername'];
echo "".$getusername."";
}
if(empty($_POST['username'])) {
echo "".$row['username']."";
}
?>
">
username_select id:
<select id="username_select" name="getusername">
<?php
$username = $_SESSION['username'];
$result = mysql_query("SELECT username FROM account WHERE websiteusername='".$username."'");
while($row = mysql_fetch_array($result)) {
echo "<option value='".$row['username']."'>".$row['username']."</option>";
}
?>
</select>
To show the selected value of select in input
$("#YourInputId").val($("#username_custom").val());
To set the first option text of select
$("#YourInputId").val($("#username_custom option:eq(0)").text());
To change the textbox value on change of select
$(document).ready(function() {
$("#username_select").change(function() {
$("#username_custom").val($(this).val());
$("#YourInputId").val($("#username_custom").val());
});
});
In this line
echo "<option value='".$row['username']."'>".$row['username']."</option>";
you can add SELECTED to the option you want to get selected. You can use a variable in the while loop to find out which item you are at and get that item selected;
For ex.
$ctr = 0;
while($row = mysql_fetch_array($result)) {
echo "<option value='".$row['username']."'" . ( $ctr == 1 ? "selected" : "" ) . ">".$row['username']."</option>";
$ctr++
}
Hope this helps.
Cheers
In this case you can also call change event of drop down.
$("#username_select").change();
I am using PHP 5 to create a query page for a MySQL database with 2 tables "students" and "teachers". I have created a combo box which can allow users to view and select the 2 tables from the combo box via a "submit" button after selecting from the combo box.
However the problem with the script is that I want to verify if the "submit" button works which I created a "echo.php" to echo out the value of the combo box and submit button. Overall the idea is to do a query like these steps:
1) User selects value from combo box "teacher" or "student".
2) User clicks submit button.
3) After clicking submit button, user is redirected to "echo.php"
4) "echo.php" should output/echo out either "teacher" or "student".
The codes for script:
<?php
include "db_connect.php";
{
?>
<td valign=top><strong>Name:</strong></td>
<td>
<?php
echo "<form name = \"queryEquipTypeForm\" method = \"post\" action
=\"select_table.php\">";
echo '<select name=\"table\">';
echo "<option size =30 selected>Select</option>";
$result = mysql_query("show tables");
if(!$result) trigger_error("Query Failed: ". mysql_error($db), E_USER_ERROR);
if(mysql_num_rows($result))
{
while($table_array = mysql_fetch_array($result))
{
echo "<option>$table_array[0]</option>";
}
echo '</select>';
echo '</form>';
if(!$_POST['submit'])
{
?>
<form method="post" action="select_table.php">
<input type="submit" name="submit" value="Submit">
</form>
<?php
}
else
{
echo '<script type="text/javascript">
alert("Redirecting you to echo.php page");
window.location="echo.php"</script>';
}
}
else
{
echo "<option>No Names Present</option>";
}
}
?>
</td>
The codes for "echo.php" :
<?php
include "select_table.php";
echo "data is : ".$_POST['table'];
?>
The output of echo.php would be exactly the same as "select_table.php" with the cobo box and the "data is: " without the "teachers" or "student" word as its being redirected to echo.php.
I'm not quite sure what exactly what you want to do, but as michaeltwofish already pointed out, redirecting to another page using javascript will make you lose the post data. Also you seem to echo two <form> elements when the select_table.php is called without post data, one with only a submit button, while your first form is missing the button.
Normally, you would want your php script to either output the form with the combobox where the user can select the table, or, if there was post data (meaning that the user selected a value), the results of the selection, kinda like the following:
<?php
if(isset($_POST['table'])) {
print "Selected element: " . $_POST['table'];
} else {
echo '<form method="post" action="select_table.php">';
echo '<select name="table">';
// here should be your SQL query and the combobox options generation
echo '</select>';
echo '<input type="submit" />';
echo '</form>';
}
?>
When the form is submitted, you redirect to echo.php, but that means you lose the POST data. You need to think carefully about the flow of your application, because what you have seems a bit confused.