getting data from $_POST and Showing specific data in php - php

This may have been asked before but i have not been able to find it.
I have created a dropdown list in a form to show a selection from a database.
I am then sending that information via $_POST to another page.
But i am only getting the one result (eg plantID).
$sql = "SELECT DISTINCT * FROM PLANTS";
$result = mysqli_query($mysqli,$sql)or die(mysqli_error());
//********************* Botannical name drop down box
echo "<form name='selection' id='selection' action='profile.php' method='post'>";
echo "<select name='flower'>";
while($row = mysqli_fetch_array($result)) {
$plantid = $row['FlowerID'];
$plantname = $row['Botannical_Name'];
$plantcommon = $row['Common_Name'];
$plantheight = $row['Height'];
$plantav = $row['AV'];
$plantcolours = $row['Colours'];
$plantflowering = $row['Flower_Time'];
$plantspecial = $row['Special_Conditions'];
$plantfrost = $row['Frost_Hardy'];
$plantaspect = $row['Aspect'];
$plantspeed = $row['Growth_Speed'];
echo "<option value=".$plantid.">".$plantname." -> AKA -> ".$plantcommon."</option>";
}
echo "</select>";
echo "<br />";
//********************* End of form
echo "<input type='submit' name='submit' value='Submit'/>";
echo "</form>";
Is there any way i can send all the data via post or
can i somehow get the required PlantID from the database and show all the information for that record in a table on the second page.
Hope this makes sense to someone out there :D

Although technically you can, it is not advised nor used anywhere.
Just send an id like you do right now and then select all the data with another query based on this id.

Related

PHP/SQL duoble drop down from SQL table

I have a nested drop down choice where, basically, the second select input should update its content depending on first selected option.
I get it working ok when it open the page but did not exactly understood how to update the variable once the page is loaded. As a matter of fact if the last option of the SQL table in the first option match the name of one or more record in the second input those may correctly be selected but - changing the option - the second input box doesn’t update.
I tried some java but hadn’t succeeded, also thought about AJAX. Can any one help me with that?
My code is following, the $namev variable is the one, I guess, should need some correct action to be handled toward second input box:
<head>
…..
</head>
<body>
…..
<form>
…….
<div class="divFLOATleft">
<label>voce</label>
<?php
$result = $conn->query("select id_voce,id_gruppo_voce,gruppo_voce,voce FROM voci");
echo "<select name='voce'><option value='' disabled selected>scegli voce</option>";
while ($row = $result->fetch_assoc()) {
unset($idv, $namev);
$idv = $row['id_voce'];
$namev = $row['voce'];
$id_gv = $row['id_gruppo_voce'];
$id_v = $row['gruppo_voce'];
echo '<option value="'.$idv.'">'.$namev.'</option>';
}
echo "</select>";
echo"</div>";
echo"<div class='divFLOATleft'>";
echo"<label>categoria</label>";
$result = $conn->query("select id_voce,id_gruppo_voce,gruppo_voce,voce FROM voci WHERE gruppo_voce LIKE '$namev'");
echo "<select name='voce'><option value='' disabled selected>scegli categoria</option>";
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$idc = $row['id_voce'];
$namec = $row['voce'];
$id_gc = $row['id_gruppo_voce'];
$id_c = $row['gruppo_voce'];
echo '<option value="'.$idc.'">'.$namec.'</option>';
}
echo "</select>";
?>
</div>
</form>
…..
</body>

Storing values from dropdowns to Database using PHP

