PHP dropdown list - php

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();
}
}

Related

insert dynamic dropdown values in the database on button click in 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.

Delete MySQL Database selection from dropdown menu in PHP

I'm currently working on a knowledge base for articles for our schools info center. Currently I'm making a page for moderators to delete articles. The page grabs all data from the "articles" table in the database to display it in a dropdown menu. The user can then select whichever and press delete. Which I intend to have said button take the selected ID and remove it from the database. However it will not delete.
Code:
<?php
session_start();
echo 'Select an article to delete, '.$_SESSION['username']. '<br>';
include 'index.php';
{
if(isset($_POST['Delete'])){
$delete = 'DELETE FROM articles WHERE articleID IN (' . implode(',', $_POST['articles']) . ')';
if(mysqli_query($link, $delete))
{
echo '<script language="javascript">';
echo 'alert("Article was deleted!")';
echo '</script>';
}
else
{
echo 'ERROR: Could not delete article';
}
}
}
?>
<form method="post" action="deleteArticles.php">
<select name="articles" multiple="multiple">
<?php
$sql=mysqli_query($link,"SELECT * FROM articles ORDER BY title");
while ($row = mysqli_fetch_assoc($sql))
{
echo '<option value="' . $row['articleID'] . '">' . $row['title'] . '</option>';
}
?>
</select>
<input type="submit" value="Delete" name="Delete" />
</form>
You missed to close your open select tag. You also didn't add multiple attribute to allow multiple selection.
<select name="articles" multiple="multiple">
<?php
$sql=mysqli_query($link,"SELECT * FROM articles ORDER BY title");
while ($row = mysqli_fetch_assoc($sql))
{
echo '<option value="' . $row['articleID'] . '">' . $row['title'] . '</option>';
}
?>
</select>
Uneeded {} wrapping removed.
And this:
<?php
session_start();
echo 'Select an article to delete, '.$_SESSION['username']. '<br>';
include 'index.php';
{
if(isset($_POST['Delete'])){
$delete = 'DELETE FROM articles WHERE articleID IN (' . implode(',', $_POST['articles']) . ')';
if(mysqli_query($link, $delete))
{
echo '<script language="javascript">';
echo 'alert("Article was deleted!")';
echo '</script>';
}
else
{
echo 'ERROR: Could not delete article';
}
}
}
?>
To:
<?php
session_start();
echo 'Select an article to delete, '.$_SESSION['username']. '<br>';
include 'index.php';
if(isset($_POST['Delete'])){
$delete = 'DELETE FROM articles WHERE articleID IN (' . implode(',', $_POST['articles']) . ')';
if(mysqli_query($link, $delete))
{
echo '<script language="javascript">';
echo 'alert("Article was deleted!")';
echo '</script>';
}
else
{
echo 'ERROR: Could not delete article';
}
}
?>
Since it is multiple selection, change select name to articles[]
Like:
<select name="articles[]" multiple="multiple">

Trying to update a single item's quantity when an item is "purchased" from my store, but every item in my table is updated. Why?

