Option list which can retrieve from and post to database - php

can anybody post an code for option list which can retrieve data dynamically from database, and once user selects from option list a record, that record must post it ($_POST) to database.. !!
ive tried this, it retrieves records from db, but not posting it :
<?php
require_once "db.php";
if (isset($_POST['a_id']) {
$a = $_POST ['a_id'];
$sql = "INSERT INTO projektet
VALUES ('$a')";
mysql_query($sql);
}
HERE IS THE PART SEEMS NOT WORKING :
<form method="post">
<select name="a_id">
<?php
$host="localhost";
$username = 'root';
$password = "";
$con = mysql_connect($host,$username,$password);
mysql_select_db('naho',$con);
// Checking connection
if (!$con){
echo ("Failed to connect to MySQL:. " .mysql_error($con));
}
else {
echo("db connect");
}
$result = mysql_query("SELECT * from `arqitekti`");
if($result == FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row=mysql_fetch_array($result)){
?>
<option value="<?php '.row[a_id];'?>"><?php echo $row["a_emri"];?></option>
<?php }
?>
</select>
<input type="submit" value="submit"/>
</form>

<option value="<?php '.row[a_id];'?>"><?php echo $row["a_emri"];?></option>
This line looks strange... Shouldn't it be:
<option value="<?php echo $row[a_id]; ?>"><?php echo $row["a_emri"];?></option>
I think that your code is POSTing, but it wasn't getting any value because of the value declaration on the options of the select. After that change it should work.
PS: If your POST code isn't in the same page as your HTML, it's <form method="POST" action="YOUR_PAGE">, not only <form method="POST">.

Related

PHP option value based on database table

My problem now:
once I echo the value from the database its woking good. but when I submit the form I got an empty value of the selected option.
Can any one help. I tried to used {} in he value code but it did not work.
What I want :
Set the the value of the selected option as it is on the database to insert it into another table.
<select class="form-control" name="CenterTO" id="CenterTO">
<option value="" selected>--select-- </option>
<?php
require("inc/DB.php");
$query = "SELECT centerName FROM jeCenter";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
while($row = mysql_fetch_array($result)){
echo '<option value="'.$row['centerName'].'">'.$row['centerName'].'</option>';
}
} else {
echo '<option>No data</option>';
}
mysql_close();
?>
Try this
<select class="form-control" name="CenterTO" id="CenterTO">
<option value="0" selected>--select--</option>
<?php
require("inc/DB.php");
$query = "SELECT centerName FROM jeCenter";
$result = mysql_query($query);
$count = count($result);
if (!empty($count)) {
while($row = mysql_fetch_array($result))
{
$name = $row['centerName'];
echo "<option value='$name'> $name </option>";
}
} else {
echo '<option>No data</option>';
}
mysql_close();
?>
</select>
You will have to "expand" your select query to include the ID of the row, and then instead of $row['centerName'] use $row['id'] (or what your ID column is named) in the value argument of the option element, and not the 'centerName'. If I understood correctly what you want, this should be it.
Edit: And do switch to mysqli_, mysql_ has been deprecated.
try to write like this:
echo '<option value="',$row["centerName"],'">',$row["centerName"],'</option>';
Warning:
Please don't use the mysql_ database extensions, they were deprecated in PHP 5.5.0 and were removed in PHP 7.0.0. Use mysqli or PDO extensions instead.
Solution
I recreated your issue and enhanced your code using mysqli extensions, and it's working fine. Take a look at the following code,
<?php
if(isset($_POST['submit'])){
// display submitted option
echo $_POST['CenterTO'];
}
?>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbName = "stackoverflow";
// Open a new connection to the MySQL server
$connection = new mysqli($host, $username, $password, $dbName);
// Check connection
if($connection->connect_errno){
// error
die('Connect Error: ' . $connection->connect_error);
}
// Execute query
$result_set = $connection->query("SELECT centerName FROM jeCenter");
?>
<form action="form_page.php" method="POST">
<select name="CenterTO">
<option value="" selected>--select-- </option>
<?php
// Check if number of rows is greater than zero or not
if($result_set->num_rows > 0){
// Loop through each record
while($row = $result_set->fetch_assoc()){
?>
<option value="<?php echo $row['centerName']; ?>"><?php echo $row['centerName']; ?></option>
<?php
}
}else{
?>
<option value="none">No data</option>
<?php
}
?>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
<?php
// Close connection
$connection->close();
?>

Fill drop down list on page load php

