How to make a dropdown stay when processing different If/Else blocks? - php

I'm new to PHP-to-Mysql so I'm using the mysql_* function which others have stated to be unsupported anymore. But I find this place the best to ask my question since I can't find anyone with a similar question.
So basically, my problem is how to make a dropdown list stay which is inside an IF/ELSE block. When it is passes a value (submit) through another IF/ELSE block, it basically disappears so I'm trying a code where I don't have to re-write the entire dropdown code inside the next IF/ELSE block. Since what I'm trying is to show a textbox depending on what option is selected inside the dropdown (it has an auto-submit function). Is this possible? Or I have to resort to other libraries (jQuery,javascript etc.)?
Here's a part of the code if it helps:
elseif($_POST['question'] == edit ){
$res = mysql_query("SELECT questionID FROM questions");
echo "<form action='' method='post'>
Edit Question No.
<select name='question_select' onchange=this.form.submit()>
<option value=null selected>--</option>";
while($row = mysql_fetch_array($res))
{
echo "<option value=\"".$row['questionID']."\">".$row['questionID']."</option>";
}
echo "</select></form>";
}
//TEXTBOX TO BE DISPLAYED WHEN A NUMBER IS SELECTED IN EDIT EXISTING
if (isset($_POST['question_select'])){
$res = mysql_query("SELECT question FROM questions WHERE questionID='{$_POST['question_select']}'");
$row = mysql_fetch_assoc($res);
echo "Editing Question ",$_POST['question_select'],"<br>
<form action='' method='post'>
<textarea name='edited_question' rows='4' cols='50'>",$row['question'],"</textarea><br>
<input type='submit' name='save' value='Save'>
<input type='hidden' name='question_num' value='{$_POST['question_select']}'>
<input type='submit' name='cancel' value='Cancel'>
</form>";
}
//PASSING OF VALUES WHEN SAVE IS PRESSED
if (isset($_POST['save'])){
$edited_question = trim($_POST['edited_question']);
mysql_query("UPDATE questions SET question='$edited_question' WHERE questionID='{$_POST['question_num']}'") or die(mysql_error);
header("Location:admin_questions.php");
}

use jquery for that.it is easy and simple to use.
for depanding dropdown,jquery code is:
$(document).ready(function(e) {
$("#abc").change(function()
{
var firstfeild= $("#firstfeild").val();
$.post("getdata.php",{"firstfeild":firstfeild},function(data)
{
$("#abc").html(data);
});
});
});
and in getdata.php, just write mysql query.

function renderDropdown($res)
{
echo "
<select name='question_select' onchange=this.form.submit()>
<option value=null selected>--</option>";
while($row = mysql_fetch_array($res))
{
echo "<option value=\"".$row['questionID']."\">".$row['questionID']."</option>";
}
echo "</select>";
}
if(1==1)
{
echo "<form action='' method='post'>Edit If Question No.";
renderDropdown($res);
echo "</form>";
}
else
{
// $someOtherRes
echo "<form action='' method='post'>Edit Else Question No.";
renderDropdown($someOtherRes);
echo "</form>";
}

Related

set php get set variable with hyperlink

