Save selected option in dropdown menu in php - php

I want to insert an image into a selected category in the drop down menu. Didn't want to hard code the menu in html so it can be dynamically updated by phpmyadmin to menu. Currently, all images insert in Greeting_Cards table because it is a place holder for now.
I have tried saving it as a variable: $selected = $_POST['tables']; and passing it as $selected rather than greeting_cards, but that throws back a notice of undefined index and doesn't add to any table at all.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>upload</title>
</head>
<body>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="submit" value="upload" />
</form>
<?php
require_once('/var/db_file.php');
//To do after submit button
if(isset($_POST['submit']))
{
mysql_connect("localhost","root", $pass);
mysql_select_db("images");
$imageName = mysql_real_escape_string($_FILES["image"]["name"]);
$imageData = mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["image"]["type"]);
/* Drop down menu */
$dbname = "images";
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
$tableNames=array();
while($row = mysql_fetch_row($result)){
$tableNames[] = $row[0];
}
echo '<select name="tables" id="tables">';
foreach($tableNames as $name){
echo '<option value="' . $name . '">' . $name . '</option>';
}
echo '</select>';
/* Drop down menu end */
$selected = $_POST['tables'];
echo '<br>';
if(substr($imageType,0,5) == "image"){
mysql_query("INSERT INTO `$selected` VALUES('','$imageName','$imageData')");
echo "Image Uploaded!";
}
else{
echo "Has to be an image!";
}
}
?>
</body>
</html>
Edit 1: Added the $selected variable in, instead of Greeting_Cards
Fix: Moved ending tag of form to encompass the php code.
Thanks for your help!

In this code snippet, the $_POST['tables'] is not getting the assigned value, as the form does not have the select dropdown named tables.
Despite the dropdown is being echoed, it is outside the <form>, thus not being submitted.

Related

How to input a number into a database based of a drop down menu consisting of data from another table in PHP?

I wish to input a number into a database based of a drop down menu consisting of data from another table.
Links table:
Category table:
So basically my drop down will consist of the category.cat written information. But when I submit the form it will input category.id into the links.catID column in the database.
The code I have so far is:
<?php
// since this form is used multiple times in this file, I have made it a
function that is easily reusable
function renderForm($links, $url, $catID, $type, $error){
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>New Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != ''){
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<strong>Link Title: *<br></strong> <input type="text" name="links" size="40" value="<?php echo $links; ?>" /><br><br/>
<strong>URL: *<br></strong> <input type="text" name="url" size="40" value="<?php echo $url; ?>" /><br><br/>
<?php
require 'db/connect.php';
echo" <strong>Category: *<br></strong>";
echo "<select name='catID' id='catID'>";
$sql = "SELECT * FROM links";
$results = $db->query($sql);
if($results->num_rows){
while($row = $results->fetch_object()){
echo "<option>";
echo "{$row->catID}";
echo "</option>";
}
} echo "</select><br>";
?>
<br>
<strong>Type: *<br></strong> <input type="text" name="type" size="40" value="<?php echo $type; ?>" /><br><br/>
<p>* Required</p><br>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit'])){
// get form data, making sure it is valid
$links = mysql_real_escape_string(htmlspecialchars($_POST['links']));
$url = mysql_real_escape_string(htmlspecialchars($_POST['url']));
$catID = mysql_real_escape_string(htmlspecialchars($_POST['catID']));
$type = mysql_real_escape_string(htmlspecialchars($_POST['type']));
// check to make sure all fields are entered
if ($links == '' || $url == '' || $catID == '' || $type == ''){
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($links, $url, $catID, $type, $error);
} else {
// save the data to the database
mysql_query("INSERT links SET links='$links', url='$url', catID='$catID', type='$type'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
} else {
// if the form hasn't been submitted, display the form
renderForm('','','','','');
}
?>
Which gives me the following:
May be try this? (Considering the links.links columns and category.cat columns are common)
Store the value of dropdown in a variable say $dropdown_selected_option
Getting the id from the category table using sql:
$sql = "Select id from category where cat = '$dropdown_selected_option'";
$result = mysqli_query($conn, $sql);
Later run a query again to update the given fields in second table;
Update links set
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result))
{
// Run update query here where $row['id'] has the ID from the category table required.
}
}

What is wrong with this php search page?