I have two input text fields where user has to specify the begin and end of the fly.
<input type="text" name="start" placeholder="Start destination">
<input type="text" name="end" placeholder="End destination">
I would like to change that and give user to chose start and end destination from database.
<select>
<option value="$id">$name</option>
</select>
I know how to get done if i read database and input values manually, but i know its posible if page loads and execute my SELECT QUERY.
So i have to create dropdown list and fill that with a values from database.
This dropdown list has to be filled when the page load.
Some idea for this ???
I am working with php.
Thank you in advance !!
EDIT : I get done this only with php.
<?php
$db_host = "localhost";
$db_username = "root";
$db_password = "";
$db_name = "flights";
$conn = mysql_connect("$db_host","$db_username","$db_password") or die ("no conn");
#mysql_select_db("$db_name") or die ("no database");
if ($conn = true) {
// echo "";
}
//cyrilic
$sql = "SET NAMES 'utf8'";
mysql_query($sql);
//query for end
$sql="SELECT Distinct end from flights_table;";
$result=mysql_query($sql);
echo "<select name=\"city\">";
echo "<option>end destination</option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value='".$row['end']."'>".$row['end']." </option>";
}
echo "</select>";
?>
This php fires when page loads. Those select options i have putted in a form, and when form is submited, it fires php itself. I am getting selected options this way :
$startfly=$_POST['end'];
I am doing this for starting the flight :)
Thank you guys !
Try this :
At the top of page include your database connection file :
<?php
require "connection.php";
?>
Then :
<?php
$selectStart = "Start : <select name='start'>";
$selectEnd = "End : <select name='end'>";
$query = mysql_query("SELECT * FROM someTable ORDER BY dateField ASC");
if(mysql_num_rows($query) > 0)
{
while($row = mysql_fetch_assoc($query))
{
$selectStart .= "<option value='".$row['startItem']."'>".$row['startItemName']."</option>";
$selectEnd .= "<option value='".$row['endItem']."'>".$row['endItemName']."</option>";
}
}
$selectStart = "</select>";
$selectEnd = "</select>";
?>
In your HTML :
<form action='destinationPage.php' method='post'>
<?php
echo $selectStart;
echo $selectEnd;
?>
<input type='submit' value='Submit' />
</form>

Keep getting Notice: Undefined index: whatever I do

I am trying to fill a table in my database from a drop down menu which I populated from another table from my database. The problem is that whenever I submit my query, it gives me the same error "Notice: Undefined index:" and won't fill the table. I am new to coding, so please be gentle.
This is the part for populating the drop down menu
<?php
#mysql_connect("localhost", "root","") or die(mysql_error());
mysql_select_db("motocikli") or die(mysql_error());
$query = "SELECT kategorija_ime FROM kategorija";
$result = mysql_query($query) or die(mysql_error()."[".$query."]");
?>
<select name="kateg">
<?php
while ($row = mysql_fetch_array($result))
{
echo "<option value='".$row['kategorija_ime']."'>'".$row['kategorija_ime']."'</option>";
}
?>
</select>
<form action="insert.php" method="post">
<input type="submit">
</form>
And this is the insert.php
<?php
$dsn = 'mysql:dbname=motocikli;host=127.0.0.1';
$user = 'root';
$password = '';
$pdo = new \PDO($dsn, $user, $password);
function unesiPoruku($kateg)
{
global $pdo;
$upit = $pdo->prepare("INSERT INTO test (kateg) VALUES (:kateg)");
$upit->bindParam('kateg',$kateg);
$upit->execute();
}
$kateg = $_REQUEST['kateg'];
unesiPoruku($kateg);
?>
The error is showing for $kateg = $_REQUEST['kateg'];, the 'kateg' tag.
Your select box needs to be inside the form so that the value is posted properly to the server
ie.
<form action="insert.php" method="post">
<select name="kateg">
<?php
while ($row = mysql_fetch_array($result))
{
echo "<option value='".$row['kategorija_ime']."'>'".$row['kategorija_ime']."'</option>";
}
?>
</select>
<input type="submit">
</form>

Update a MySQL Database with a Form

I'm trying to create a form that allows a user to select a field from a drop down box and then change what is currently written in the field.
My current code allows me to view the drop down list select the field I want to change and then enter my new text into a box. But when I click update, nothing happens.
<?php
mysql_connect("", "", "") or die(mysql_error());
mysql_select_db("") or die(mysql_error());
$query = "SELECT * FROM news_updates";
$result=mysql_query($query) or die("Query Failed : ".mysql_error());
$i=0;
while($rows=mysql_fetch_array($result))
{
$roll[$i]=$rows['Text'];
$i++;
}
$total_elmt=count($roll);
?>
---------------------------------------------------------Now I have the form
<form method="POST" action="">
Select the news post to Update: <select name="sel">
<option>Select</option>
<?php
for($j=0;$j<$total_elmt;$j++)
{
?><option><?php
echo $roll[$j];
?></option><?php
}
?>
</select><br />
Text Field: <input name="username" type="text" /><br />
<input name="submit" type="submit" value="Update"/><br />
<input name="reset" type="reset" value="Reset"/>
</form>
-----------------------------------------------Now I have the update php
<?php
if(isset($_POST['submit']))
{
$username=$_POST['username'];
$query2 = "UPDATE news_updates SET username='$username' WHERE rollno='$value'";
$result2=mysql_query($query2) or die("Query Failed : ".mysql_error());
echo "Successfully Updated";
}
?>
Well, you seem to be missing the $value part. Something like this should do, for the last part:
<?php
if(isset($_POST['submit']))
{
$username = mysql_real_escape_string($_POST['username']);
$value = mysql_real_escape_string($_POST['sel']);
$query2 = "UPDATE news_updates SET username='$username' WHERE rollno='$value'";
echo $query2; //For test, to see what is generated, and sent to database
$result2=mysql_query($query2) or die("Query Failed : ".mysql_error());
echo "Successfully Updated";
}
?>
Also, you should not use mysql_* functions as they are deprecated. You should switch to mysqli or PDO.
First, try adding a value to your options, like so:
for($j=0;$j<$total_elmt;$j++)
{
?>
<option value="<?php echo $roll['id']; ?>"><?php echo $roll['option_name']; ?></option>
<?php
}
Then, when you parse your file, go like so:
$value = $_POST['sel']; // add any desired security here
That should do it for you
You need to change this
<?php
for($j=0;$j<$total_elmt;$j++)
{
?><option><?php
echo $roll[$j];
?></option><?php
}
to this
<?php
for($j=0;$j<$total_elmt;$j++)
{
?><option value="<?php echo $roll[$j];?>"> <?php echo $roll[$j];?></option> <?php
}
And you also need to change the update query from this
$query2 = "UPDATE news_updates SET username='$username' WHERE rollno='$value'";
to this
$query2 = "UPDATE news_updates SET username='$username' WHERE rollno='".$_POST['sel']."'";
N. B.: Here I am assuming that $_POST['sel'] has the value selected by the user from the drop down menu because I could not find anything which corresponds to $value