I have two .php pages, one that returns the contents of a table including an id for each entry along with an html text input and another that retrieves the details and allows me to update the record.
I'd like to store the id of the entry by clicking on the list item using a href rather than having to text input the id and submit.
choose.php
echo "<ul>";
while ($row=mysql_fetch_array($result)) {
$reference=$row[reference];
$name=$row[name];
echo "<li>$reference, $name</li>";
}
echo "</ul>";
session_start();
$_SESSION['regName'] = $reference;
mysql_close($link);
?>
<form method="get" action="update.php">
<input type="text" name="regName" value="">
<input type="submit">
</form>
update.php
session_start();
$reference = $_GET['regName'];
echo "Your selection id is: ".$reference.".";
$query="SELECT * FROM firsttable WHERE reference='$reference'";
$result=mysql_query($query) or die("Query to get data from firsttable failed with this error: ".mysql_error());
$row=mysql_fetch_array($result);
$name=$row[name];
echo "<form method=\"POST\" action=\"updated.php\">";
echo "<p>";
echo "<label for=\"name\">Name: </label><input type=\"text\" id=\"name\" name=\"name\" size=\"30\" value=\"$name\"/>";
echo "<p><input type=\"submit\"></p>";
echo "</form>";
I apologise if this seems very obvious, I've only started to learn php as of today and it's much more complicated than anything I've done up until now.
Thanks
James
Answering your question, you just need to use HREF parameter of A tag. This will make an active link, which will contain a reference you need:
echo '<ul>';
while ($row = mysql_fetch_array($result)) {
$reference = $row[reference];
$name = $row[name];
echo '<li><a href=/update.php?regName='.$reference.'>'.$name.'</a></li>';
}
echo '</ul>';
?>
Read here for more details about passing data via GET\POST: https://www.w3schools.com/tags/ref_httpmethods.asp
And as you were told above, please consider rewiring the code as it is totally unsafe and must not be used anyhow besides some very basic concept proof. And only inside intranet or local machine.
Good luck!

Automatic marking

Am puzzled about how to make a system that can automatically mark.
Am using a variable $count in PHP and is the one storing data from the checked radio button.
I have not tried to check on how to do it and am just afraid of how to do it.
I have the following codes which out puts the data in radio buttons
<?php
$get=mysql_query("select * from courses where courseid='".$cid."'");
while ($picked=mysql_fetch_array($get)) {
echo "<b>The questions for ".$picked['coursename']." are:</b><br><br>";
}
$query=mysql_query("select * from papers where cid='".$cid."'");
if (mysql_num_rows($query)>0) {
$count=1;
while ($row=mysql_fetch_array($query)) {
echo "Qn ".$count.". ".$row['question']."<br><input type='radio' name='".$count."' value='A'>".$row['A']."<br><input type='radio' name='".$count."' value='B'>".$row['B']."<br><input type='radio' name='".$count."' value='C'>".$row['C']."<br><input type='radio' name='".$count."' value='D'>".$row['D']."<br><br>";
$count++;
}
}else{
echo "No papar has been set yet for this paper.";
}
?>
<input type="submit" name="but" value="Submit Assessment">
and it outputs the following:
And the database is like:

Retrieve DIV-content inside a Form

I have been searching for help from various forums and similar posts, but without any progress.
I have three pages, one that lets me insert information about projects into my database, a second that show the images and names of every project in the database, and a third page which I want to have a function that shows the image and name of the selected project in the second page.
Code on the second page(dashboardadmin.php):
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$conn = mysqli_connect("localhost","root","","wildfire");
if(mysqli_connect_errno())
{
echo mysqli_connect_error();
}
$sql= "SELECT pid, project_name, image, image_type FROM project";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
echo "<form action='omprojekt.php' method='post'>
<div id='comp' name='comp'>
<img src=pic.php?pid=".$row['pid']." width=100xp height=100xp/>"." ".$row['project_name']."
</div>
<input type='submit' name='submit' value='Choose' />
</form>";
}
}
else {
echo "0 results";
}
mysqli_close($conn);
?>
Code on the third page (omprojekt.php):
<?php
/* Tried both of the $val variables but of course only one at a time. This is only to show you what I have tried. */
$val = isset($_POST['comp']) ? $_POST['comp'] : '';
$val = $_POST['comp'];
if(isset($_POST['submit'])){
echo "$val";
}
?>
In the last code you can see that I have two $val variables, but I have only used one of them at a time in my codes. The purpose of showing both of them here is to show you that I have tried both of them.
What I want to do is to make the third page show the image and name of the selected project in the second page. As you see, I have tried to retrieve the content from the DIV using the same "name". The problem is that the third page(omprojekt.php) doesn't show any content at all, and not even any errors.
You're expecting the div to submit like an input, but it won't, because it's not an input. So put it in an input.
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
// Don't use and id attribute because you're in a loop and you might have multiple id's with the same value.
echo "<form action='omprojekt.php' method='post'>
<div>
<img src=pic.php?pid=".$row['pid']." width=100xp height=100xp/>"." ".$row['project_name']."
</div>
<input type='hidden' name='pid' value='".$row['pid']."'>
<input type='hidden' name='project_name' value='".$row['project_name']."'>
<input type='submit' name='submit' value='Choose' />
</form>";
}
}
Then on the next page,
$val = (isset($_POST['pid']) && isset($_POST['project_name'])) ?
"<img src=pic.php?pid={$_POST['pid']} width=100xp height=100xp/> {$_POST['project_name']}" : '';
For the sake of completeness, there are a few other things wrong with your code.
1) The width and height attributes on the iamge should have quotes, and do not accept "px", they are just numbers. If you want to use "px" you should use style instead. <img src='' style='width:20px; height:20px;' />
2) You should be escaping user input before running it through your query.
Data will only be sent from a <form> to the action script if it exists in an <input...> HTML tag. You cannot pick data out of randon <DIV> tags etc.
So you could do this by using a hidden input field like this ( this is only one way )
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
echo "<form action='omprojekt.php' method='post'>
<div>
<img src=pic.php?pid=".$row['pid'] .
" style="width:100px;height:100px" /> " .
$row['project_name']."
</div>
<input type='hidden' name='comp' value='" . $row['pid'] . "' />
<input type='submit' name='submit' value='Choose' />
</form>";
}
}
Now when you get to omprojekt.php the $_POST['comp'] variable will exist.
You can have as many hidden input fields as you like so if you want to pass the project_name as well just add another hidden field.

