insert dynamic dropdown values in the database on button click in php - php

i am dynamically adding the values in the dropdown . After selecting the value in the dropdown and entering text in the textbox, both textbox value and dropdown value has to be entered in the database on button click. But my code is not working properly ie only textbox value is inserted in the database but not dropdown selected vlaue. Please correct my code
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<label style="margin-left:260px;width:170px"><h3 >Topic:</h3><br></label><br>
<select name="topic" style="margin-left: 282px;margin-top: -17px;">
<option value=""> -----Select----- </option>
<?php
$records = mysql_query("SELECT topic FROM topic ");
while ($row = mysql_fetch_array($records)){
echo "<option value=\"\">" . $row['topic'] . "</option>";
}
?>
</select>
<label style="margin-left:260px;width:170px"><h3 >Enter Crime Key Point:</h3><br></label><br>
<textarea name="details" id="details" rows="14" cols="60" style="margin-left:112px"><?php if(isset($_POST['details'])){echo htmlspecialchars($_POST['details']);}?>
</textarea><br><br>
<br><br><input type='submit' name='submit' value='Post' style='margin-left:305px;'>
</form>
if(isset($_POST["submit"]) ){
//if ( isset( $_POST['topic'] )){
//if(!empty($_POST['CarList'])){
$story = $_POST['details'];
$topic = $_POST['topic'];
echo $topic;
$sql = "SELECT `registered` FROM `user` WHERE `name`='{$_SESSION['name']}'";
$result = mysql_query($sql);
if (! $result)
{
throw new My_Db_Exception('Database error: ' . mysql_error());
}
else
{
$row = mysql_fetch_assoc($result);
$register=$row['registered'];
if ($register==1)
{
$sql = "INSERT INTO `stories`(`stories`,`name`,`topic`,`date/time`) VALUES ('$story','{$_SESSION['name']}','$topic',now())";
$result = mysql_query($sql);
echo $result;
if (! $result)
{
//echo "Story is not inserted. Please avoid special characters.";
echo 'Retrieval of data from Database Failed - #'.mysql_errno().': '.mysql_error();
}
else
{
die("<script>location.href = 'usershome.php'</script>");
echo "Story inserted successfully";
}
}
else
{
$sql = "select count(*) from stories where `date/time`=DATE(NOW()) AND `name` = '{$_SESSION['name']}'";
$result = mysql_query($sql);
if (! $result)
{
throw new My_Db_Exception('Database error: ' . mysql_error());
}
else
{
$row = mysql_fetch_assoc($result);
$count=$row['count(*)'];
if ($count<3)
{
$sql = " INSERT INTO `stories`(`stories`,`name`,`date/time`) VALUES ('$story','{$_SESSION['name']}',now())";
$result = mysql_query($sql);
if (! $result)
{
echo "Story is not inserted";
}
else
{
die("<script>location.href = 'usershome.php'</script>");
echo "Story inserted successfully";
}
}
else
{
echo '<img src="images/animated-star-image-0009.gif" width="25px"/>Please Register to enter more than 3 stories per day';
}
}
}
}
}
?>

The line:
echo "<option value=\"\">" . $row['topic'] . "</option>";
change it to:
echo "<option value='".$row['topic']."'>" . $row['topic'] . "</option>";
You are passing empty values for the topic parameter. Setting up a correct value will ensure that you are inserting the correct user input in the database.
For future you can debug this easy by outputting your POST content before executing the SQLinsert.
That will fix your issue, but there are several other things you might consider changing, one of them is the deprecated mysql_ extension, switch to mysqli or PDO.

Related

Session variable and Dynamic Pagination in php

