Post query from php to sqlite database through button - php

So I have the following webpage containing html and php. Within the page I have a checkbox which populates its options from a table within the database. and another multi-select checkbox that gets populated from a different table. The first checkbox is related to products and the second is store location which can have multiple locations.
I'm trying to setup a submit button after something is selected from both it posts to the database within the table to give store location details for each product.
table schema:
table name: products
id, name, StoreLocation
table name: stores
id, name
how I am using the product checkbox
<select name="Pname">
<?php
$resultSet = $db->query('SELECT name FROM products');
while($row = $resultSet->fetchArray()){
echo"<option value=\"productN\">" . $row['name'] . "</option>";
}
?>
</select>
store location checkbox
<select name="Sname", id="Sname" multiple>
<?php
$resultSet = $db->query('SELECT name FROM stores');
while($row = $resultSet->fetchArray()){
echo"<option value=\"storeN\">" . $row['name'] . "</option>";
}
?>
</select>
This is what I was attempting but it did not work
<form action="index.php" method="post">
<input type="submit" name="myButton" value="Submit"/>
<?php
$query = "INSERT INTO products (Store Location) VALUES ($row)";
?>
</form>
Is it a problem with my setup for the sql query? When I try to use the submit button nothing is inserted to the database. I've tried sample queries and those did not work either.

First: all options have the same value. You should be using the id of the record, so you can identify it, when the FORM is posted.
echo"<option value=\"productN\">" . $row['name'] . "</option>";
Second: This makes no sense
<form action="index.php" method="post">
<input type="submit" name="myButton" value="Submit"/>
<?php
$query = "INSERT INTO products (Store Location) VALUES ($row)";
?>
</form>
If you want to react on a POST request (FORM submit) you'll receive the data of the FORM in PHP via $_POST. In this array, check for the name of your Submit button. For beginners it's helpful to dump the POST array, to see what it contains: var_dump($_POST);
Lastly: Do never pass data directly into SQL queries, use prepared statements.
Consider to make some tutorials about Webdevelopment with PHP.

Related

How to use data when submit button is clicked for next sql query

I am trying to create an html form where i have a dropdown menu populated with data from stations table. I am able to select a station and then i want to use this station name when a button is clicked to display a table with related data. But i don't understand how i can use selected station to create another query when submit button is clicked. Below is my code:
<form method="post">
<label>Choose a station:</label>
<select name="owner">
<?php
$sql = mysqli_query($conn, "SELECT name FROM stations");
while ($row = $sql->fetch_assoc()){
?>
<option value="owner1"><?php echo $row['name']; ?></option>
<?php
}
?>
</select>
<br><br>
<input type="submit" value="Submit">
</form>
i think onclick must be used but i don't understand what would be posted that i can use for new sql query.
When you click submit button browser send form via POST method to the same page and reload it. So you can capture the value selected in the form with this PHP code:
If (isset($_POST['owner'])) {
// mysqli query where the selected value is $_POST['owner']
}

Database isn't receiving values from form using php

Im trying to send form data to my sql database but the database isn't receiving any of my values. The name of my database is taxibooking and table name is bookings.
I tried separating the php code in another file and using action on form to access the php code. on clicking submit I was redirected to a blank page with my php file name.
<form method="POST" action="">
Name of customer:<input type="text" name="fname"><br><br>
Enter pickup address:<textarea name="padd" rows="5" cols="10"></textarea><br><br>
Enter destination address:<textarea name="dadd" rows="5" cols="10"></textarea><br><br>
Select Taxi type:<select name="taxi"><option value="Viennese Fiaker">The Viennese Fiaker</option><option value="Indian Auto Rickshaw">Indian Auto Rickshaw</option><option value="Little Yellow">Little Yellow</option><option value="Mumbai Taxi Fiat">Mumbai Taxi Fiat</option><option value="Tricycles">Tricycles</option><option value="Water Taxi">Water Taxi</option><option value="Impeccable Taxi">Impeccable Taxi</option><option value="Red Taxi">Red Taxi</option></select><br><br>
<input type="submit" value="submit" name="sub">
</form>
<?php
$con=mysqli_connect("localhost","root","","taxibooking");
if(isset($_POST['sub']))
{
$n=$_POST['fname'];
$p=$_POST['padd'];
$d=$_POST['dadd'];
$type=$_POST['taxi'];
$sql="insert into bookings(name,pickup,destination,type) values ('$n','$p','$d','$type')";
mysqli_query($con,$sql);
}
?>
Try to debug and put query on if condition
if(mysqli_query($con,$sql)){
echo'done';
}else{
echo "error".$sql."</br>" . mysqli_error($con);
}
Here's how to add parameters on your insert script.
$sql="insert into bookings(name,pickup,destination,type) values ('".$n."','".$p."','".$d."','".$type."')";
I made a new database with a different name with the same table name and properties and now it sort of mysteriously works now. No changes done to the code.