Passing data between PHP webpages from a dynamically generated list

I have a PHP code which generates a dynamic list inside a form like the following, note that the list is built dynamically from database:
echo '<form name="List" action="checkList.php" method="post">';
while($rows=mysqli_fetch_array($sql))
{
echo "<input type='password' name='code' id='code'>";
echo "<input type='hidden' name='SessionID' id='SessionID' value='$rows[0]' />";
echo "<input type='submit' value='Take Survey'>";
}
What I need is to POST the data corresponding to the user choice when he clicks on the button for that row to another page.
If we use hyperlinks with query strings there will be no problem as I'll receive the data from the other page using a GET request and the hyperlinks would be static when showed to the user.
Also I need to obtain the user input from a textbox which is only possible with POST request.
Simply from the other page (checkList.php) I need these data for further processing:
$SessionID=$_POST['SessionID'];
$Code=$_POST['code'];
As I have a while loop that generates the fields, I always receive the last entry form the database and not the one corresponding to the line (row) that the user chosed from the LIST.
I'm going to recommend that you clean up the names of variables so that your code can
at least tell us what it's supposed to do. It should be rare that someone looks at your code
and has a lot of trouble trying to see what you're trying to accomplish :P, ESPECIALLY when you need help with something ;]. I'm going to try some things and hope that it makes doing what you want easier to comprehend and perhaps get you your answer.
It's good to try your best to not echo large amounts of HTML unnecessarily within a script , so firstly I'm going to remove the
echos from where they are not necessary.
Secondly, I'm going to use a mysql function that returns an easier to process result.
$user = mysqli_fetch_assoc($sql)
Third, I don't know if form having a name actually does anything for the backend or frontend of php, so I'm
just going to remove some of the extra crust that you have floating around that is either invalid HTML
or just doesn't add any value to what you're trying to do as you've presented it to us.
And yes, we "note" that you're building something from the database because the code looks like it does =P.
I'm also sooo sad seeing no recommendations from the other answers in regard to coding style or anything in regard to echoing html like this :(.
<?php while($user = mysqli_fetch_assoc($sql)): ?>
<form action="checkList.php" method="post">
<input type='password' name='code' value='<?php echo $user['code'] ?>' />
<input type='hidden' name='SessionID' value='<?php echo $user['id'] //Whatever you named the field that goes here ?>' />
<input type='submit' value='Take Survey' />
</form>
<?php endwhile; ?>
i not sure this is correct
echo '<form name="List" method="post">';
while($rows=mysqli_fetch_array($result))
{
echo "<input type='password' name='code' id='code'>";
echo "<input type='button' value='Take Survey' onclick=show($rows[0])>";
echo "<br>";
}
and javascript
<script>
function show(id)
{
alert(id);
window.location="checkList.php?id="+id;
}
</script>
On checkList.php
$id=$_GET['id'];
echo $id;
You can just check in checkList.php whether $_POST['code'] exists and if exists retrieve $_POST['SessionID'] which will be generated from database. But one thing, if You have all hidden fields in one form, they all will be sent, so You need to think how to correct that - maybe seperate forms for each hidden field, submit button and maybe other POST fields.
And afterwards, You will be able to get data in the way You need - $SessionID=$_POST['SessionID'];
I suppose it is the easiest way to solve that.
You can try something like this:
while($rows=mysqli_fetch_array($sql))
{
$index = 1;
echo "<input type='password' name='code' id='code'>";
//Attach $index with SessionID
echo "<input type='hidden' name='SessionID_$index' id='SessionID' value='$rows[0]' />";
echo "<input type='submit' value='Take Survey'>";
}
On checkList.php
<?php
$num = explode('_', $_POST['SessionID']);
$num = $num[1];
//in $num you will get the number of row where you can perform action
?>
$form = 1;
while($rows=mysqli_fetch_array($sql))
{
echo '<form name="List_$form" action="checkList.php" method="post">';
echo "<input type='password' name='code' id='code_$form'>";
echo "<input type='hidden' name='SessionID' id='SessionID_$form' value='$rows[0]' />";
echo "<input type='submit' value='Take Survey'>";
echo '</form>';
$form++;
}