<form action='movies.php' method='POST'>
Language: <select name="language">
<option selected>hindi</option>
<?php
require("config.php");
$result="SELECT language FROM movies";
$q = mysqli_query($conn,$result) or die(mysql_error());
while ($row=mysqli_fetch_array($q)) {
$s1=$row["language"];
echo "<option>
$s1
</option>";
}
echo "<br>"
?>
</select>
<br /> <br />
<input type='submit' value='Submit' />
</form>
<?php
$lang=#$_POST['language'];
$_SESSION["lang1"]=$lang;
/*
if($lang){
$sql = "SELECT name,language FROM movies WHERE language='$lang'";
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows($result)>0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<div class="query"> <img src="images\tiles\bb.jpg"> ';
echo "<h3> " . $row["name"]."</h3>". "<br>";
echo "</div>";
}
} else {
echo "0 results";
}
}
*/
$page=#$_GET['page'];
if($page==""|| $page=="1")
{
$page1=0;
}
else{
$page1=($page*3)-3;
}
$sql = "SELECT name,language FROM movies WHERE language='". $_SESSION['lang1']."' limit $page1,3 ";
$result = mysqli_query($conn,$sql);
$a= mysqli_num_rows($result);
while ($list=mysqli_fetch_array($result))
{
echo $list['name'] . " : " . $list['language'] . "<br />";
}
$sql = "SELECT name,language FROM movies WHERE language='$lang'";
$result = mysqli_query($conn,$sql);
$a= mysqli_num_rows($result);
$numrows=$a;
$rowsperpage=3;
$totalpages= ceil($numrows/$rowsperpage);
echo "</br>";
for($b=1;$b<=$totalpages;$b++)
{
?><?php echo $b." ";?> <?php
}
?>
I get proper output on movies.php which is the first 3 rows from database,but when i click on the dynamically created pagination link like movies.php?page=2 then there is no output on this page.This code works fine if i manually set the
$_SESSION["lang1"]="English"; then i get proper output but when i take input from the form it doesnt work.

PHP dropdown list

I am trying to get the user to pick from the dropdown menu. When the user clicks on the selected item they will click a button and show the results.
I haven't been able to display the information onto the page.
$sql = "select * from Owner";
echo'<form action="index1.php" method="post">';
echo '<select name="bid" id="bid">';
foreach($conn->query($sql) as $row) {
echo '<option value=" ';
echo $row["id"];
echo ' ">';
echo $row['LastName'];
echo '</option>';
}
echo'</select>';
echo'<br><input type="submit" value="Show Info"><br>';
echo'</form>';
//check if submit button has been clicked
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = $_POST['bid'];
try{
$sql = "select Owner.FirstName, Owner.LastName,MarinaSlip.BoatName from Owner, MarinaSlip where Owner.OwnerNum = MarinaSlip.OwnerNum
and Owner.FirstName = $id";
foreach($coon->query($sql) as $row){
echo$row['FirstName'].' '.$row['LastName'].' '.$row['BoatName'].'<br>';
}
}//end of try
catch(PDOExeption $e){
echo "Error: ".$e -> getMessage();
}
}

PHP Loop with dropdown selection and submit button?