I am working on an attendance module. Initially, it will show the list of all students along with a dropdown having options Present/Absent. The faculty member will choose Present/Absent accordingly & submit the same.
I am having problem in storing the corresponding values to the DB.
$sql = "select a.student_id, r.student_name, r.section, r.group_name, a.$subject from result.$batch r, attendance.$batch a where a.student_id = r.student_id AND r.section='$section'";
$c = 1;
$result1 = $result->query($sql);
if ($result1->num_rows > 0)
{
while($row = $result1->fetch_assoc())
{
echo '<tr>';
echo "<td>$c </td>";
echo "<td>{$row['student_id']}</td>";
echo "<td>{$row['student_name']}</td>";
echo "<td>{$row['section']}</td>";
echo "<td>{$row['group_name']}</td>";
echo "<td>
<select class='dropdown' id='attend' name='attend[$c]' > <option value='1'>Present</option> <option value='2'>Absent</option>
</td>";
echo '</tr>';
++$c;
}
}
else
{
echo "No Results Found";
}
Can someone please help me with the updation code. Updation is to be made in the table $batch (batch is a variable containing Table Name to use) and column $subject (contains variable name).
well, you can do one thing.when user clicks on the check-box to mark absent or present, save it into an array using Javascript like :
onclick='array.push(this.id);'
this would push the id of current element to an array in Javascript.
When you finally submit the form, just do this,
onsubmit="passValues();"
in script tag, do this
function passValues()
{
var x = array // the array to which elements were pushed
document.getElementById('someBlankElement').innerHTML = "<input type='hidden' value = 'display array here' name='get_this_name_through_php_when_form_submits' >"
}
and done !

PHP code not updating SQL database although print_r suggests correct input