Unable to post a value selected from db in a drop down box

I had spent some time trying to get the drop down box working correctly, getting the values of department and location to populate from the DB. This is working fine and I have added additionally date fields so a customer can select records for a specific period, location and department. When I action the form running departmentReport.php the page returns blank even when trying to echo each value as seen below.
<form id="departmentReport" action="departmentReport.php" method="get" onsubmit="#">
<fieldset id="departmentReport">
<h3>Department Report</h3>
<br>
<?php
include 'includes/DbCon.php';
$sql = "select department_name from departments";
echo"<select name = 'departments' value=''>Department Name</option>";
foreach ($conn->query($sql) as $row){
echo "<option value=$row[department_name]>$row[department_name]</option>";}
echo "</select>";
?>
<br></br>
<?php
include 'includes/DbCon.php';
$sql = "select `location_name` from `location`";
echo "<select name = 'location' value=''>Location Name</option>";
foreach ($conn->query($sql) as $row){
echo "<option value=$row[location_name]>$row[location_name]</option>";}
echo "</select>";
?>
<br></br><br>
<label for="date">Date From<br></label>
<input id="date1" type="date" name="dateF"
autofocus="true"/>
<br>
<br>
<label for="date">Date To<br></label>
<input id="date2" type="date" name="date2"
autofocus="true"/>
<br>
<br>
<input type="submit" class="button" value="Submit">
On Submit departmentReport.php is actioned
<?php
include "../includes/dbCon.php"; //* CONNECTION TO DATABASE
$department = mysqli_real_escape_string($conn, $_POST['departments']); //* CLEAN DATA, THIS DELETES ANY SPECIAL CHARACTERS THAT CAN BE USED FOR MALICIOUS CODE
$location = mysqli_real_escape_string($conn, $_POST['location']); //* CLEAN DATA, THIS DELETES ANY SPECIAL CHARACTERS THAT CAN BE USED FOR MALICIOUS CODE
$date1 = mysqli_real_escape_string($conn, $_POST['date1']); //* CLEAN DATA, THIS DELETES ANY SPECIAL CHARACTERS THAT CAN BE USED FOR MALICIOUS CODE
$date2 = mysqli_real_escape_string($conn, $_POST['date2']); //* CLEAN DATA, THIS DELETES ANY SPECIAL CHARACTERS THAT CAN BE USED FOR MALICIOUS CODE
echo "$department";
echo "$location";
echo "$date1";
echo "$date2";
This brings the results below..
However when adjusting post to get I see the values I selected
http://localhost:8888/departmentReport.php?departments=Marketing&location=London&dateFrom=02%2F01%2F2017
Im unsure why I cannot see the values when echoing them!
Any assistance will be much appreciated.
Your variable when retrieving the post data is wrong
Select department html code:
<select name = departments value=''>Department Name</option>
In the select form, the name is "departments", but when you retrieve them in the PHP, it is:
$_POST['departmant_name']
Which is wrong input variable name. It should be:
$_POST['departments']
Also, please put quotes mark on the select name
<select name = 'departments' value=''>Department Name</option>
All other variable also wrong.
Looks like you entered the database column name, not the form input name.
Edit:
I also noticed that in your form, the form "method" is set to "GET" while your PHP code is using "POST"

Inputting multiple values in database from HTML form using PHP