I am trying to make a loop that gets the name some other info about a product from a sql table - MySQL table
Then Creates a page that looks like that - Webpage
So Far I have this code that does show it but I cant figure out a way how to update the name of the dropdown menu so when I press submit It writes into another SQL table the name of the product and then how many of those products did the customer selected .
<?php
$sql = "SELECT * FROM product";
$result = $conn->query($sql);
while ( $row = mysqli_fetch_assoc($result) ) {
$columnValues[] = $row['ProductID'];
foreach($columnValues as $key => $value) {
$$key = $value;
while ($row = $result->fetch_assoc()) {
echo "<tr>\n". "<br>";
echo "##product-ID## ";
echo "<td>".$row['ProductID']. "</td>\n";
echo " ##product-name## ";
echo "<td>".$row['ProductName']."</td>\n";
echo "<td>\n";
echo " ##dropdown## ";
echo "<select id=$value>\n";
echo "<option value='1'>1</option>\n";
echo "<option value='2'>2</option>\n";
echo "<option value='3'>3</option>\n";
echo "<option value='4'>4</option>\n";
echo "<option value='5'>5</option>\n";
echo "<option value='6'>6</option>\n";
echo "</select>\n";
echo "</td>\n";
echo "</tr>\n";
}
}
}
$conn->close();
?>
<html>
<body>
<form method="POST" action="#" >
<input type="submit" name="Submit" value="Submit" /><br>
</form> </body>
</html>
I know I will most likely need a second php script for the capture of the post so help with that will be greatly appreciated too .
////////////////////////////////////////////////
So up to here I got it somehow - It loops and shows all the product . When I press submit it adds only the last product in the loop and it doesn't care of the drop down menu - Just adds a "2" .
The table where the script writes is simple - 4 columns OrderID1,productid1,ProductName1 orderedqnt1
Thanks in advance .
Index.php
<html>
<body>
<form method="POST" action="insert.php" >
<?php
session_start(); // session start for Variables to add to the sql in Insert.php
include("global.php"); // Stores the session Variables
## Conection part
$sql = "SELECT * FROM product";
$result = $conn->query($sql);
while ( $row = mysqli_fetch_assoc($result) ) {
$columnValues[] = $row['ProductID'];
foreach($columnValues as $key => $value) {
$$key = $value;
while ($row = $result->fetch_assoc()) {
echo "<tr>\n". "<br>";
echo "##product-ID## ";
echo "<td>".$row['ProductID']. "</td>\n";
echo " ##product-name## ";
echo "<td>".$row['ProductName']."</td>\n";
echo "<td>\n";
/* echo " ##dropdown## "; */
echo "<select id=" . $value . " name='dropdown'>\n";
echo "<option value=''>-</option>\n";
echo "<option value='1'>1</option>\n";
echo "<option value='2'>2</option>\n";
echo "<option value='3'>3</option>\n";
echo "<option value='4'>4</option>\n";
echo "<option value='5'>5</option>\n";
echo "<option value='6'>6</option>\n";
echo "</select>\n";
/* echo "</td>\n"; */
/* Echo ":::::value variable = "."$value"; */
echo "</tr>\n" . "<br>";
print_r ($value);
$_SESSION['GrabIDses']=mysqli_real_escape_string($conn,$row['ProductID']); //Grabs the ID of the product in Session Variable
$_SESSION['GrabNameses']=mysqli_real_escape_string($conn,$row['ProductName']); //Grabs the Name of the product in Session Variable
$_SESSION['GrabSKUses']=mysqli_real_escape_string($conn,$row['SKU']); //Grabs the SKU of the product in Session Variable
$_SESSION['Ordered']=mysqli_real_escape_string($conn,$value); //Grabs the Ordered Quantity for the product in Session Variable ????????????????
/* $GrabID = mysqli_real_escape_string($conn,$row['ProductID']);
$GrabName = mysqli_real_escape_string($conn,$row['ProductName']);
$GrabSKU = mysqli_real_escape_string($conn,$row['SKU']);
echo "----------------------"."$_SESSION['GrabSKUses']"."<br>"."$_SESSION['GrabIDses']"."<br>"."----------------------"; */
}
}
}
$conn->close();
echo "<br>";
?>
<input type="submit" name="Submit" value="Submit" /><br>
</form>
</body>
Insert.php
<?php
session_start(); // session start
$getvalue = $_SESSION['GrabIDses']; // session get
$getvalue1 = $_SESSION['GrabNameses']; // session get
$getvalue2 = $_SESSION['GrabSKUses']; // session get
$ordered11 = $_SESSION['Ordered']; // session get
echo $getvalue;
echo "||";
echo $getvalue1;
echo "||";
echo $getvalue2;
echo "||"."<br>";
print_r($_SESSION);
## Connection Part
if(isset($_POST['dropdown'])) {
echo("You order was completed" . "<br>");
$sql = "INSERT INTO testorder (productid1,ProductName1,orderedqnt1) VALUES ('$getvalue', '$getvalue1','$ordered11')";
if (mysqli_query($conn, $sql))
{ echo "New record created successfully"; }
else
{ echo "Error: " . $sql . "<br>" . mysqli_error($conn); }
mysqli_close($conn);
}
else {
echo" dhur";
}
?>
The < select>-Boxes have to be inside the form and inside the web page at all.
Enter a name-attribute in the < select>-Tag, to make the data available in the saving script vie $_POST
I am not sure, what you want to do, so I don't know if $row['ProductID'] is a reasonable name.
<html>
<body>
<form method="POST" action="#" >
<?php
$servername = "localhost";
$username = "root";
$password ="";
$dbname = "company";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM product";
$result = $conn->query($sql);
while ( $row = mysqli_fetch_assoc($result) ) {
$columnValues[] = $row['ProductID'];
foreach($columnValues as $key => $value) {
$$key = $value;
while ($row = $result->fetch_assoc()) {
echo "<tr>\n". "<br>";
echo "##product-ID## ";
echo "<td>".$row['ProductID']. "</td>\n";
echo " ##product-name## ";
echo "<td>".$row['ProductName']."</td>\n";
echo "<td>\n";
echo " ##dropdown## ";
echo "<select id='$value' name='{$row['ProductID']}'>\n";
echo "<option value='1'>1</option>\n";
echo "<option value='2'>2</option>\n";
echo "<option value='3'>3</option>\n";
echo "<option value='4'>4</option>\n";
echo "<option value='5'>5</option>\n";
echo "<option value='6'>6</option>\n";
echo "</select>\n";
echo "</td>\n";
/* Echo ":::::value variable = "."$value"; */
echo "</tr>\n";
}
}
}
$conn->close();
?>
<input type="submit" name="Submit" value="Submit" /><br>
</form>
</body>
</html>
<body>
<form method="POST" action="#" >
<?php
$servername = "localhost";
$username = "root";
$password ="";
$dbname = "company";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM product";
$result = $conn->query($sql);
while ( $row = mysqli_fetch_assoc($result) ) {
$columnValues[] = $row['ProductID'];
foreach($columnValues as $key => $value) {
$$key = $value;
while ($row = $result->fetch_assoc()) {
echo "<tr>\n". "<br>";
echo "##product-ID## ";
echo "<td>".$row['ProductID']. "</td>\n";
echo " ##product-name## ";
echo "<td>".$row['ProductName']."</td>\n";
echo "<td>\n";
echo " ##dropdown## ";
echo "<select id='$value' name='{$row['ProductID']}'>\n";
echo "<option value='1'>1</option>\n";
echo "<option value='2'>2</option>\n";
echo "<option value='3'>3</option>\n";
echo "<option value='4'>4</option>\n";
echo "<option value='5'>5</option>\n";
echo "<option value='6'>6</option>\n";
echo "</select>\n";
echo "</td>\n";
/* Echo ":::::value variable = "."$value"; */
echo "</tr>\n";
}
}
}
$conn->close();
?>
<input type="submit" name="Submit" value="Submit" /><br>
</form>
</body>
</html>
echo "<select id=$value>\n";
needs a name. So change to
echo "<select id=" . $value . " name='dropdown'>\n";
Then you need to make a second page, use
if(isset($_POST['dropdown'])) {
Then insert or update table with the info. I think you can get this part down quite easily :).
Edit:
while ( $row = mysqli_fetch_assoc($result) ) {
$columnValues[] = $row['ProductID'];
foreach($columnValues as $key => $value) {
$$key = $value;
while ($row = $result->fetch_assoc()) {
You're using 2 while loops. That's 1 to many.

Form values from dropdown list not passing

I created a drop down list that has been populated by the database and now I'm having trouble retrieving the data. Normally, I would know how to retrieve the value of the drop down list if I had to manually name the data, but in this case, I'm not quite sure how I would name it.
Here is my current code:
<h1>Generate Reports</h1>
<form enctype="multipart/form-data" action="http://localhost/yiiFolder/index.php/create" method="post">
<table>
<tr>
<td><strong>Materials</strong></td>
<?php
mysql_connect('host', 'root', 'password');
mysql_select_db ("db");
$sql = "SELECT material_name FROM materials";
$result = mysql_query($sql);
echo "<td><select name='materials'>";
while ($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['material_name'] . "'>" .
$row['material_name'] . "</option>";
}
echo "</select></td></tr> ";
$sql2 = "SELECT location_name From locations";
$result2 = mysql_query($sql2);
?>
<td><strong>Locations</strong></td>
<?php
echo "<td><select name='locations'>";
while ($row2 = mysql_fetch_array($result2))
{
echo "<option value='" . $row2['location_name'] . "'>" .
$row2['location_name'] . "</option>";
}
echo "</select></td></tr>";
?>
<tr>
<td><button name="submit" type=submit>Generate</button></td>
</tr>
</table>
</form>
<?php
$material = $row['material_name'];
$locations = $row2['location_name'];
$generate = $_POST['submit'];
if(isset($generate))
{
echo $material;
echo $locations;
}
?>
You're trying to capture value before the submit button is hit. Also, as Hanky pointed out you're using the wrong names while referring to select data. You should do this instead
if(isset($_POST['submit'])) // this code will run after the button is clicked
{
$material = $_POST['materials']; // and not material_name
$locations = $_POST['locations']; // and not location_name
echo $material;
echo $locations;
}
PS: You're following a very unsecure way of developing a web application. At the very least you need to switch to PDO and always escape the data.

Insert Data from Checkbox and Textbox in DB

I've created two php files with code for an order form for a cafeteria and the correspronding lines of code for inserting the posted values in my database. Here I present them.
CODE FOR addorder_form.php
**<?php
db_connect();
$cats=array("Kafedes", "Rofhmata", "Pota", "Snack/Glyka");
$arrlength=count($cats);
for($i=0;$i<$arrlength;$i++) {
$sql = mysql_query('SELECT title FROM products WHERE cname="'.$cats[$i].'"') or die(mysql_error());
echo '<div id="main_content">';
echo "<h4 style=color:#800000> ".$cats[$i]."</h4>";
echo "<br />";
while($row = mysql_fetch_array($sql, MYSQL_BOTH)){
echo "<div id='center' style='align:center'>";
echo "<input style='text-align:right;' type='checkbox' action='addorder.php' name='products[]' value='".$row["title"]."'>".$row["title"];
echo '</div>';
echo ' <div id="center_side" style="float:right"><form "method="post" action="addorder.php"><input type="text" size="4" padding-left="0.2em" name="quantity"/>';
echo '</div>';
echo '</div>';
echo '<br />';
}
}
echo '<form name="addorder" method="" action="addorder.php" onclick="addorder.php">';
echo '<input type="submit" value="Add order" style="float: right;"><br/>';
echo '</form>';
?>**
CODE FOR addorder.php
**<?php
include_once("buzzcafe_fns.php");
do_html_header("");
$quantity = '';
$title = '';
if (isset($_POST['quantity']) && isset($_POST['products'])) {
if(isset($_POST["Submit"])) {
$quantity = $_POST['quantity'];
$title = $_POST['products'];
if($_POST["Submit"] == "Submit")
{
for ($i=0; $i<sizeof($title); $i++) {
db_connect();
$insertOrder = mysql_query("INSERT INTO orders VALUES('".$title[i]."','".$quantity."')")or die(mysql_error());
}
echo "Record inserted";
}
}
}
?>**
When I run them I have non any syntax errors, though it does not work. As far as the db_connect() is set in the buzzcafe_fns.php file I've included and it is checked that works properly. How can I make my "INSERT INTO" work?
You can use another insert query
First You will check if $title variable array or not.
Next Using For loop
<?php
$con=mysql_connect("localhost","root","");
$db=mysql_select_db("yourdatabasename here" ,$con);
$count=count($title);
for($i=0;$i<$count;$i++){
mysql_query("INSERT INTO orders SET title='".$title[$i]."', quantity='".$quantity."'");
}
?>

Categories