First of all this is my first question on here, and altohugh I have searched the site none of the answers I've seen resolve my current problem.
I am a PHP novice and am currently working on an end project for a course. The object is to make a rudimentary blog where users can post, delete and edit their news, admins can edit or delete everything etc. I am mostly doing fine, but am having a bit of trouble with the editing feature.
The following code displays all blog posts, their authors and dates of posting. If the currently logged in person is the author of a post or a admin, they have the option of deleting or editing each individual post. A small form appears that contains the title and post text. When the user types something else in clicking on the edit button should change the values in the database to the new values the user specified. The problem is that whenever i click on the edit button in the current setup, nothing happens. If i move the if statement outside of the other if statement, the posts do update, but become blank in the database.
Running print_r($_POST) after the fact shows that the array it builds has correct names and updated values, but still they aren't updated in the database. Here is the code, the pertinent part starts at the last if statement( I know, it isn't injection proof, will get to that as soon as it works):
$query = "SELECT id, title, body, pub_date, user_id FROM posts ORDER BY id desc";
$query_fetch = mysql_query($query);
while ($blog_post = mysql_fetch_assoc($query_fetch)) {
$author_id = $blog_post["user_id"];
$post_id = $blog_post["id"];
$post_id2 = $blog_post["id"] . 2;
$title = $blog_post['title'];
$body = $blog_post['body'];
$query = "SELECT username FROM users WHERE id = '$author_id'";
$query_run = mysql_query($query);
$author = mysql_fetch_assoc($query_run);
echo "<h2>" . censor($blog_post["title"]) . "</h2>" . "<br> <p> Autor: " . $author["username"] . "</p><br><p>Objavljeno: " . $blog_post["pub_date"];
if ($_SESSION['admin'] == 1 or $_SESSION['username'] == $author["username"]) {
echo "<form action='' method='POST'><input type='submit' name= '$post_id' value= 'Obriši objavu'></form>";
echo "<form action='' method='POST'><input type='submit' name= '$post_id2' value= 'Uredi objavu'></form>";
}
echo "<p>" . censor($blog_post["body"]) . "</p>";
if (isset($_POST["$post_id"])) {
$del_post = "DELETE FROM posts WHERE id = '$post_id'";
mysql_query($del_post);
}
if (isset($_POST["$post_id2"])) {
echo "<form action='' method= 'POST'>New title<input type='text' value = '$title' name='title'>New text<textarea name='body' id='' cols='30' rows='10'>$body</textarea><input type='submit' name='edit' value='edit'></form>";
if (isset($_POST['edit'])) {
$edit_title = $_POST['title'];
$edit_body = $_POST['body'];
$query = "UPDATE posts SET title= '$edit_title', body= '$edit_body' WHERE id= '$post_id'";
mysql_query($query);
}
}
}
Any help would be appreciated.
This last piece of code
if (isset($_POST["$post_id2"])) {
echo "<form action='' method= 'POST'>New title<input type='text' value = '$title' name='title'>New text<textarea name='body' id='' cols='30' rows='10'>$body</textarea><input type='submit' name='edit' value='edit'></form>";
if (isset($_POST['edit'])) {
$edit_title = $_POST['title'];
$edit_body = $_POST['body'];
$query = "UPDATE posts SET title= '$edit_title', body= '$edit_body' WHERE id= '$post_id'";
mysql_query($query);
}
}
gets activated when post_id2 is sent, but generates a form where post_id2 is not contained anymore. So when you submit that form, the IF is not entered.
You can modify it like this:
if (isset($_POST["$post_id2"])) {
echo "<form action='' method= 'POST'>New title<input type='text' value = '$title' name='title'>New text<textarea name='body' id='' cols='30' rows='10'>$body</textarea><input type='submit' name='edit' value='edit'></form>";
}
if (isset($_POST['edit'])) {
$edit_title = $_POST['title'];
$edit_body = $_POST['body'];
$query = "UPDATE posts SET title= '$edit_title', body= '$edit_body' WHERE id= '$post_id'";
mysql_query($query);
}
In general I think you would find it easier to use forms differently, specifically by using some sort of action tag:
input type="hidden" name="command" value="edit"
input type="hidden" name="post" value="{$post_id}"
This way you could run one single query immediately, without the need for browsing all the posts in a cycle.
One other useful possibility is to split your code between different PHP files, and keeping common code in one include:
<?php // this is delete.php
include "common.php";
$post_id = my_get_var('post_id');
my_sql_command("DELETE FROM posts WHERE...");
used from
<form action="delete.php" method="post" ...>
As you can see this allows for different ways of retrieving post_id (centrally defined in a single function my_get_var in common.php) and the central definition of SQL functions. How this function interfaces to MySQL can then be updated, specifically passing from mysql_ functions (which are deprecated, and soon will no longer be available) to e.g. PDO.
It also allows you to test a single command independently, by directly entering delete.php in the browser (you need for my_get_var to accept both POST and GET variables to do this).
Details
You want to inspect and/or modify a collection of posts. You then require initially at least the following operations: list, edit, and delete.
Only the first works against all posts.
So you could have a list.php file running the SELECT. Also, it is only in this SELECT that you need information about the user, so your query could become:
$query = "SELECT posts.id, title, body, pub_date, user_id, username FROM posts JOIN users ON (posts.user_id = users.id) ORDER BY posts.id desc";
In the display cycle we would display this information:
$query_fetch = mysql_query($query);
// This file will receive requests to edit or delete
// We can use a single form.
echo '<form action="manage.php">';
while ($post = mysql_fetch_assoc($query_fetch)) {
echo "<h2>" . censor($post["title"]) . "</h2>" . "<br> <p> Autor: " . $post["username"] . "</p><br><p>Objavljeno: " . $post["pub_date"];
if ((1 == $_SESSION['admin']) or ($_SESSION['username'] == $post["username"]) {
echo "<input type=\"submit\" name=\"Obriši objavu\" value=\"{$post['id']}\" />";
echo "<input type=\"submit\" name=\"Uredi objavu\" value=\"{$post['id']}\" />";
}
echo "<p>" . censor($blog_post["body"]) . "</p>";
}
echo "</form>";
This way you need only one form, and it will submit one field with a name describing the action to be taken, and the post on which to do it.
The file manage.php will then receive this information -- and can also be used to update it:
foreach(array(
"delete" => "Obriši objavu", // from list.php
"edit" => "Uredi objavu", // " "
"update" => "update" // from this file itself (see below)
)
as $test_todo => $var) {
if (array_key_exists($var, $_POST)) {
$id = $_POST[$var];
$todo = $test_todo;
}
}
if (isset($id)) {
switch($todo) {
case "delete":
mysql_query("DELETE FROM posts WHERE id = '{$id}'");
break;
case "edit":
// Get this post.
$query = "SELECT posts.id, title, body, pub_date, user_id, username FROM posts JOIN users ON (posts.user_id = users.id) WHERE posts.id = '{$id}';";
echo '<form action="manage.php" method= "POST">';
// This is how we tell this file what to do, and to what.
echo "<input type=\"hidden\" name=\"update\" value=\"{$id}\">";
// run query, fetch the one record, display info...
echo "</form>";
break;
case "update":
// Build the update query from $_POST.
mysql_query("UPDATE posts SET ...");
}
At first check that your query is correct. Then try to hard-code your query. Also test your query in phpMyAdmin Also you can try to remove the '' from your number variables on every query.
Please, can you give us your error?
There is a possibility also that your database has already been updated. So double check it.
This is how I usually debug. echo the query. Run it in PHPmyadmin, and see the error.
so, in your case.
echo "UPDATE posts SET title= '$edit_title', body= '$edit_body' WHERE id= '$post_id'";
echo that and you will have the query that the script will be trying to run.
Try running it in phpmyadmin and check what the error is.

insert value from drop down box to the database

I am missing something from my code and I don't know how to make it work. I may have programed it wrong and that could be giving me my troubles. I am new at php and things have been going slowly. please understand that the code my not be organized as it should be. After creating about 12 pages of code I found out that I should be using mysqli or pod. Once I get everything working that will be the next project. Enough said here is my issue. I was able to populate my drop down box and there shows no errors on the page. Also all the data does get inserted into the database except for the section made on the drop down box. Here is my code. I will leave out all of the input fields except the drop down.
<?php
{$userid = $getuser[0]['username'];}
// this is processed when the form is submitted
// back on to this page (POST METHOD)
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
# escape data and set variables
$tank = addslashes($_POST["tank"]);
$date = addslashes($_POST["date"]);
$temperature = addslashes($_POST["temperature"]);
$ph = addslashes($_POST["ph"]);
$ammonia = addslashes($_POST["ammonia"]);
$nitrite = addslashes($_POST["nitrite"]);
$nitrate = addslashes($_POST["nitrate"]);
$phosphate = addslashes($_POST["phosphate"]);
$gh = addslashes($_POST["gh"]);
$kh = addslashes($_POST["kh"]);
$iron = addslashes($_POST["iron"]);
$potassium = addslashes($_POST["potassium"]);
$notes = addslashes($_POST["notes"]);
// build query
// # setup SQL statement
$sql = " INSERT INTO water_parameters ";
$sql .= " (id, userid, tank, date, temperature, ph, ammonia, nitrite, nitrate, phosphate, gh, kh, iron, potassium, notes) VALUES ";
$sql .= " ('', '$userid', '$tank', '$date', '$temperature', '$ph', '$ammonia', '$nitrite', '$nitrate', '$phosphate', '$gh', '$kh', '$iron', '$potassium', '$notes') ";
// #execute SQL statement
$result = mysql_query($sql);
// # check for error
if (mysql_error()) { print "Database ERROR: " . mysql_error(); }
print "<h3><font color=red>New Water Parameters Were Added</font></h3>";
}
?>'
Here is the drop down
<tr><td><div align="left"><b>Tank Name: </b> </div></td><td><div align="left">
<?php
echo "<select>";
$result = mysql_query("SELECT tank FROM tank WHERE userid = '$userid'");
while($row = mysql_fetch_array($result))
{
echo "". $row["tank"] . "";
}
echo "";
?>
</div></td></tr>
You missed some code in while loop.
while($row = mysql_fetch_array($result))
{
echo "<option>".$row['tank']."</option>";
}
echo "</select>";
are you able to build drop down menu or box. if not try this query
$sql="SELECT `tank` FROM `tank` WHERE user_name='$user'";
$result=mysqli_query($dbc,$sql)
//here $dbc is a variable which you use to connect with the database.
Otherwise leave that only read from here why you need to change your code. in the while loop
one one more thing you have to give your select attribute a name, because it will return the value through name so give a name to your select attributes as you are using tank while building your drop down menu so i will give a same name tank. Than you dont have to change anything.
and you have to give value to your option as well, thanks
echo "<select name='age'>";
while($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['tank'] . "' >" . $row['tank'] . "</option>";
}
echo "</select>";

Getting two variables from one radio button?

http://i.stack.imgur.com/Gy3o0.png
That is what the site looks like now. What I want to do is when you click on the approve registration on the table, it will extract the value of the id no and the name of that particular record. I thought i was on the right track. I knew how to get the id no. But it doesn't get the value of the name at the same time.
This is how the code looks like:
while($row = mysql_fetch_array($mayor))
{
$id = $row['identification_no'];
$name = $row['lastname'].", ".$row['firstname'];
echo "<tr>";
echo "<td><form method=post action=approvedmayor.php><input type='radio' name=id value='$id'></td>";
}
approvedmayor.php
$query = mysql_query("insert into tbcandidates VALUES ($id, '$name', 'mayor')");
if ($query)
{
echo "You appproved ";
echo $name;
}
else
echo "error";
you can try like this...
<?php
while($row = mysql_fetch_array($mayor))
{
$id = $row['identification_no'];
$name = $row['lastname'].", ".$row['firstname'];
echo "<tr><td><a href='approvedmayor.php?id=$id&name=$name'>Approve</a></td></tr>";
}
?>
in this type don't use the form, and Approve button... try this alone
Actually it is bad practice to insert that kind of data directly from POST data.
If you have all these candidates already stored in the database, you should run a SELECT query in your approvedmayor.php first, and if the candidate still exists, insert it's data to another table.
$query = mysql_query('SELECT * FROM `candidates` WHERE `id` = '.$id.' LIMIT 1');
if(mysql_num_rows($query)) {
$candidate = mysql_fetch_assoc($query);
$insertQuery = mysql_query("insert into tbcandidates VALUES ($candidate['id'], $candidate['name'], $candidate['mayor'])");
if ($insertQuery) {
echo "You appproved ";
echo $name;
} else echo "error";
} else echo 'This candidate is no longer available';
I understand your question,
But thats not the best way go ahead, Before we move let us understand some little elements functions
Radio Button : Its an input type element, that allows the user to choose only one [ 1 ] of option given list.
Check Boxes : Its an input type element, that allows the user to select n number of options or selections from give list.
Fore info - http://www.w3schools.com/html/html_forms.asp
Now comming to your question..
You need to modify your code to check boxes as below
<input type='checkbox' name=id[] value='$id'>
Notice : elements name is in Array mode.. ie whenever a user one or more than one, the values are stored in array.
Once the values are stored in array, call it / use if however you want.
For your mentioned code
echo "<form method=post action=approvedmayor.php>';
while($row = mysql_fetch_array($mayor))
{
$id = $row['identification_no'];
$name = $row['lastname'].", ".$row['firstname'];
echo "<tr>";
echo "<td><input type='radio' name=id[] value='$id'></td>";
}
echo "</form>";
approvedmayor.php
$temp_app_arr = $_POST['id'];
foreach ($temp_app_arr as $pos => $val) {
$query = mysql_query("insert into tbcandidates VALUES ('$val', '$name', 'mayor')");
if ($query) {
echo "You appproved ";
echo $name;
} else {
echo "error";
}
}
And i believe this should gonna be good code / algorithm for your project.

Categories