I have this code, that gets the categories from the database and displays them on a dropdown menu. Now, what I want to do, Is when something is selected and the button isset, get the ID of that category (table: categories ,row category_id) then submit it into (table: posts ,row category_id). I don't know how to get the ID of the category that was selected in the dropdown. Thanks.
$db variable is the database connection.
This is what I've got so far. This is the submission of the data to the database:
include('../includes/db_connect.php');
if(isset($_POST['submit'])){
$newTitle = $_POST['newTitle'];
$newPost = $_POST['newPost'];
$newCategory = $_POST['newCategory'];
$my_date = date("Y-m-d H:i:s");
if(!empty($newPost))
if(!empty($newTitle)){
$sql="INSERT INTO posts (title, body, category_id)
VALUES('$newTitle', '$newPost', '$newCategory')";
$query = $db->query($sql);
if($query){
echo "Post entered to database";
}else{
echo "Error Submitting the data";
}
}
}
This is the select:
<textarea name="newPost" cols="176" rows="25"/></textarea><br>
<select name=""="newCategory" id="newCategory">
<option value="0">Select category</option>
<?php
$result = mysqli_query($db, "SELECT * FROM categories");
if ( $result ) {
while( $row = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {
echo '<option value="' . $row['category'] . '">' . $row['category'] . '</option>';
}
} else {
echo 'Couldn\'t fetch Categories from MySQL.';
}
?>
Ps - I know this is easily injectable, you don't need to tell me, Just answer the question please :)
You mostly likely just need to change this line, and have the value be the category primary key like id or whatever it is called.
echo "<option value='{$row['id']}'>{$row['category']}</option>";
Otherwise after submit you would have to run a mysql query to find the id by searching where category='$newCategory'
Related
Update: I’m now getting an error telling me that roomID is null and this is why it’s not going into the database. Can you see why it would be null when it should be the option that the user selects in the select box?
I'm working on a hotel booking system as an exercise. I am trying to make a form that will insert a new booking into the database. I have the customer and room IDS in the mySQL database and I have put them into HTML select boxes for the user to select an option.
This works fine until I try to save the new booking to the database. I don't get any errors and it tells me the booking has been saved on my page but if I go into the database it hasn't been saved. I have tried inserting the customerID and roomID values from text boxes so just typing it in instead of the drop down menu and that inserts into the database just fine.
I'm pretty sure the problem is something to do with getting the value out of the select box and into the POST variable but I'm not 100% sure. I've only been coding for 6 months so I don't really know what I'm doing! I've tried to figure it out by looking at other examples on here but nothing seems to work.
Here's my code:
Getting the data to fill the select boxes:
//Locate room names
$query = $query = 'SELECT `roomID` FROM `room`';
$result2 = mysqli_query($DBC,$query);
$rowcount = mysqli_num_rows($result2);
if ($rowcount > 0) {
$row = mysqli_fetch_assoc($result2);}
//Locate customerIDs
$query = $query = 'SELECT `customerID` FROM `customer`';
$result = mysqli_query($DBC,$query);
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
$row = mysqli_fetch_assoc($result);}
Creating Select boxes:
<form method="POST" action="newbooking.php">
<p>
<label for="customerID">Customer ID: </label>
<?php
echo "<select name='customerID'id='customerID' input type='number'>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='customerIDselect'>" . $row['customerID'] . "</option>";
//customerID
$customerID = cleanInput($_POST['customerIDselect']);
}
echo "</select>";
?>
</p>
<p>
<label for="rooms">Room (name, type, beds): </label>
<?php
echo "<select name='roomID'id='roomID' input type='number'>";
// output data of each row
while($row = $result2->fetch_assoc()) {
echo "<option value='roomIDselect'>" . $row['roomID'] . "</option>";
//roomID
$roomID = cleanInput($_POST['roomIDselect']);
}
echo "</select>";
?>
</p>
Inserting data into database:
//save the customer data if the error flag is still clear
if ($error == 0) {
$query = 'INSERT INTO `bookings` (`customerID`,`roomID`,`checkin`,`checkout`, `extras`) VALUES (?,?,?,?,?)';
$stmt = mysqli_prepare($DBC,$query); //prepare the query
mysqli_stmt_bind_param($stmt,'sssss', $customerID, $roomID, $checkin, $checkout, $extras);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo "<h2>booking saved</h2>";
} else {
echo "<h2>$msg</h2>".PHP_EOL;
}
I'm running the following queries to retrieve info from the timesheetlogin table.
$clientlist = db_select("SELECT * FROM timesheetlogin WHERE type='client' ORDER BY company DESC");
$candlist = db_select("SELECT * FROM timesheetlogin WHERE type='cand' ORDER BY name DESC");
This info is displayed in a form on the front-end.
<select name="client" id="client">
<?php
foreach($clientlist as $key => $value) {
$company = $clientlist[$key]["company"];
$name = " (" . $clientlist[$key]["name"] . ")";
echo '<option value="'. $company .'">'. $company . $name .' </option>';
$clientid = $clientlist[$key]["id"];
}
?>
</select><br />
So the form has lots of blank fields that I haven't shown, with just the client and candidate name being chosen from a dropdown.
Finally I'd like to insert the entry to the database:
if (isset($_POST['submit'])) {
$clientid = db_quote($_POST['client']);
$candid = db_quote($_POST['cand']);
Here is the SQL
db_query("INSERT INTO timesheets (clientid, candid, weekending, department, orderno, basicpay, basiccharge, otpay, otcharge, ot2pay, ot2charge, status, hue, huc) VALUES ('$client', '$cand', '$week_ending', '$department', '$order_no', '$basic_pay', '$basic_charge', '$ot_pay', '$ot_charge', '$ot2_pay', '$ot2_charge', '$status', '$hue', '$huc')");
The problem I have is I need to pass the id's associated with $_POST['client'] and $_POST['cand'] NOT the strings that are currently in the option fields.
My initial thoughts are to do something like this to check the 'client' field and query the database to get the value of the id:
if (isset($_POST['client'])) {
//code
}
That seems messy though. I have already queried the db and looped through the $clientlist array, so the ids are available in that loop. Is there a way to assign the $clientid variable based on what the user chooses from the select box?
Thanks
You can put ids like this :
$clientid = $clientlist[$key]["id"];
echo '<option value="'.$clientid.'">'. $company . $name .' </option>';
I would like to create a multi-select drop down list of countries in my form which lets users choose more than one country and also provides the ability to remove the item they selected, if needed.
I could create a drop down list which extracts the name of the countries from a mysql table, but it lets users only select one country. I searched a lot for multi-select drop down but none of the samples that I have found get data from mysql. They had only a few options which could easily write with option value like How to access the values selected in the multiselect dropdown list in PHP?
This is my code through which only one item can be selected:
<?php
mysql_connect('localhost', 'root', 'password');
mysql_select_db('imdb');
$sql2 = "SELECT country FROM countries";
$result2 = mysql_query($sql2);
echo "<select name='country'>";
while ($row = mysql_fetch_array($result2)) {
echo "<option value='" . $row['country'] . "'>" . $row['country'] . "</option>";
}
echo "</select>";
?>
Finally, I found what I was looking for. So I share it since might be useful for those with similar question.
First, as Marc said, I had to add multiple like below:
<select name="countrylist[]" multiple="multiple">
and this is the html line that I was searching for :
<option value="<?php echo $row['country'];?>"> <?php echo $row['country'];?> </option>
where country is the name of the related field in my database.
it might be worth saying that in order to insert the result in database (e.g table name = "test", field name = "q5":
<?php
mysql_connect("hostname", "user name", "user password") or die(mysql_error());
mysql_select_db("db name") or die(mysql_error());
$q5 = implode(',', $_POST['countrylist']);
if(isset($_POST['submit']))
{
$query="INSERT INTO test (q5) values ('". $q5 ."')";
mysql_query($query) or die (mysql_error() );
}
?>
It worked for me and hope will be useful for others.
WHy is my drop down list not populating with the table data? (dropdown box is empty)
And what is used to display data upon selection of an item in that drop down - is it a "VIEW" (please do provide a study link so I can learn)
My Code
<?php
$con=mysqli_connect("localhost","root","","ismat_db");
//check connection
if(mysqli_errno($con))
{
echo "Can't Connect to mySQL:".mysqli_connect_error();
}
else
{
echo "Connected to mySQL</br>";
}
//$query = 'SELECT FirstName FROM persons';
//$result = mysqli_query($con,$query);
$query = mysqli_query($con,"SELECT 'FirstName' FROM persons");
//print_r($query);
//echo '<select name="FirstName">';
echo "<select name= 'FirstName'>";
//while($row=mysqli_fetch_array($result))
while($row=mysqli_fetch_array($query))
{
echo $row;
//echo "<option value='".$row['FirstName']."'>".'</option>';
}
echo '</select>';
?>
You had 2 errors:
I pointed the first in the comment: to print an option you must use this code:
echo "<option value='". $row['FirstName']."'>".$row['FirstName']
. '</option>';
The second is in your SQL: you are not selecting the FirstName field from the database, but a string 'FirstName' instead. That's why it is printed twice as you said. Use this SQL to get the field:
$query = mysqli_query($con,"SELECT FirstName FROM persons");
Also usually people put an id of the record and not a field, that may have possible duplicates into the value of an <option>. So, I would have used:
echo "<option value='". $row['id']."'>".$row['FirstName']
. '</option>';
selecting the id from the database together with first name.
Try this:
echo "<option value='".$row['FirstName']."'>".$row['FirstName']."</option>";
Also seems that you are having an issue with the database query. Swap your while loop with the following and see if it works
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
echo "<option value='".$row['FirstName']."'>".$row['FirstName']."</option>";
}
$result->free();
}
Am facing troubles in this code, i just want to get all data from table row if the user selected "show all" from the select drop menu.
here is the select menu !
so, this menu grab data from this table, but if he selects All, what is the suitable code to echoing in between option value :)
<b>speciality:</b> <select id="main_mav" name="speciality">
<option value="none">Select speciality:</option>
<option value=""> All specialities </option>
<?php
$result = mysql_query('SELECT speciality FROM visits') or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['speciality'].'">'.$row['speciality'].'</option>';
}
?>
</select><br />
That's the Submit form !
if ($region=="All regions" ){
$region=$_POST['""'];
}
else ( $region=$_POST['region']);
$date1 =$_POST['from_date'];
$date2 = $_POST['to_date'];
$product=$_POST['product'];
$speciality=$_POST['speciality'];
$type=$_POST['visit_type'];
sql="SELECT id, customer_name, seller_1_name, seller_2_name FROM visits Where (speciality ='$speciality') AND (visit_type ='$type') AND (product ='$product') AND (region ='$region') AND (visit_date BETWEEN '$date1' AND '$date2')";
$result=mysql_query($sql); ## This line is new.
$num=mysql_numrows($result);
$row = mysql_fetch_array($result);
What's the correct code to enter if user selected " show all in drop menu " ?!
You really need to sanitize your inputs, at least with mysql_real_escape_string!
On to your actual question: just check if $speciality is empty, and generate a different query without the (speciality ='$speciality') condition.
Since your HTML referenced 'specialties' and your PHP referenced 'regions' I'm gonna just stick with 'regions', but here's the idea.
if ($region=="All regions" ){
$sql = 'SELECT id, customer_name, seller_1_name, seller_2_name, FROM visits';
} else {
$region = mysql_real_escape_string($_POST['region']);
$date1 = mysql_real_escape_string($_POST['from_date']);
$date2 = mysql_real_escape_string($_POST['to_date']);
$product = mysql_real_escape_string($_POST['product']);
$speciality = mysql_real_escape_string($_POST['speciality']);
$type = mysql_real_escape_string($_POST['visit_type']);
$sql = "SELECT id, customer_name, seller_1_name, seller_2_name FROM visits Where (speciality ='$speciality') AND (visit_type ='$type') AND (product ='$product') AND (region ='$region') AND (visit_date BETWEEN '$date1' AND '$date2')";
}
$result = mysql_query($sql); ## This line is new.
$num = mysql_numrows($result);
$row = mysql_fetch_array($result);