Pulling multiple fields from database using forms and php - php

I have a database with multiple rows with various fields.
I have a form that contains a drop down list.
The drop down list displays one of the database fields (field_name) for each row in the database.
When the user selects the desired entry hits SUBMIT, that value is passed to the results.php page and can be used via $_POST.
All of this currently works.
I would like a way to send the rest of the row's fields that correspond to the row of the selected field (not just the "field_name") from the database along with what is selected from the drop down menu.
For instance, if I have a database with rows with a fields named "name", "date", and "age", I would like to have all the database rows "name"s appear in the drop down list and once submitted, pass that particular name's "date" and "age" on to the results.php for use on that page.
<html>
<head>
<title>Drop Down Test</title>
</head>
<body style="font-family: verdana; font-size: 11px;">
<?php
//Variables for connecting to database.
$hostname = "abcd";
$username = "abcd";
$dbname = "abcd";
$password = "abcd";
$usertable = "abcd";
//Connecting to database
$connection = mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database!");
$db = mysql_select_db($dbname);
$query = "SELECT * FROM abcd";
$result = mysql_query($query) or die(mysql_error());
?>
<h2>Drop Down Test Form</h2>
<p>Please fill out the form below and click submit.</p>
<form action="results.php" method="POST">
<p>Drop Down Test:
<select name='event'>
<!-- Drop down -->
<?php
while($row = mysql_fetch_array($result))
{
echo '<option>' . $row['field_name']. '</option>';
}
?>
</select>
<p><input type="submit" value="Submit"><p>
</form>

you should put a value on your option like this:
echo '<option value = "'.$row['field_name'].'" name = "">' . $row['field_name']. '</option>';
then you can access it by $_POST['event'];
UPDATE
getting all the values from the select, you can use $_SESSION variables to pass it to the other php.file.

// First of all, I advice you to connect via PDO, or at least msqli, because mysql_query is depreciated.
// To connect with database you need:
DEFINE("USER", "root");
DEFINE("DBNAME", "test");
DEFINE("DBPASSWORD", "");
DEFINE("DBHOST", "localhost");
$dbh = new PDO('mysql:host='.DBHOST.';dbname='.DBNAME,USER,DBPASSWORD,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
//The query:
$sth = $dbh->prepare("SELECT name,age,date FROM test");
$sth->execute();
//the drop down form
echo '<form action="results.php" method="POST">
<select name="event"><option value=0></option>';
while ($result = $sth->fetch(PDO::FETCH_ASSOC)) { extract($result);
echo '<option value="date:'.$date.'-age:'.$age.'"/>'.$name.'</option>';
echo '</select>
<p><input type="submit" value="Submit"><p>
</form>';
}
//the event in the records.php by clicking submit
if(isset($_POST['event'])){
echo 'name:',$name'-date:',$date,'-$age',$age;
}

This did the trick (in results.php):
<?php
$hostname = "****";
$username = "****";
$dbname = "****";
$password = "****";
$usertable = "abcd";
$connection = mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database!");
$db = mysql_select_db($dbname);
//it was this SQL query that was the key, namely the WHERE statement
$query = "SELECT * from abcd where field_name='$_POST[event]'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result);
echo "id: " . $row[0] . "<br/>";
echo "field_name: " . $row[1] . "<br/>";
//etc...
//try to throw the individual results into variables
$variable = $row[1];
echo "Check to see that the variable was passed a value: " . $variable . "<br />";
echo "Check to see that form selection carried over: " . $_POST['event'] . "<br />";
?>
I realize this is not the "up-to-date" way of doing things and I will now try to get everything "modernized".
Thanks for all the help!

Related

php search works as seperate page, but not on same page

I'm working on a project where I can use multiple forms on an html page to search and update tables from a mysql database. I have created a basic html form that will run a search on a separate php file. When I try to integrate that same php script into that same html it finds no results. Any help would be appreciated.
basic html
<html>
<body>
<form name="search" method="post" action="searchresults.php">
<input name="search" type="text" size="40" maxlength="50" />
<input type="submit" name="Submit" value="Search" />
</form>
</body>
</html>
search php
<?php
$database = "dbname";
$username = "name";
$password = "pass";
$host = "host";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error){
die("Failed:" . $conn->connect_error);
}
echo"Successful";
$query = $_POST['search'];
$query = htmlspecialchars($query);
$raw_results = mysqli_query($conn,"SELECT * FROM beers WHERE name LIKE '%".$query."%'");
if(mysqli_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysqli_fetch_array($raw_results)){
echo "<p><h3>".$results['Name']."</h3>".$results['Brewery']."</p>";
}
}
else{ // if there is no matching rows do following
echo "No results";
}
?>
This works separated, but if I copy the same php script and insert it into the main html it connects but finds no results. Tried using _GET instead of _POST removed the action field and Ive searched all over for similar issues. If I scale everything completely down it gives me a parse error for $query = htmlspecialchars($query); , any thoughts?
Apply if (isset($query)) {...}. Only when search name is valid can you gain results.
<?php
$query = $_POST['search'];
// Apply validation.
if (isset($query)) {
$query = htmlspecialchars($query);
echo"Successful";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
die("Failed:" . $conn->connect_error);
}
$raw_results = mysqli_query($conn, "SELECT * FROM beers WHERE name LIKE '%" . $query . "%'");
if (mysqli_num_rows($raw_results) > 0) { // if one or more rows are returned do following
while ($results = mysqli_fetch_array($raw_results)) {
echo "<p><h3>" . $results['Name'] . "</h3>" . $results['Brewery'] . "</p>";
}
} else { // if there is no matching rows do following
echo "No results";
}
}
?>

