How to get value from html select option using GET - php

I am creating a student login site for tutoring center. After a student logged in tutor can see student information and tutor also can submit student information along with tutor name. My problem is whatever i select the tutor name it always insert the last tutor name. I am using PDO for database connection. please can anybody give me an idea how can i solve this problem.Thanks..
Here is my html form code:
<form action="" method="post">
<table border="1">
<tr>
<th>Student Name</th>
<th>course</th>
<th>Tutor</th>
<th>Actions</th>
</tr>
<?php
//select all users from database
$rows = $database->selectFromOnline();
foreach($rows as $row){
$time = $row['time_out'];
?>
<tr>
<td> <?php echo $row['user_name'] ?></td>
<td> <?php echo $row['course'] ?> </td>
<td>
<select name='tutor'>
<?php
//select all instructor from instructor table
$sqls = $database->selectFromTutor();
foreach($sqls as $sql){
echo"<option value='$sql[tutor_ln]'> $sql[tutor_ln] </option>";
}
?>
</select>
</td>
<?php
echo" <td> <a href='tutor.php?user_name=$row[user_name]&&course=$row[course]&&tutor=$sql[tutor_ln]'>Delete</a></td>";
?>
</tr>
<?php
}
?>
</table>
</form>
This is my inserting code:
if(isset($_GET['user_name'])){
$user_name = $_GET['user_name'];
$course = $_GET['course'];
// if i use $_POST['tutor'] it gives me undefined variable error
$tutor = $_GET['tutor'];
//insert into report database table
$database->insetIntoReport($user_name, $course, $tutor);
//Redirect to current page
header('Location: tutor.php');
exit;
}
?>

You're outputting multiple <select name='tutor'> in your form. One select for EVERY time that inner ->selectFromTutor() is executed. As such, you'll get MULTIPLE instances of the tutor select, and only the LAST one will be submitted with the rest of the form.

Your form says <form action="" method="post"> you should be using $_POST variables in your code.

If you are using method="post" on your form, you should use $_POST[]

In addition to the other answers, you could also use $_REQUEST if do not want to bother, whether a form was sent via POST or GET.

I guess you are not willing to use post then you should write a javascript function like
<script type="text/javascript">
function DeleteTutor(name,course){
var tutor=document.getElementById('tutor').value;
window.location.href = 'tutor.php?username='+name+'&course='+course+'&tutor='+tutor;
}
</script>
capture name and course in variables $name and $course and your delete link modified to
<?php echo"<td> <a onclick=\"DeleteTutor('$name', '$course')\">Delete</a></td>"; ?>
Don't forget to add id to select for this to work
<select name='tutor' id="tutor">

Related

Sending a SQL command with one click of an HTML button through PHP

So, I have a basic PHP site that brings up a list of salespeople from a MySQL server when a selection from a drop-down box is submitted. I've set up a button to appear next to each result, and I want a php script to run when the button is clicked using MySQL data from that specific result. Everything works except the button that runs the second MySQL query. Here's an example of the table after the first query:
<table border="1">
<tr>
<td>Last name</td>
<td>First Name</td>
<td>Job Title</td>
<td>City</td>
<td>Client List</td>
</tr>
<tr>
<td>Bondur</td>
<td>Gerard</td>
<td>Sale Manager (EMEA)</td>
<td>Paris</td>
<td>
<form method="POST" action="empLookup.php">
<input type="submit" name="empLookup" value="Look up clients"
</td>
</tr>
</table>
By clicking on the button I would run a MySQL command like 'SELECT clients FROM blah WHERE employeeNumber = ?'
I don't have a problem with any of this except passing the value from the button to the PHP script.
This is what my PHP code looks like for handling the form submission and display of results. The button(s) in question are in the HTML table in the foreach loop.
<?php #this is the default php file for looking up Employees
$page_title = 'Our Associates by City';
require ('./pdoConn.php');
$sql = "SELECT DISTINCT city from Offices";
echo '<h1>Our Associates by City</h1>';
Type in a Name to view Years</a><br>';
//create the form
echo 'Please select a year: <br>';
echo '<form action="index.php" method="post">';
echo '<select name= "city">';
foreach($conn->query($sql) as $row)
{
//each option in the drop down menu is each and every year
//brought up by the query
echo '<option value ="'. $row['city'].' ">'. $row['city']. '</option>';
} //end of foreach
echo '</select>'; //end drop down menu
//now to create the submit button
echo '<br><input type="submit" name="submit" value="List"><br>';
echo '</form>'; //end of form
//This if statement runs when the submit button is clicked
if ($_SERVER[REQUEST_METHOD] == 'POST')
{
$flit = $_POST[city]; //the city variable from the HTML form will be used
echo '<br><br>';
$sql2 = "SELECT employeeNumber,lastName,firstName,jobTitle,city
FROM Employees,Offices
WHERE Employees.officeCode = Offices.officeCode AND city = ?";
$stmt = $conn->prepare($sql2);
$stmt->execute(array($flit));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo 'Contact any of our local staff: <br>';
//create a table of employees
echo '<table border="1"><tr><td>Last name</td><td>First Name</td>';
echo '<td>Job Title</td><td>City</td></tr>';
//time to populate the table, this loop runs for each entry
foreach($rows as $r)
{
echo '<tr><td>'.$r[lastName].'</td><td>'.$r[firstName].'</td><td>';
echo $r[jobTitle].'</td><td>'.$r[city].'</td><td>';
echo '<form method="POST" action="empLookup.php">';
//now to make the button which will search the employee's client list
echo '<input type="submit" name="empLookup" value="Look up clients"</td></tr>';
} //end foreach
echo '</table>';
} //end if server request post thing
?>
I does not completely understood your exact requirement but I think you want employee number into your button if this is your requirement then you can simply check this code
`echo '<input type="submit" name="empLookup" value="'.$r['emp_id_from_database'].'"</td></tr>';`
From your html code, your form looks empty.
You need to add the data to your html form. If you want to avoid the user to see you can use fields. Like it was in the comments said, use $variableName instead of ? in your query. Don't forget use \"$variableName\" to avoid mysql injections.
I took a second reading of your code: You realy should read a php book completly before you program stuff for productive company websites. There are beginner mistakes in your code. And some beginner mistakes leads to insecure websites. I hope this doesn't look an offense, but like an advise.