Please understand- I am not experienced with PHP. But I know I am close to figuring this out.
I have a table, generated by a while loop (getting data from a MySQL database), that gives the customer a list of albums from an artist. I want the customer to be able to input the quantity of the album they wish to purchase, and have the database update appropriately. I can get the code to loop through and update every album in my table (based on user input), but that is obviously not what I want. How can I make it so only ONE album is updated at a time??
Here is my code:
<div id = "MusicSearch"><h4>Search For Music</h4></div>
<div id="search">
<form method="post" action="get-records.php?go" id="searchform">
<input type="text" name="artistName">
<input type="submit" name="submit-form" value="Search">
</div>
<?php
if(isset($_POST['submit-form'])){
$artistName = $_POST['artistName'];
if(isset($_GET['go'])){
if(preg_match("/^[A-Za-z]+/", $_POST['artistName'])){
include 'include/connect.php';
$sql = "
SELECT y.artistName
, x.albumName
, x.albumID
, x.cost
, x.stock
FROM album x
JOIN artist y
ON x.artistID = y.artistID
WHERE y.artistName LIKE '%" .$artistName. "%'
";
$result = $con->query($sql);
echo '<table><tr><th>Artist</th><th>Album</th><th>Cost</th><th>Stock</th><th>Quantity</th></tr>';
?>
<?php
while ($row = $result->fetch_array()) {
$albumName=$row['albumName'];
$cost=$row['cost'];
//$albumID=$row['albumID'];
$stock=$row['stock'];
echo '<tr>';
echo '<td>' . $artistName . '</td>';
echo '<td>' . $albumName . '</td>';
echo '<td>' . $cost . '</td>';
echo '<td>' . $stock . '</td>';
?>
<td><form method="post" action="get-records.php">
<input type="hidden" name="albumID[<?php echo $row['albumID']; ?>]" value="<? echo $row['albumID']; ?>"></input>
<input type="number" name="quantity[<?php echo $row['albumID']; ?>]" value="<?php echo $row['quantity']; ?>"></input>
<input type="submit" name="purchase-form" value="Purchase"/></form></td>
<?php
}
echo "</table>";
}
}
}
if(isset($_POST['quantity'])){
foreach($_POST['albumID'] as $key => $id){
$quan = mysqli_real_escape_string($con, $_POST['quantity'][$key]);
$q = "UPDATE album SET stock = stock-$quan WHERE albumID = albumID";
try{
$result = $con->query($q);
if (!$result)
echo "Error, try again " . mysqli_error($con);
if(is_null('id'))
throw new Exception('Error. Try again');
}
catch (Exception $ex) {
echo '<div class="error">' . $ex->getMessage() . '</div>';
}
}
}
?>
replace your update query with this UPDATE album SET stock = 'stock-".$quan."' WHERE albumID = '".$id."'
May you need to use $_POST['albumID']'s value Instead of albumID, here
$q = "UPDATE album SET stock = stock-$quan WHERE albumID = $id";
albumID = albumID is true for all rows that's why its updating all records

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.

Session not retaining original value on next page

This page shows the status of several chatrooms. A user can click a button to get them into the room of the person they choose. The nickname session of the person they select should be sent to the room through the form. The sessions are correct on this page, but when the values are submitted to the room, the nickname changes to the 1st nickname in the database, rather than the one I have passed to the page. How can I get the session to use the data it initially collected? (The page that receives the values only echos sessions, so I didn't post it)
<?php
session_start();
require_once('connect.php');
$con = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME) or die('Connection failed: ' . mysqli_connect_error());
$sql = mysqli_query($con, "SELECT UserType, NickName, Online, InChat FROM main_member WHERE UserType = 2 ORDER BY Online DESC");
while($row = mysqli_fetch_array($sql)){
$UserType = $row['UserType'];
$NickName = $row['NickName'];
$Online = $row['Online'];
$InChat = $row['InChat'];
$_SESSION['NickName_Session'] = $NickName;
echo '<table width="353" border="0">';
echo '<tbody>';
echo '<tr>';
echo '<td width="248" height="51">';
echo Status($Online,$InChat,$NickName);
echo '</td>';
echo '</tr>';
echo '</tbody>';
echo '</table>';
}
function Status($Online,$InChat,$NickName){
if ($Online == 0) {
echo 'I am not online.';
}
elseif($Online == 1 && $InChat == 0){
echo 'I am online and I will be in my chatroom shortly.';
}
elseif($Online == 1 && $InChat == 1){
echo 'I am online.';
echo '<form name="get_nickname" id="get_nickname" action="script.php" method="POST">';
echo '<input type="hidden" name="nickname" id="nickname" value="' . $_SESSION['NickName_Session'] . '">';
echo '<input type="submit" name="submit" id="submit" value="Start Chat" />';
echo '</form>';
}
}
mysqli_close($con);
?>
this is the script page:
session_start();
if(!isset($_SESSION['file'])) {
$_SESSION['file'] = (rand(1000000, 9999999)) . round(10*microtime(TRUE));
}
if(isset($_POST['create'])) {
$_SESSION['file'] = (rand(1000000, 9999999)) . round(10*microtime(TRUE));
}
$url='chat_container.php';
Header("Location: $url");
exit();
and here is the chat container where I need the nickname:
session_start();
require_once('connect.php');
echo $_SESSION['NickName_Session'];

Categories