I'm trying to add multiple values into a database using PHP from an HTML. However, I can't just refer to the name attribute of the HTML form because each field in the form is generated by a PHP script. I've tried Googling around, but since I don't exactly know what I'm looking for, my search has been futile.
Here's the bit of code that I use to generate the HTML form:
<form action="input_points.php" method="post">
<?php
while($row = mysql_fetch_array($result)) {
echo $row['Name'] . ' <input type="text" name="userpoints">';
}
?>
<button type="submit" name="add_points">Add Points </button>
</form>
I don't know what names are currently in the directory so I need this piece of php to determine what names are in the database. Afterwards, I want to have a bunch of boxes for people to input points (hence the form). I'm having trouble figuring out how to link the particular text box with the user.
For example, if I have a text box for Bob, how would I link up the input text field that contains the number of points Bob earns with Bob's entry in the database?
I know you can do this with regular form fields:
$userpoints = $_POST['userpoints'];
UPDATE members SET points = $userpoints where $user = "Bob";
But since I have multiple users, how do I link up the correct database entry with the right user? Also, how would I determine which boxes are empty and which boxes are updated with a value?
If you want to update multiple filed then are using array
Please changes some code
<form action="input_points.php" method="post">
<?php
$userCount=mysql_num_rows($result);
echo '<input type="hidden" name="userCount" value="' .$userCount. '">';
while($row = mysql_fetch_array($result)) {
echo '<input type="hidden" name="userid[]" value="' .$row['id']. '">'; //Give the uniq id
echo $row['Name'] . ' <input type="text" name="userpoints[]">';
}
?>
<button type="submit" name="add_points">Add Points </button>
</form>
PHP Code -
$userCount = $_POST['userCount'];
for($i=1; $i=$userCount; $i++){
$userpoints = $_POST['userpoints'];
$userid = $_POST['userid'];
//UPDATE members SET points = $userpoints where $user = $userid;
//YOUR CODE HERE
}
The update you're trying to do is not safe unless you treat values to prevent SQL injection... but if you really want it, instead of mysql_fetch_array(), try using mysql_fetch_assoc().
Using mysql_fetch_assoc() you can extract the keys (database field names) with array_keys(). The keys will be your the name property of your form fields and the values of will be the fields' values.
Hope it helps.
You can use an array to store all the data that you need and add a hidden field that contains the missing data:
<form action="input_points.php" method="post">
<?php
for($i=0; $row = mysql_fetch_array($result); $i++ ) {
echo ' <input type="hidden" name="user[0]['name'] value ='". $row['name'] ."'">';
echo $row['Name'] . ' <input type="text" name="user[$i]['points'] ">';
}
?>
<button type="submit" name="add_points">Add Points </button>
</form>
Problem when you hit submit userpoints contain only the last value previous all values are overwritten
solution
name="userpoints"
must be different each time why not you define it in database and then fetch it just like you fetch $row['Name']?

List option values fail to insert into the database

I've created a php form to insert values into a database.
One of my form options is a dynamic list populated with fields from another table.
I first created the form without the dynamic option, and all data inserted just fine (and still does).
Now I'm attempting to include the code below, and while it displays the option values properly, the value fails to insert. Any advice?
<?php
/*
* LIST ALL CATEGORIES
****************************************/
include('../dbconnection.php');
$query = 'SELECT category_id, category_name FROM ingredient_categories';
$result = mysql_query($query);
echo '<select>';
while ($ingredientCategoryOption = mysql_fetch_array($result)) {
echo '<option value="'.$ingredientCategoryOption[category_id].'">'.$ingredientCategoryOption[category_name].'</option>';
}
echo '</select>';
?>
I had created something similar yesterday. The $polls array is passed to the view in CodeIgniter in the $this->load->view('poll.php', $data['polls']), while you do it in the page itself. However, you can have the general idea.
<FORM id="formPoll" class="question" name="createpoll" action="<?php echo base_url()?>index.php/poll/selectOption/" method="POST">
<select name="poll_list">
<?php
foreach($polls as $poll){
echo "<option name='poll_table'>$poll->name</option>";
}
?>
</select>
<div id="input">
Poll name: <input type="text" name="name"></input>
Title: <input type="text" name="title"></input>
</div>
<div id="options">
Option: <input type="text" name="option"></input>
</div>
<input type="submit"></input>
</FORM>
Some ideas:
Check if $results is not empty before using it
Give your <select> form a name, as I showed above
Check if $ingredientCategoryOption is not null or is something returned.
Check your database connection

Categories