Data Not Displaying in Drop Down by mysqli

I have a small data entry form which works well, but someone asked me if I can have the 'name' field as a drop down box of users as opposed to having to type in a name and risk a spelling mistake - yep makes sense.
This is pretty new to me and following some information on here and other sites I have tried to accomplish the first part.. populating the drop down box.. nope. No errors, just nothing in the box.
To power this I have tblStaffNames (userID, txtName)
The code I am using looks like this;
<?php
include("connect-db.php");
$queryNames = "SELECT txtName FROM tblStaffName";
$resultNames = $conn->query($queryNames);
?>
<select name="personname">
<?php
while ($rowNames = $resultNames->fetch_assoc()) {
echo "<option value=\"{$rowNames['txtName']}\">";
echo $rowNames['txtName'];
echo "</option>";
}
?>
</select>
The $conn is all good as on another page I can display data in a table from the database, including tblStaffNames - so I can rule out any sort of connection issues.
When I run the page, the little drop down box appears, very simple like but it's there, just no values.
I will end up using the value like this as part of the data entry form;
<td><select name="personname" style="width:100px" ><?php echo $RowNames; ?></select></td>
But I can't actually get to the point of displaying data.
Can anyone help me out with what I am doing wrong here?
I tested your code with slight changes. It works for me. Please check your DB connection is OK as I have done in my code.
<?php
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "staff_db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$queryNames = "SELECT txtName FROM tblStaffName";
$resultNames = $conn->query($queryNames);
//Generating the Dropdown
echo "<select name=\"personname\">";
while ($rowNames = $resultNames->fetch_assoc()) {
echo "<option value=\"{$rowNames['txtName']}\">";
echo $rowNames['txtName'];
echo "</option>";
}
echo "</select>";
?>
I dont know what your error but for better understanding i change your code like this
$queryNames = "SELECT userID,txtName FROM tblStaffName";
$resultNames = $conn->query($queryNames);
?>
<select name="personname">
<?php
while ($rowNames = $resultNames->fetch_assoc()) {
?>
<option value="<?php echo $rowNames['userID']; ?>">
<?php echo $rowNames['txtName']; ?>
</option>
<?php
}
?>
</select>
Following code snippets works for me.
<?php
$servername = "localhost";
$username = "user";
$password = "password";
//DB Server Connection
$conn = mysql_connect($servername, $username, $password) or die("Connection establishment failed");
//DB Selection
$selected = mysql_select_db("staff_db", $conn) or die("Could not select DB");
//Query String
$queryNames = "SELECT txtName FROM tblStaffName";
//Query the DB
$resultNames = mysql_query($queryNames);
//Generating the Dropdown
echo "<select name=\"personname\">";
while ($rowNames = mysql_fetch_array($resultNames)) {
echo "<option value=\"{$rowNames['txtName']}\">";
echo $rowNames['txtName'];
echo "</option>";
}
echo "</select>";
?>

Filter SQL results with drop down menu in PHP

