I am trying to insert values input from the user in a form into my database.
I have 2 drop down lists for a blood test and then category. E.g user first selects drop down 1 'Thyroid' (Category) and then drop down 2 displays 'FT4,FT3 TSH' (blood test) etc and the user makes their selection.
Then they input the date and the value.
In my insert I need to insert into my database the user_id(established after login with session variables, bloodtest_id(from drop down 2), date, value.
I can't get my SQL query right for the insert in general and need some help please.
Drop down 2 (blood test) is in a seperate php file and I'm not sure how to tell the SQL query how to find that value to use either?
The addBlood.php is below. This is the page the form is on
<?php
session_start();
include('dbConnect.php');
$queryStr=("SELECT * FROM category");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
?>
<html>
<head>
<TITLE>Category and Test</TITLE>
<head>
<!-- Help for code to create dynamic drop downs -->
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
function getTest(val) {
$.ajax({
type: "POST",
url: "get_test.php",
data:'category_id='+val,
success: function(data){
$("#test-list").html(data);
}
});
}
function selectCategory(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
</script>
</head>
<body>
<div class="frmDronpDown">
<div class="row">
<label>Category:</label><br/>
<select name="category" id="category-list" class="demoInputBox" onChange="getTest(this.value);">
<option value="">Select Category</option>
<?php
foreach($results as $category) {
?>
<option value="<?php echo $category["category_id"]; ?>"><?php echo $category["category_name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<form action="addBlood.php" method="post">
<label>Test:</label><br/>
<select name="test" id="test-list" class="demoInputBox">
<option value="">Select Test</option>
</select>
</div>
</div>
<label>Result:</label><input class="input" name="result" type="text"><br>
<label>Date:</label><input class="input" name="date" type="date"><br>
<input class="submit" name="submit" type="submit" value="Submit">
</form>
<?php
if(isset($_POST['submit'])){
//$currentBloodTest=$test["bloodtest_id"];
$currentUser=$_SESSION["currentUserID"];
$value = $_POST['result'];
$date = $_POST['date'];
//$query = $db->prepare("INSERT INTO results (user_id, bloodtest_id,date,value)values ($currentUser,$currentBloodTest, $date , $value)");
$dbParams = array();
$query->execute($dbParams);
echo "<br><br><span>Data Inserted successfully...!!</span>";
}
?>
</body>
</html>
Below is the getTest.php which gets all the blood tests.
<?php
include('dbConnect.php');
if(!empty($_POST["category_id"])) {
$queryStr=("SELECT * FROM bloodtests WHERE category_id = '" . $_POST["category_id"] . "'");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
?>
<option value="">Select Test</option>
<?php
foreach($results as $test) {
?>
<option value="<?php echo $test["bloodtest_id"]; ?>"><?php echo $test["test_name"]; ?></option>
<?php
}
}
?>
If this is where you are having some troubles, and are unsure how to proceed:
//$query = $db->prepare("INSERT INTO results (user_id, bloodtest_id,date,value)
// VALUES ($currentUser,$currentBloodTest, $date , $value)");
$dbParams = array();
$query->execute($dbParams);
Then this may help you out (you were very close):
$currentUser = $_SESSION["currentUserID"];
$currentBloodTest = $_POST['test']; // name of the 'select' element
$value = $_POST['result'];
$date = $_POST['date'];
$query = $db->prepare("INSERT INTO results (user_id, bloodtest_id, date, value)
VALUES (?, ?, ?, ?)");
$query->execute( array($currentUser, $currentBloodTest, $date, $value) );
Also, this part you have in the ajax lookup:
$queryStr=("SELECT * FROM bloodtests WHERE category_id = '" . $_POST["category_id"] . "'");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
Really should be written as:
$queryStr = "SELECT * FROM bloodtests WHERE category_id = ?";
$results = $db->prepare($queryStr);
$results->execute( array($_POST["category_id"]) );
Related
I am trying to create a form for the admin of an e-commerce site and the admin should be able to create a category and add new products.
I have two tables in my database from where I want to populate the dropdown list. I want the second dropdown to populate as I select the first drop-down value but I have to do it without the submit button.
This is the code for the form with two drop-downs:-
<form method="post" action="add_category.php">
<h4>Choose the root level:</h4>
<select name="rootLevel">
<?php
$conn = mysqli_connect("localhost","root","","store")
or die("Error in Connection on add_category");
$query = "SELECT * FROM root_category";
$result = mysqli_query($conn,$query) or die("Query failed add_category");
$id=1;
//echo $id;
//echo "Hello";
while($row = mysqli_fetch_assoc($result)){
global $id;
//echo "<h1>$id</h1>";
$id = $row['id'];
echo "<option name='rootLevel' value=$id>".$row['Name']."</option>";
//echo "<option>$id</option>";
}
?>
</select>
<br><br>
<h4>Choose the Level 1 Category:</h4>
<select name="level1">
<?php
global $id;
//echo "<option>".$_POST['rootLevel']."</option>";
$query_level1 = "Select * from level1_category Where P_id = $id";
$result1 = mysqli_query($conn,$query_level1) or die("Query failed level 1");
while($row = mysqli_fetch_assoc($result1)){
$id1 = $row['P_id'];
echo "<option name='level1' value=$id1>".$row['Name']."</option>";
}
?>
</select>
I have successfully populated the first drop-down and now I want to fetch the $id in 'resultValue' without the submit button.
You cant do this only with PHP. You have to use jquery OR Ajax to do this.
Please check this example page . This may help you
https://www.tutorialrepublic.com/faq/populate-state-dropdown-based-on-selection-in-country-dropdown-using-jquery.php
OR
https://www.codexworld.com/dynamic-dependent-select-box-using-jquery-ajax-php/
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajax({
type: "POST",
url: "states.php",
data: { country : selectedCountry }
}).done(function(data){
$("#states").html(data);
});
});
});
</script>
</head>
<body>
<div class="form-group">
<label for="country" class="input__label">Country</label>
<select id="country" onchange="states(this.value);" name="country" class="country form-control login_text_field_bg input-style">
<option selected>Choose...</option>
<?php
$sql= $cnn->prepare("SELECT key_iso_code FROM country");
$sql->execute();
while($i = $sql-> fetch($cnn::FETCH_ASSOC)){
extract($i);
?>
<option><?php echo $key_iso_code ?></option>
<?php
}
?>
</select>
</div>
<div class="form-group col-md-4">
<label for="inputState" class="input__label">State/Province</label>
<select id="states" name="state" class="form-control input-style">
<option selected>Choose...</option>
</select>
</div>
</body>
<?php
include("PDOConnection.php");
if(isset($_POST["country"])){
// Capture selected country
$country = $_POST["country"];
// Display city dropdown based on country name
if($country !== 'Shoose...'){
$sql= $cnn->prepare("SELECT state.key_name FROM country INNER JOIN state ON country.key_id = state.key_country_id WHERE country.key_iso_code like '$country'");
$sql->execute();
while($i = $sql-> fetch($cnn::FETCH_ASSOC)){
extract($i);
echo "<option>". $key_name . "</option>";
}
}
}
?>
I am learning PHP, Jquery, Ajax and other web dev languages and have been stuck on this problem for hours on end.
I have two drop-down boxes:
One displaying a list of countries (via a database query)
One displaying a list of cities related to the country chosen (also via a database query)
Anyway, I want to be able to retrieve the text of both menu boxes and use them in further database queries in a text box on the same page at the click of a button but with no reloading of the page involved.
I have used JQuery and Ajax for the dynamic menu so I have some idea of what is required for this task. Here is the code for the page in question:
<body>
<div class = "country">
<label>Select a Country: </label>
<select name="country" onchange="getId(this.value);">
<option value = "">Select Country</option>
<?php
$query = "SELECT DISTINCT(Country) AS Country FROM Locations ORDER BY Country ASC;";
$results = mysqli_query($con, $query);
foreach ($results as $country) {
?>
<option value = "<?php echo $country['Country']; ?>"><?php echo
$country['Country'] ?></option>
<?php
}
?>
</select>
</div>
</br>
<div class="city">
<label>Select a City: </label>
<select name="city" id="cityList">
<option value="">Select a city</option>
</select>
</div>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
function getId(value){
$.ajax({
type: "POST",
url: "getdata.php",
data: "Country="+value,
success: function(data){
$("#cityList").html(data);
}
});
}
</script>
<button id="button">Go</button>
document.getElementById("button").onclick = function(){
document.getElementById("textbox").innerHTML = "<?php $query = mysqli_query($con, "SELECT * FROM Locations WHERE Country='dropdown text' AND City='dropdown text'");
while($results = mysqli_fetch_array($query)){
echo "Name: " . "$results['City']" . "is in" . "$results['Country']" "</option>";
}
?>";
}
</script>
</body>
The PHP file I have been working on so far is incomplete as I am unsure on how to echo the result, since I want it to eventually end up in the text box on the main page. My PHP is as follows:
<?php
include_once "connection.php";
if(!empty($_POST['Country'])||($_POST['City'])){
$country = $_POST['Country'];
$city = "SELECT * FROM Locations WHERE Country = '$Country' AND City = '$city'";
$results = mysqli_query($con, $query);
foreach ($results as $city) {
?>
<option value = "<?php echo $city['Country']; ?>"><?php echo $city['City'] ?></option>
<?php
}
}
?>
Any suggestions or advice would be greatly appreciated.
<?php
include_once "connection.php";
if(!empty($_POST['Country'])){
$country = $_POST['Country'];
$city = "SELECT * FROM Locations WHERE Country = '$Country' ";
$results = mysqli_query($con, $query);
foreach ($results as $city) {
?>
<option value = "<?php echo $city['City']; ?>"><?php echo $city['City'] ?></option>
<?php
}
}
?>
You are posting just 'Country' and have to get just 'country' from post. the city does not come from post.
Ok so I have a database that will store song information and a star rating for each song.
I have tables
artists
genres
tracks
track_rating
in tracks i have trackID (set to autoIncrement), genreID, artistID, title
I can insert a track and that works fine the trouble is when i insert a track
I also want to insert a rating that is associated with that track
In track_rating i have rating_id(AutoInc), track_id, rating_number, total_points
The problem I am having is with the track_id. I am having trouble getting the value from the tracks table to insert it into the track_rating table.
Here is my code
add_track_form
<?php
require('includes/database.php');
$query = 'SELECT * FROM genres ORDER BY genreID';
$statement = $db->prepare($query);
$statement->execute();
$genres = $statement->fetchAll();
$statement->closeCursor();
$queryArtist = 'SELECT * FROM artists ORDER BY artistID';
$statementArtist = $db->prepare($queryArtist);
$statementArtist->execute();
$artists = $statementArtist->fetchAll();
$statementArtist->closeCursor();
?>
<!DOCTYPE html>
<html>
<!-- the head section -->
<head>
<title>MixMatcher</title>
<link rel="stylesheet" type="text/css" href="css/main.css">
</head>
<!-- the body section -->
<body>
<header><h1>Tracks</h1></header>
<main>
<h1>Add Track</h1>
<form action="add_track.php" method="post" id="add_track_form">
<label>genre:</label>
<select name="genre_id">
<?php foreach ($genres as $genres) : ?>
<option value="<?php echo $genres['genreID']; ?>">
<?php echo $genres['genreName']; ?>
</option>
<?php endforeach; ?>
</select><br>
<label>Artist:</label>
<select name="artist_id">
<?php foreach ($artists as $artists) : ?>
<option value="<?php echo $artists['artistID']; ?>">
<?php echo $artists['artistName']; ?>
</option>
<?php endforeach; ?>
</select><br>
<label>Title:</label>
<input type="text" name="title"><br>
<label>Add Track</label>
<input type="submit" value="Add track"><br>
</form>
<p>View track List</p>
</main>
<footer>
<p>© <?php echo date("Y"); ?> MixMatcher, Inc.</p>
</footer>
</body>
</html>
add_track
<?php
// Get the track data
$genre_id = filter_input(INPUT_POST, 'genre_id', FILTER_VALIDATE_INT);
$artist_id = filter_input(INPUT_POST, 'artist_id', FILTER_VALIDATE_INT);
$title = filter_input(INPUT_POST, 'title', FILTER_SANITIZE_STRING);
// Validate inputs
if ($genre_id == null || $genre_id == false ||
$artist_id == null || $title == null ) {
$error = "Invalid track data. Check all fields and try again.";
include('database_error.php');
} else {
require_once('includes/database.php');
// Add the track to the database
$query = 'INSERT INTO tracks (genreID, artistID, title)
VALUES (:genre_id, :artist_id, :title)';
$statement = $db->prepare($query);
$statement->bindValue(':genre_id', $genre_id);
$statement->bindValue(':artist_id', $artist_id);
$statement->bindValue(':title', $title);
$statement->execute();
$statement->closeCursor();
$query1 = 'SELECT * FROM tracks ORDER BY trackID';
$statement1 = $db->prepare($query1);
$statement1->execute();
$tracks = $statement->fetchAll();
$statement->closeCursor();
//Problem Here
$trackID = $tracks['trackID'];
$queryRating = 'INSERT INTO track_rating (track_id, rating_number, total_points)
VALUES (:track_id, :rating_number, :total_points)';
$statementRating = $db->prepare($queryRating);
$statementRating->bindValue(':track_id', $trackID);
$statementRating->bindValue(':rating_number', 0);
$statementRating->bindValue(':total_points', 0);
$statementRating->execute();
$statementRating->closeCursor();
// Display the track List page
include('index.php');
}
?>
$query = 'INSERT INTO tracks (genreID, artistID, title)
VALUES (:genre_id, :artist_id, :title)';
$statement = $db->prepare($query);
$statement->bindValue(':genre_id', $genre_id);
$statement->bindValue(':artist_id', $artist_id);
$statement->bindValue(':title', $title);
$statement->execute();
$lastestID = $statement->inser_id();
$statement->closeCursor();
from ur code i added up the $lastestID = $statement->inser_id(); thats the code for getting the lastest id if ur using prepared stament then us the variable $lastestID in inserting the track_ID in ur track_rating table..
I have a main MySQL table called restaurants which holds all details for each restaurant - RestaurantID, RestaurantName, Address, Town, County etc.
I am creating a Review and ratings form in PHP to allow my users to review each of the restaurants. I have created 2 dropdown menus one which the user will select the County and the second I hope to populate with RestaurantName of those in that County.
Can anyone spot where I am going wrong? My first dropdown populates without any issues, although the second dropdown is blank?
I've added all my code so far for this, anything else that you think would be useful let me know.
leave.php
<?php
include_once "settings.php"
?>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<body>
<div class="County">
<label>County</label>
<select name = "County" onchange="getId(this.value);">
<option value ="">Select County </option>
<?php
$query = "SELECT DISTINCT County FROM restaurants";
$results = mysqli_query($con, $query);
foreach ($results as $restaurants) {
?>
<option value ="<?php echo $restaurants['County']; ?>"><?php echo $restaurants["County"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="RestName">
<label>Restaurant</label>
<select name = "Restaurant" id="RestList">
<option value ="">Select Restaurant </option>
<option value="" >
<?php
include_once "settings.php";
if (!empty($_POST["RestaurantID"])) {
$RestaurantID = $_POST["RestaurantID"];
$query = "SELECT * FROM restaurants WHERE RestaurantID = $RestaurantID";
$results = mysqli_query($con, $query);
foreach ($results as $County) {
?>
<option value="<?php echo $restaurants["RestaurantID"]; ?>"><?php echo $restaurants["RestaurantName"]; ?>"></option>
<?php
}
}
?>
</select>
</div>
<script>
function getId(val){
$.ajax({
type: "POST",
url:"getdata.php",
data: "RestaurantID="+val,
success: function(data){
$("#RestList").html(data);
}
});
}
</script>
</body>
</html>
getdata.php
<?php
include_once "settings.php";
if (!empty($_POST["RestaurantID"])) {
$RestaurantID = $_POST["RestaurantID"];
$query = "SELECT * FROM restaurants WHERE RestaurantID = $RestaurantID";
$results =
($con, $query);
foreach ($results as $restaurants) {
?>
<option value="<?php echo $restaurants['RestaurantID']; ?>"><?php echo $restaurants["RestaurantName"]; ?>"></option>
<?php
}
}
?>
In this line:
<select name="Restaurant" id="RestList" </select>
You don't actually close the "<select>" tag...
There are 02 tables called item and customer.
item(item_id, item_name)
customer(cus_id, iid, cus_name)
I just tried to store item_id from item to the iid in the customer.
but it always showing null values.
My database is item_sales.
Here is my PHP code
<html>
<title></title>
<head></head>
<body>
<?php
$hostname = "localhost";
$database = "item_sales";
$username = "root";
$password = "";
$con = mysql_pconnect($hostname, $username, $password);
error_reporting(0);
?>
<form action="index.php" method="post" enctype="multipart/form-data">
<p>Customer Name : <input type="text" name="cus_name" /><br/><br/> </p>
<p>Select an Item:
<select name="iid">
<?php
$sql = mysql_query("SELECT * FROM item");
mysql_select_db($database,$con);
while($sqlv = mysql_fetch_array($sql))
{ ?>
<option id="<?php echo $sqlv['item_id']; ?>"><?php echo $sqlv['item_name']; ?></option>
<?php } ?>
</select>
</p>
<?php
if(isset($_POST['submit']))
{
$sql2 = "SELECT * FROM item WHERE iid='%item_id%'";
mysql_select_db($database,$con);
$mydata = mysql_query($sql2);
$cus_name = $_POST['cus_name'];
$sql3 = "INSERT INTO customer (cus_id, iid, cus_name) VALUES ('', '$_POST[iid]', '$cus_name')";
mysql_query($sql3);
}
?>
<input type="submit" name="submit" value="Add Sale" />
</form>
</body>
</html>
The reason it is not working is that you are attempting to save the iid select into the iid field, and I'm guessing the iid field in customer is a numeric type field, like INT - using the POST variable like this, you are going to be saving the text of the SELECT rather than the val.
What you need to do to fix this particular problem is set a "value" on each of the select options. You've set an ID but thats no real help here.
<select name="iid">
<?php
$sql = mysql_query("SELECT * FROM item");
mysql_select_db($database,$con);
while($sqlv = mysql_fetch_array($sql))
{ ?>
<option value="<?php echo $sqlv['item_id']; ?>"><?php echo $sqlv['item_name']; ?></option>
<?php } ?>
</select>
This is besides the point your code is very dangerous. I would recommend you do not use the original mysql functions as, 1) they don't offer any real protection from malicious users, and 2) they will be removed from PHP support very soon.
See this SO article on how to replace the mysql functionality from your PHP code : How can I prevent SQL injection in PHP?
That article also might help you understand the dangers your code offers.
The correct code is following :
<html>
<title></title>
<head></head>
<body>
<?php
$hostname = "localhost";
$database = "item_sales";
$username = "root";
$password = "";
$con = mysql_pconnect($hostname, $username, $password);
error_reporting(0);
?>
<form action="index.php" method="post" enctype="multipart/form-data">
<p>Customer Name : <input type="text" name="cus_name" /><br/><br/> </p>
<p>Select an Item:
<select name="iid">
<?php
$sql = mysql_query("SELECT * FROM item");
mysql_select_db($database,$con);
while($sqlv = mysql_fetch_array($sql))
{ ?>
<option value="<?php echo $sqlv['item_id']; ?>"><?php echo $sqlv['item_name']; ?></option>
<?php } ?>
</select>
</p>
<?php
if(isset($_POST['submit']))
{
$sql2 = "SELECT * FROM item";
mysql_select_db($database,$con);
$mydata = mysql_query($sql2);
$cus_name = $_POST['cus_name'];
$iid = $_GET['item_id'];
$sql3 = "INSERT INTO customer (cus_id, iid, cus_name) VALUES ('', '$_POST[iid]', '$cus_name')";
mysql_query($sql3);
}
?>
<input type="submit" name="submit" value="Add Sale" />
</form>
</body>
</html>