Need help updating database row with values from HTML form

I've got an admin area where the admins can set the level of repair and it shows on a progress bar in the users area. I have it all working apart from updating the mySQL database to the value submitted.
My database has a table called 'users' and fields 'UserID', 'Username', 'Password', 'progress', 'admin'.
Here is the code I'm using to try and make the magic happen:
<?php
$query="SELECT * FROM users";
$result=mysql_query($query);
$num=mysql_numrows($result);
?>
<form id="chooseuseredit" method="post" action="<?php echo $PHP_SELF;?>">
<select name="ChooseUser">
<?php
$i=0;
while ($i < $num) {
$f1=mysql_result($result,$i,"UserID");
$f2=mysql_result($result,$i,"Username");
$f3=mysql_result($result,$i,"progress");
$f4=mysql_result($result,$i,"admin");
?>
<option value="<?php echo $f1; ?>"><?php echo $f2; ?></option>
<?php
$i++;
}
?>
</select>
<input type="submit" name="chooseSubmit" id="chooseSubmit" value="Choose User" />
</form>
<?php
if(isset($_POST['chooseSubmit']) )
{
$varID = $_POST['ChooseUser'];
$errorMessage = "Jesus Christ Benton, Choose a User!!";
?>
<br>
<p><strong>Editing UserID: <?php echo "$varID"; ?></strong></p>
<p>Progress:<br>
<form name="edituserform" method="post" action="<?php echo $PHP_SELF;?>">
<select name="editinguser">
<option value="0">Phone Not Recieved</option>
<option value="20">Phone Recieved</option>
<option value="40">Parts Recieved</option>
<option value="60">Repair Started</option>
<option value="80">Repair Finished</option>
<option value="100">Posted Back</option>
</select>
<input type="hidden" name="edituserid" id="edituserid" value="<?php echo "$varID"; ?>" />
<input type="submit" name="edituser" id="edituser" value="Edit" />
</form>
<?php
if(isset($_POST['edituser'])){
$add = $_POST['edituser'];
$varIDe = $_POST['edituserid'];
$errorMessage = "Jesus Christ Benton, Choose a User!!";
$query1 = mysql_query("UPDATE users SET progress = $add WHERE UserID = $varIDe");
mysql_query($query1) or die("Cannot update");
echo $add;
echo $varIDe;
}
?>
<?php
}
?>
I'm not sure if the variables are working or not, or if it's the way I've used the submit button before? Its got me a little stumped.
You're query should be
$query1 = mysql_query("UPDATE users SET progress = '$add' WHERE UserID = $varIDe");
Don't forget the quotes
and it would be best to change your
mysql_query($query1) or die("Cannot update");
to mysql_query($query1) or die("MySQL ERROR: ".mysql_error());
to get it to display errors
edit
Found a few errors
mysql_numrows should be mysql_num_rows
and major error
$query1 = mysql_query("UPDATE users SET progress = $add WHERE UserID = $varIDe");
is running a query, change it to
$query1 = "UPDATE users SET progress = '".$add."' WHERE UserID = '".$varIDe."'";
I think your getting the wrong variable
if(isset($_POST['edituser'])){
$add = $_POST['edituser']; // this is a button
should be :
if(isset($_POST['editinguser'])){
$add = $_POST['editinguser']; // this is a select list
But please read the following about SQL Injection
When something's going wrong, with respect to query, you better debugging, adding one: or die ( mysql_error ( ) ) ; and then the error message is displayed.
$query1 = mysql_query("UPDATE `users` SET `progress` = '".$add."' WHERE UserID = '".$varIDe."'");
if(mysql_query($query1))
{
//DO SOME ACTION
}
else
{
die(mysql_error());
}

Categories