I ve been stuck on this problem for about 3 days now. I would appreciate any help i can with this problem how ever please can you explain where and how i have gone wrong as i would like to learn and understand!
Basically what i am trying to achieve is the following.
A drop down menu, that will display the results of the selected column in my database.
My database has 3 columns "project_name","stage" and "project_details"
If the user selects "stage" it must only display / echo the results form the "stage" column on the screen.
The code below is what i have so far! I know i am subject to an SQL injection but i am trying to get the filter to work first then i will sort that out.
At the moment i keep getting an error on line 42 and 56, i would appreciate any help or input for anyone!
<form action='filter2.php' method='post' name='value' >
<select name="value">
<option value="project_name">project_name</option>
<option value="stage">stage</option>
<option value="project_details">project_details</option>
</select>
<br />
<input type='submit' value = 'Filter'>
</form>
<?php
// Authentication Variables
$servername = "localhost";
$username = "basic";
$password = "redrobinX123";
$dbname = "basic_forms1";
// Make connection
$con = mysql_connect($servername, $username, $password, $dbname);
// If error connecting
if (!$con) {
die(mysql_error("could not connect"));
}
// If post value isset
if(isset($_POST['value'])) {
$column = $_POST['value']; // Set Column
$query = "SELECT". $column . "FROM photo"; // Create Query
$sql = mysql_query($query); // Run Query
// Loop through results
while ($row = mysql_fetch_array ($sql)){
echo "<br>". $row[$column] . "<br>";
}
// Close connection
mysql_close($con);
}
?>
Set it up like this....
// Authentication Variables
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Make connection
$con = mysqli_connect($servername, $username, $password, $dbname);
// If error connecting
if (!$con) {
die(mysqli_error("could not connect"));
}
// If post value isset
if(isset($_POST['value'])) {
$column = $_POST['value']; // Set Column
$query = "SELECT $column FROM photo"; // Create Query
$sql = mysqli_query($con, $query); // Run Query
// Loop through results
while ($row = mysqli_fetch_array($sql, MYSQLI_ASSOC)){
echo "<br>". $row[$column] . "<br>";
}
// Close connection
mysqli_close($con);
}
I think you mixing mysql and mysqli functionalities. Try this
<form action='filter2.php' method='post' name='value' >
<select name="value">
<option value="project_name">project_name</option>
<option value="stage">stage</option>
<option value="project_details">project_details</option>
</select>
<br />
<input type='submit' value = 'Filter'>
</form>
<?php
// Authentication Variables
$servername = "localhost";
$username = "basic";
$password = "redrobinX123";
$dbname = "basic_forms1";
// Make connection
$con = mysqli_connect($servername, $username, $password, $dbname);
// If error connecting
if (!$con) {
die(mysqli_error("could not connect"));
}
// If post value isset
if(isset($_POST['value'])) {
$column = $_POST['value']; // Set Column
$query = "SELECT ". $column . " FROM photo"; // Create Query
$sql = mysqli_query($con,$query); // Run Query
// Loop through results
while ($row = mysqli_fetch_array ($sql)){
echo "<br>". $row[$column] . "<br>";
}
// Close connection
mysqli_close($con);
}
?>

Entering data into mysql database using php