Store PHP/SQL foreach form items in variables

Sorry I'm a bit of a noob when it comes to PHP but I just wondered if someone had an idea on how I could solve this PHP/SQL problem.
I have a PDO statement that gets all users from a database.
With the array of users from the database I create a foreach loop to display all of the users in a table which I want to use to select a specific user, enter a number in the row of the user I select, then click submit and store the users name and also the number. I will use this information to populate another database later.
My question is, I cant seem to reference the user or the number in the table to extract the user and number I enter. When I try and request the numbered entered in the index.php, it will only ever display a number if I enter a number for a the final user in the table. When I try and view the FullName it never works and I get 'Undefined index: FullName' error.
I also specified to 'POST in the form but it doesnt seem to be doing that.
Does anyone have any ideas?
Thanks
//function.php
function getName($tableName, $conn)
{
try {
$result = $conn->query("SELECT * FROM $tableName");
return ( $result->rowCount() > 0)
? $result
: false;
} catch(Exception $e) {
return false;
}
}
//form.php
<form action "index.php" method "POST" name='form1'>
<table border="1" style="width:600px">
<tr>
<th>Name</th>
<th>Number Entered</th>
<tr/>
<tr>
<?php foreach($users as $user) : ?>
<td width="30%" name="FullName">
<?php echo $user['FullName']; ?>
</td>
<td width="30%">
<input type="int" name="NumberedEntered">
</td>
</tr>
<?php endforeach; ?>
</table>
<input type="submit" value="submit"></td>
</form>
//index.php
$users = getName('users', $conn);
if ( $_REQUEST['NumberedEntered']) {
echo $_REQUEST['NumberedEntered'];
echo $_REQUEST['FullName'];
}
The variable FullName isn't transmitted by your form to index.php. Only values of form elemnts are sent. You can add a hidden form field, that contains FullName like this:
<input type="hidden" name="FullName" value="<?php echo $user['FullName']">
But your second problem is, that your foreach loop will create several input fields with the exact same name. You won't be able to recieve any of the entered numbers, except the last one. have a look at this question for possible solutions.
Update
Putting each row in individual form tags should solve your problem:
<?php foreach($users as $user) : ?>
<form action="index.php" method="POST">
<tr>
<td align="center" width="40%" >
<?php echo $user['FullName']; ?>
<input type="hidden" name="FullName" value="<?php echo $user['FullName']; ?>" />
</td>
<td width="30%">
<input name="NumberedEntered"/>
</td>
<td>
<input type="submit" value="submit"/>
</td>
</tr>
</form>
<?php endforeach; ?>

i can get the form´s select bar into a working array so i can delete it in the database?