I found a tutorial that looked like it would do what I've been trying to do without success. I adapted it to my details and tried it. It doesn't work. When you enter the search and hit submit, all it does is go back to the beginning. I can't see anything wrong with the code so after a couple of hours of trying things, here it is. Can you see what is wrong?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>test</title>
</head>
<body>
<?
if ($searching =="yes")
{
echo "<h2>Search</h2><p>";
if ($find == "")
{
echo "<p>You forgot to enter a search term";
exit;
}
mysql_connect('localhost', 'user', 'password') or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
$data = mysql_query("SELECT * FROM engravers WHERE upper($field) LIKE'%$find%'");
while($result = mysql_fetch_array( $data ))
{
echo $result['Country'];
echo "<br>";
echo $result['Year'];
echo "<br>";
echo $result['Engraver1Surname'];
echo "<br>";
echo $result['Designer1Surname'];
echo "<br>";
echo $result['Printer'];
echo "<br>";
echo "<br>";
}
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
echo "<b>Searched For:</b> " .$find;
}
?>
<h2>Search</h2>
<form name="search" method="post" action="<?=$PHP_SELF?>">
Search for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="Country">Country</option>
<Option VALUE="Year">Year</option>
<Option VALUE="Engraver1Surname">Engraver</option>
<Option VALUE="Designer1Surname ">Designer</option>
<Option VALUE="Printer">Printer</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" value="Search" />
</form>
</body>
</html>
As mentioned in my comment, after POSTing, you need to grab the variables from the $_POST array. Something like:
if ($_POST['searching'] == "yes") {
$find = $_POST['find'];
$field = $_POST['field'];
// etc...
This looks like very old PHP code that had register_globals on. It doesn't work like that anymore.
Use the superglobal $_POST to get to your variables, for example:
if ($_POST['searching'] =="yes") {
...
}
Also, read into SQL injection and how to avoid it.
You need to set the variables on begin:
//set default values
$find="";
$searching="";
$field="";
If(isset($_POST['searching']) && $_POST['searching']="yes"){
$find= mysql_real_escape_string($_POST['find']);
$searching=mysql_real_escape_string($_POST['searching']);
$field=mysql_real_escape_string($_POST['field']);
...

How to keep the value of selected item of a drop down after form submission in PHP?

I am just building a simple search page in PHP. I need to know how can i keep the selecte value of the drop down list upon form submission. Currently, the value resets to the first index.
Can I do this via PHP without using client-side script?
Here is the code:
<?php
mysql_connect('localhost','root','');
mysql_select_db('hotel');
$sql = "SELECT * FROM customers";
$result = mysql_query($sql);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form method="get">
<select name="field" id="field">
<?php
/*if($field == 'Active')
'selected="selected"';
*/
while($rows = mysql_fetch_array($result))
echo '<option>'.$rows['customer_id'].'</option><br>';
?>
</select>
<?php
if (isset($_GET['Search']) && $_GET['action']=='search')
{
$sql="SELECT * FROM customers WHERE customer_id=".$_GET['field'];
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
echo '<br>Customer Name: '.$row['customer_name'].'<br>';
echo 'Email Address: '.$row['Email_Addr'].'<br>';
echo 'Contact No: '.$row['Contact_No'].'<br>';
}
?>
<input type="hidden" name="action" value="search" />
<br><input type="submit" value="search" name="Search" onclick="" />
</form>
</body>
</html>
usually like this.
echo '<option';
if ($_GET['field'] == $rows['customer_id']) echo " selected";
echo '>'.$rows['customer_id'].'</option>';
And please don't use the mysql_* functions to write new code, especially when you are learning. The mysql_* functions are in the process of becoming deprecated, they will be removed in future versions of PHP. Use mysqli_* or PDO objects instead.
You can check if the get value is the same than the select value :
while($rows = mysql_fetch_array($result))
echo '<option value="'.$rows['customer_id'].'" '.($rows['customer_id'] == $_GET['field']?'selected="selected"':'').'>'.$rows['customer_id'].'</option><br>';
When printing the select options, you can check for the value and set any mathing option to selected, maybe like this:
while($rows = mysql_fetch_array($result)){
if(!empty($_GET['field']) && $_GET['field'] == $rows['customer_id']){
echo '<option selected="selected">'.$rows['customer_id'].'</option><br>';
}
else {
echo '<option>'.$rows['customer_id'].'</option><br>';
}
}

Values are not being deleted in a table in php?

Hello im trying to delete which ever value is selected in a drop down list.
I cant seem to understand what is going on
I have 2 pages 1 with my connection and functions to view the table in a drop down (which works) and a delete function (which doesn't seem to work) and another to call the function in and to delete which ever value is selected.
connection.php
<?php
//Connect to the database
function getSQLConnection() {
$mysqlConnection = new PDO('mysql:host=localhost;dbname=isad235_100000', "root", "");
return $mysqlConnection;
}
//Get all results from members table
function getResults($tablename) {
$sql = "SELECT * FROM " . $tablename;
$mysqlConnection = getSQLConnection();
$ResultSet = $mysqlConnection->query($sql);
return $ResultSet;
}
//Delete results from members table
function deleteValue($id) {
$sql = "DELETE FROM members WHERE member_id = '$id'";
$mysqlConnection = getSQLConnection();
$ResultSetting = $mysqlConnection->query($sql);
return $ResultSetting;
}
?>
delete.php
<?php
include_once 'connection.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add</title>
</head>
<body>
<h1> Delete a Member from the Members Table. </h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method='post'>
Delete Member:
<select name='members' value='members'id="Mmembers">
<?php
$results = getResults('members');
if ($results) {
foreach ($results as $row) {
echo '<option value="' . $row['member_id'] . '">' . $row['name'] . '</option>';
}
}
else
echo '<option value="0"0"> No Data</option>';
?>
</select>
<input type="submit" id="delete" value="Delete"/>
<br/>
<br/>
</form>
<?php
if (isset($_POST['members'])) {
$ResultSetting = deleteValue(($_POST['members']));
}
?>
<br/>
<br/>
<form action='index.php' method='GET'>
Go Back:
<input type="submit" name="submit" value="Return"/>
</form>
<br/>
</body>
</html>
I ran your code and don't see any errors with it. Make sure the id column on your 'members' table is called 'member_id'. If there is a discrepancy in the name then the values for the option elements wouldn't be set. Also, the value you just deleted would still appear after the initial page submit. If you reload the page after the submit, you'll see the value has disappeared.

How to select a row(s) from mysql table using checkbox (PHP)

Hi I have a page that displays all of the contents of my table. Alongisde each row of the table I also have a column containing a checkbox. When the user selects one or more rows by ticking the checkbox and pressing the submit button, I want just those rows to appear in a table on the next page (buy.php). I know it is basically a select statement per row that is selected. But I dont know how to approach this. Can anybody help? Thanks
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Shopping</title>
</head>
<body>
<form action='buy.php' method='post'>
<input type='submit' value='Submit' />
</form>
<h1>Buy</h1>
<?php // Script 12.7 - sopping.php
$db = mysql_connect('localhost', '#####', '#####');
mysql_select_db('shopping', $db);
$query = 'SELECT * FROM Items';
if ($r = mysql_query($query, $db)) {
print "<form>
<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['ID']}</td>
<td>{$row['Name']}</td>
<td>{$row['Cost']}</td>
<td><input type='checkbox' name='buy[{$row['ID']}] value='buy' /></td>
</tr>";
}
print "</table>
</form>";
} else {
print '<p style="color: blue">Error!</p>';
}
mysql_close($db); // Close the connection.
?>
</body>
</html>
EDIT: I tried the suggestion below and I did not get a table. Just the title of the page appeard:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Confirmation</title>
</head>
<body>
<h1>Order Details</h1>
<?php // Script 12.7 - buy.php
$db = mysql_connect('localhost', '#####', '#####');
mysql_select_db('shopping', $db);
foreach($_POST['buy'] as $item) {
$query = 'SELECT * FROM Items WHERE ID = $item';
if ($r = mysql_query($query, $db)) {
print "<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['ID']}</td>
<td>{$row['Name']}</td>
<td>{$row['Cost']}</td>
</tr>";
}
print "</table>";
} else {
print '<p style="color: blue">Error!</p>';
}
}
mysql_close($db);
?>
</body>
</html>
You need to create a dynamic SQL query.
1) I suggest you change your checkbox to the following
<input type='checkbox' name='buy[]' value='{$row['ID']}' />
2) Loop through all of the buy options
<?php
foreach($_POST['buy'] as $item) {
// Append the ID (in the $item variable) to the SQL query, using WHERE `ID` = $item OR `ID` = $item and so on
}
?>
UPDATE:
<?php // Script 12.7 - buy.php
$db = mysql_connect('localhost', '#####', '#####');
mysql_select_db('shopping', $db);
$query = 'SELECT * FROM Items WHERE ';
$item_count = count($_POST['buy']);
for($i = 0; $i < $item_count; $i++) {
$itemid = (int)mysql_real_escape_string($_POST['buy'][i]); // Secures It
$query .= '`ID` = '.$itemid;
if($i +1 < $item_count) {
$query .= ' OR ';
}
}
if ($r = mysql_query($query, $db)) {
print "<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['ID']}</td>
<td>{$row['Name']}</td>
<td>{$row['Cost']}</td>
</tr>";
}
print "</table>";
mysql_close($db);
?>
// this checkbox use
//buy.php foreach($_POST['buy'] as $item) {
$query = "SELECT * FROM Items WHERE ID = $item"; //use " "
// try it if any problem please carefully look you database table // download file and try it 2file with table sql data
// https://copy.com/8ZsBAFj7LvypLJkK
// this checkbox use
<input type='checkbox' name='buy[]' value='{$row['ID']}' />
//buy.php
foreach($_POST['buy'] as $item) {
$query = "SELECT * FROM Items WHERE ID = $item";
//use " "
// try it if any problem please carefully look you database table
// download file and try it 2file with table sql data
// https://copy.com/8ZsBAFj7LvypLJkK

Categories