Customer will complete a form and enter a pathway where they will want the CSV to be exported to. The pathway is entered using the top section of the php (below):
<form action="register.php" method="post">
Enter file pathway where CSV will be saved: <input type="text" name="username" required="required"/> <br/>
<input type="submit" value="Enter"/>
</form>
</body>
I want to create a variable called pathway. At the moment I can get text entered into the correct row in the mysql database (I can get John printed in the database), but not the correct text that was entered into the form (i.e. $pathway).
I want to create a variable because after saving the pathway in the database i also want to use it in an export.php.
I am assuming i also need something like this:
if($_SERVER["REQUEST_METHOD"] == "POST"){
$pathway = mysql_real_escape_string($_POST['pathway']);
// but i can't seem to piece it altogether.
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "first_db";
$table_users = $row['pathway'];
$pathway = "pathway";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO users (pathway)
VALUES ('John')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
This shoud work, if not then check your usename and password...
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "first_db";
$pathway = $_POST['username']; username - is the name of your input.
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO users (pathway)
VALUES ('$pathway')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
your DB username is Null
Change $username = ""; to $username = "root";
Your input field name is username
change it to pathway for $_POST['pathway'] to work
<form action="register.php" method="post">
Enter file pathway where CSV will be saved:
<input type="text" name="pathway" required="required"/> <br/>
<input type="submit" value="Enter"/>
</form>
First of all, you've got 'username' as the name of the field using for type a pathway, so rename it to 'pathway'.
I don't know if I understand you, but do you just want to read posted content?
Try something like:
$pathway = $_POST['pathway']
I strongly recommend to use object-oriented style with
$conn = new mysqli...
and then
mysqli->prepare(), mysqli->bind_param(), mysqli->execute()
With this you won't have to deal with mysqli_real_escape_string etc.

How do I insert into a form with over 100 fields

I've created a user form in which once the submit button is pressed I would like to send/insert the data to mysql database adding a new record. The form has over 100 input fields. How can I accomplish this. Here is my sample php code.
<html>
<head>
</head>
<body>
<?php
if (isset($_POST['submit'])){
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "hostname";
$username = "username";
$password = "password";
$dbname = "dbname";
$mystuff = "tenant_lname","tenant_fname","tenant_mname","ssn","dl_number","dl_state","birthday","tenant_hphone","tenant_wphone","tenant_cphone","curr_street","curr__unit","curr_city","curr_state","curr_zip","how_long_from","how_long_to","last_rent_mnt","last_rent_amt","own_man_name","own_man_tel","curr_reason","pre_street","pre_unit","pre_city","pre_state","pre_zip","pre_from","pre_to","pre_last_rent","pre_amt","pre_owner","pre_owner_tel","pre_reason","sec_pre_street","sec_pre_unit","sec_pre_city","sec_pre_state","sec_pre_zip","sec_pre_from","sec_pre_to","sec_pre_last_paid_mnt","sec_pre_amt","sec_pre_owner","sec_pre_owner_tel","sec_pre_reason","curr_emp_name","curr_emp_add","curr_emp_phone","curr_emp_pos","curr_emp_bus_type","curr_emp_sup","curr_emp_from","curr_emp_to","curr_emp_salary","pre_emp_name","pre_emp_add","pre_emp_phone","pre_emp_pos","pre_emp_bus_type","pre_emp_sup_name","pre_emp_from","pre_emp_to","pre_emp_salary","move_date","addntl_occ_name","addntl_occ_age","addntl_occ_relation","addntl_ft","addntl_pt","addntl_occ1_name","addntl_occ1_age","addntl_occ1_relation","addntl_occ1_ft","addntl_occ1_pt","addntl_occ2_name","addntl_occ2_age","addnt2_occ1_relation","addntl_occ2_ft","addntl_occ2_pt","addntl_occ3_name","addntl_occ3_age","addntl_occ3_relation","addntl_occ3_ft","addntl_occ3_pt","credit_yes","credit_no","det_yes","det_no","evict_yes","evict_no","bnkry_yes","bnkry_no","fel_yes","fel_no","pet_yes","pet_no","pet_numb","pet_type","furn_yes","furn_no","ins_cov_yes","ins_cov_no","ints_yes","ints_no","ints_type","smoke_yes","smoke_no","occ_smoke_yes","occ_smoke_no","explain_smoke","bnk_name","bnk_add","checking","checking_bal","saving","saving_bal","bnk_name1","bnk_add1","checking1","checking_bal1","saving1","saving_bal1","other_income","credit_name","credit_add","credit_city","credit_acct","credit_bal","credit_payment","credit_name1","credit_add1","credit_city1","credit_acct1","credit_bal1","credit_payment1","credit_acct2_name","credit_add2","credit_city2","credit_acc2","credit_bal2","credit_payment2","credit_acc3_name","credit_acc3_add","credit_acc3_city","credit_acc3_number","credit_acc3_bal","credit_acc3_payment","emer_contact_name","emer_contact_add","emer_relation","emer_phone","reg_owner_yes","reg_owner_no","reg_who","vehicle_year","vehicle_make","vehicle_model","vehicle_color","vehicle_license","veh_state","vehicle2_year","vehicle2_make","vehicle2_model","vehicle2_color","vehicle2_license","veh2_state";
$con = mysql_connect("$hostname","$username","$password");
if (!$con){
die ("Can not connect:" . mysql_error());
}
mysql_select_db("dbname",$con);
$sql = "INSERT INTO dbname ($mystuff) VALUES ('$_POST[$mystuff]')";
mysql_query($sql,$con);
mysql_close($con);
}
?>
</body>
</html>
$mystuff should be an array.
You can generate your query and form with an loop.
Do validation if these is for productive use!
$_POST is also an array, so $_POST["field1", "field2", ...] ist an syntax error.
You can only access one key at once e.g. $_POST['field1'] . ',' . $_POST['field2']
You can join all values in an array by an char (e.g. ',') with implode()
rethink your Database schema!
untested:
<html>
`enter code here`<head>
`enter code here`</head>
<body>
<?php
>if (isset($_POST['submit'])){
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "hostname";
$username = "username";
$password = "password";
$dbname = "dbname";
$mystuff = array( "tenant_lname","tenant_fname","tenant_mname","ssn","dl_number","dl_state","birthday","tenant_hphone","tenant_wphone","tenant_cphone","curr_street","curr__unit","curr_city","curr_state","curr_zip","how_long_from","how_long_to","last_rent_mnt","last_rent_amt","own_man_name","own_man_tel","curr_reason","pre_street","pre_unit","pre_city","pre_state","pre_zip","pre_from","pre_to","pre_last_rent","pre_amt","pre_owner","pre_owner_tel","pre_reason","sec_pre_street","sec_pre_unit","sec_pre_city","sec_pre_state","sec_pre_zip","sec_pre_from","sec_pre_to","sec_pre_last_paid_mnt","sec_pre_amt","sec_pre_owner","sec_pre_owner_tel","sec_pre_reason","curr_emp_name","curr_emp_add","curr_emp_phone","curr_emp_pos","curr_emp_bus_type","curr_emp_sup","curr_emp_from","curr_emp_to","curr_emp_salary","pre_emp_name","pre_emp_add","pre_emp_phone","pre_emp_pos","pre_emp_bus_type","pre_emp_sup_name","pre_emp_from","pre_emp_to","pre_emp_salary","move_date","addntl_occ_name","addntl_occ_age","addntl_occ_relation","addntl_ft","addntl_pt","addntl_occ1_name","addntl_occ1_age","addntl_occ1_relation","addntl_occ1_ft","addntl_occ1_pt","addntl_occ2_name","addntl_occ2_age","addnt2_occ1_relation","addntl_occ2_ft","addntl_occ2_pt","addntl_occ3_name","addntl_occ3_age","addntl_occ3_relation","addntl_occ3_ft","addntl_occ3_pt","credit_yes","credit_no","det_yes","det_no","evict_yes","evict_no","bnkry_yes","bnkry_no","fel_yes","fel_no","pet_yes","pet_no","pet_numb","pet_type","furn_yes","furn_no","ins_cov_yes","ins_cov_no","ints_yes","ints_no","ints_type","smoke_yes","smoke_no","occ_smoke_yes","occ_smoke_no","explain_smoke","bnk_name","bnk_add","checking","checking_bal","saving","saving_bal","bnk_name1","bnk_add1","checking1","checking_bal1","saving1","saving_bal1","other_income","credit_name","credit_add","credit_city","credit_acct","credit_bal","credit_payment","credit_name1","credit_add1","credit_city1","credit_acct1","credit_bal1","credit_payment1","credit_acct2_name","credit_add2","credit_city2","credit_acc2","credit_bal2","credit_payment2","credit_acc3_name","credit_acc3_add","credit_acc3_city","credit_acc3_number","credit_acc3_bal","credit_acc3_payment","emer_contact_name","emer_contact_add","emer_relation","emer_phone","reg_owner_yes","reg_owner_no","reg_who","vehicle_year","vehicle_make","vehicle_model","vehicle_color","vehicle_license","veh_state","vehicle2_year","vehicle2_make","vehicle2_model","vehicle2_color","vehicle2_license","veh2_state");
$sql_values=array();
foreach($mystuff as $fieldname) {
/* do validation! */
$sql_values[$fieldname] = "'" . mysql_real_excape_stiring($_POST[$fieldname]) . "'";
}
$con = mysql_connect("$hostname","$username","$password");
if (!$con){
die ("Can not connect:" . mysql_error());
}
mysql_select_db("dbname",$con);
$sql = "INSERT INTO dbname (".implode(',', $mystuff).") VALUES (" . implode(',', $sql_values) . ")";
mysql_query($sql,$con);
mysql_close($con);
}
foreach($mystuff as $fieldname) {
echo "...an input field...";
}
?>
</body>
Create inputs something like :
<input type="text" name="datas[firstname]"/>
<input type="text" name="datas[lastname]"/>
You can process the data using :
<?php
$datas = $_POST['datas'];
$columns = implode(",",array_keys($datas));
//add ' since mysql use ' for strings
$values = implode("','",$datas);
$sql = "INSERT INTO dbname (".$columns.") VALUES ('".$values."')";
Hope this help.

Categories