I am trying to use php to make a simple option list for a form that can save the list in a database, the list are editable so you can add, rename or delete rows in it. I got the rename and the add to work from simple input boxes but i want to use a drop down list for the deletion sounds simple but i don´t manage to understand why it wont work so i will try to ask for help :)
This bit of code is suppose to delete the selected item from the database
<?php
$ukat_to_delete ="";
if (isset($_POST['delunderkat'])) {
$ukat_to_delete = $_GET['delunderkat'];
$sql = mysql_query("DELETE FROM listor WHERE underkategori = '$ukat_to_delete' LIMIT 1") or die (mysql_error());
header("location: lagtillsaker.php");
exit();
}
?>
and this is the code i use to make a form that shows the list
<form action="lagtillsaker.php" enctype="multipart/form-data" name="myForm3" id="myForm3" method="post">
<table width="100%" border="0">
<tr>
<td width="25%">Ta bort en Underkategori </td>
<td width="75%"><select name="delunderkat">
<option value=""></option>
<?php echo $grupplista ?>
</select>
<input name="delunderkatknap" type="submit" value="Ta bort Underkategorin" /></td>
</tr>
</table>
</form>
and i use this bit of code to generate the list
<?php
$grupplista="";
$sql=mysql_query("SELECT DISTINCT underkategori FROM listor");
$producktCont=mysql_num_rows($sql);
if ($producktCont>0){
while($row = mysql_fetch_array($sql)){
$underkategori = $row["underkategori"];
$grupplista .= "<option value='$underkategori'>$underkategori</option>";
}
}else{
echo "det finns inga underkategorier";
}
?>
i don´t know how i can get the form´s select bar into a working array so i can delete it in the database? I get the code to remove a string or option with no content as if the option value always is nothing in the string output.
You are doing POST and trying to get the data as GET
$ukat_to_delete = $_GET['delunderkat'];
should be
$ukat_to_delete = $_POST['delunderkat'];

How to get the name/id of multiple buttons

I have gotten the id numbers of users from my database, and I want to make a button for each user. My code makes a table that shows all the IDs and creates a button for each one. I'm having trouble figuring out how to get the name of those buttons for use in other code. The error I am getting is "undefined variable" (in the 3rd line), which I am most likely getting because I am going at getting the button names wrong.
Basically, the $_POST in the third line is wrong (among perhaps other things). My question is how would one get the name (or id?) of the buttons I have made: how should I fix the $_POST or should I use something else entirely?
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_POST[$n])) header("location:" . $n . ".php");
}
?>
<div id="mod_user">
<table id='mod_table'>
<th class='ttop'>#</th>
<th class='ttop'>Page</th>
<?php
$result = $db->prepare("SELECT * FROM User");
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$n=$row["UserID"];
?>
<form action="" method="post">
<tr>
<td class='tben'><?php echo $n; ?></td>
<td class='tben'><button type='submit' name=<?php echo $n; ?> >Go here</button></td>
<br />
</tr>
</form>
<?php
} ?>
</table>
</div>
You can try like this:
<td class='tben'><button type='submit' name="usernames[<?php echo $n ?>]" >Go here</button></td>
So you can get button name from $_POST["usernames"] array as below
foreach($_POST["usernames"] as $username => $btn_value)
echo "$username => $btn_name";

how to show fixed images on pageload in php?

I have a php page where user can select one category via dropdown list and after clicking 'go' button the relative images for that category will display on page below the dropdown list from database. This works fine. Now I want to display the images on page load for the 1st dropdown list category everytime then after based on user choice. I think my point is clear to all. for example, 1st category in the dropdown is Featured art, on loading the php page images related to Featured art always display on page. After that user can change it by changing the category from dropdown. Help me please.
Here is my complete code :
<body>
<?php
include ('connect-db.php');
?>
<form name="product" method="post" action="">
<table align="right" width="10%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Category</td>
<td>
<select name="category">
<?php
$sql = "SELECT id, art_name FROM category;";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
?>
<option value="<?= $row['id']; ?>"><?= $row['art_name']; ?></option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td> </td>
<td><input name="go" type="submit" value="Go" /></td>
</tr>
</table>
</form>
<div align="center">
<ul class="display">
<?php
$id = (int)$_POST['category'];
$sql_search = "SELECT id, categoryid, path FROM list WHERE categoryid = $id";
$search = mysql_query($sql_search);
if (isset($_POST['go'])) {
while ($row = mysql_fetch_assoc($search)) {
?>
<li><img src="<?= $row['path']; ?>" border="0"></li>
<?php }
}
else {
}
?>
</ul>
</div>
</body>
Thanks in advance!:)
You may try to use GET request instead of POST. Using this you may check like:
<?php
$get_id = $_GET['category'];
if($get_id == null){
$get_id = <default-value-say-1>;
}
$id = (int)$get_id;
?>
Also, in the dropdown, set the default / first category selected.
When the user selects another option, redirect to url?category=<selected-id>
This is not a copy-paste solution, please take this as a starting
point and follow the best-practices for development in PHP or any PHP
framework of your choice.
Hope this helps!
Vivek

Categories