passing values using get from a dropdown populated from a mysql database

i have problem passing data from one page to another using GET, for example
i have these:
<form method=post action=edit.php>
<td><input type=text name=firstname></td>
<td>
<?
$query="SELECT * FROM gender;
$result = mysql_query ($query);
echo "<select name=gender_id>";
while($nt=mysql_fetch_array($result))
{
echo "<option value=$nt[gender_id]>$nt[gender_name]</option>";
}
echo "</select>";
?>
</td>
<td><input type=submit name=edit></td>
</form>
now to pass these to edit.php using GET
if($mode=="edit")
{
$fistname=$_GET["fistname"];
$gender=$_GET["gender_id"];
<td><input type=text name=firstname value="<? echo $fistname; ?>"></td>
Above is a working code for an input type text. I know how to pass values with input type text but my problem is that HOW WOULD I DO THESE WITH A SELECT tag WHICH HAS VALUES FROM A MYSQL DATABASE?.
<?
$query="SELECT * FROM gender;
$result = mysql_query ($query);
echo "<select name=gender_id>";
while($nt=mysql_fetch_array($result))
{
if ($nt[gender_id]==$_POST["gender_id"])
$selected="selected";
else
$selected="";
echo "<option ".$selected."value=$nt[gender_id]>$nt[gender_name]</option>";
}
echo "</select>";
?>
you were using <form method=**post** action=edit.php>, in that way you should use $fistname=$_POST["fistname"]; $gender=$_POST["gender_id"];
if you want to use $fistname=$_GET["fistname"]; $gender=$_GET["gender_id"];
you should use <form method=**get** action=edit.php but in that way, the thoses values will be visible in the url.
You have a typographical error on your edit.php change $_GET['fistname'] to $_GET['firstname']. Then edit:
<form method=post action=edit.php>
and put method="get"
<form method=post action=edit.php method="get">
And to prevent errors on edit.php. Add these:
if ((isset($_GET['firstname']) && (isset($_GET['gender_id'])) {
//your code
} else {
//some error message
}
<form method="GET" action="edit.php">
Or use $_POST in the script instead.
EDIT, since you didn't bother putting your question in the question:
As you iterate through the options, test the value of $nt[gender_id] and add the selected attribute to the one that matches.

Categories