pdo select column from $_POST - php

In my database I have a table called user_items where I store each username and how many of each item they have. I have 1 column for each and every time the user can buy and a column for their username. Now I also have an HTML form and want to do a PDO select from the HTML select.
<?php
if (isset($_POST['Detach'])) {
// Here we get the info about the pokemon
$teamget = $db->prepare("select * from user_items where username = :name");
$teamget->execute(array(':name' => $_SESSION['username']));
$getteam = $teamget->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator
echo $getteam -> $_POST['item'];
echo "working";
}
?>
<form method="post" action="">
<select name="item" id="item" style="width:150px;padding-left:5px;">
<option value=""></option>
<option>poke_ball</option>
<option>great_ball</option>
<option>ultra_ball</option>
<option> aster_ball</option>
<option>potion</option>
<option>super_potion</option>
<option>hyper_potion</option>
<option>burn_heal</option>
<option>parlyz_heal</option>
<option>antidote</option>
<option>awakening</option>
<option>ice_heal</option>
<option>dawn_stone</option>
<option>dusk_stone</option>
<option>fire_stone</option>
<option>leaf_stone</option>
<option>moon_stone</option>
<option>oval_stone</option>
<option>shiny_stone</option>
<option>sun_stone</option>
<option>thunder_stone</option>
<option>water_stone</option>
<option>exp_share</option>
</select>
<select name="Detach" id="Detach" style="width:150px;padding-left:5px;">
<option value=""></option>
<option>Attach To Pokemon 1</option>
<option> Attach To Pokemon 2</option>
<option> Attach To Pokemon 3</option>
<option> Attach To Pokemon 4</option>
<option> Attach To Pokemon 5</option>
<option> Attach To Pokemon 6</option>
?>
</select>
<br/>
<br/>
<br/>
<br/>
<button name="submit" type="submit" id="Submit_Butt">Detach Item</button>
<p> </p>
<p> </p>
</form>
The first select is the name of each column. What I'm trying to do is select the value of the column where $_POST = the column
Would this work ?
$teamget = $db->prepare("select '".$_POST['item']."' from user_items where username = :name");
$teamget->execute(array(':name' => $_SESSION['username']));
$getteam = $teamget->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator
echo $getteam ;

Your table organized wrong way. What it have to be:
username item quantity
and now you can query it this way
$sql ="select quantity from user_items where username = ? and item = ?";
$stmt = $db->prepare($sql);
$stmt->execute(array($_SESSION['username'], $_POST['item']));
$item = $stmt->fetchColumn();
echo $item;
it's also ought to be user_id and item_id in this table instead of actual names, but it is already too complex for you

Related

How to auto selected save value from database in to select HTML tag

How to auto select the save value fetched from database in to select HTML tag.
I have a list of rooms with Hotel name , room type , facilities , descriptions in a table. i want to edit that record . when i click on edit button it fetch room_id to edit row accordingly, all other values successfully auto fetched in textboxes except values in select tag.
Here is my code to fetch values from database and echo to corresponding textboxes , except select box . i would like to auto select value in select box.
$query = "SELECT * from room where room_id = '$id'";
$result = mysqli_query($connection, $query) or die ( mysqli_error());
while($row=mysqli_fetch_assoc($result))
{
$room_id=$row['room_id'];
$room_type_id=$row['room_type_id'];
$facilities = $row['facilities'];
$long_description=$row['long_description'];
}
?>
<form action="Edit_Room_Script.php" method="post" enctype="multipart/form-data">
<label class="form-label">Hotel Name</label>
<select class="form-control" name="name" id="name">
<?php
$sel_cus = "select hotel_name from hotels ";
$res_cus = mysqli_query($connection, $sel_cus);
while ($row = mysqli_fetch_array($res_cus)) {?>
<option value="<?php echo $row['hotel_id'];?>"><?php echo $row['hotel_name'];?></option><?php}?>
</select>
<label class="form-label">Room Type</label>
<select class="form-control" name="room_type" id="room_type">
<?php
$sel_cus = "select Room_Type_Id,Room_Type_Name from room_type ";
$res_cus = mysqli_query($connection, $sel_cus);
while ($row = mysqli_fetch_array($res_cus)) {?>
<option value="<?php echo $row['Room_Type_Id'];?>">
<?php echo $row['Room_Type_Name'];?></option>
<?php
}
?>
</select>
<label class="form-label">Facilities</label>
<input class="form-control" type="text" id="facilities" value="<?php echo $facilities;?>" name="facilities" autocomplete="Off" required >
<button class="btn btn-success btn-cons" type="submit" name="update" id="update"> Update Room</button>
</form>
i have a row in my html table is like below
Sr Hotel Name Roomtype Facility Action
1 Serena Super ABC Edit
When i click to edit button it take me to edit from where facility value successfully auto fetched from database and set in text box but hotel name and room type is not set. In select tag for hotel name and room type it populates all the hotel name and room type except serena and super how could i achieve this Please guide with some code.
Thank you
Some modifications:
1) Get $hotel_id
2) To show <select> element selected, you need to add selected="selected" attribute in your <option> tag.
If you have a drop down HTML:
<select class="form-control" name="room_type" id="room_type">
<option value="1">Villa</option>
<option value="2">Terrace</option>
<option value="3" selected="selected">Gallery</option>
<option value="4">Delux</option>
</select>
Drop down will show Gallery selected.
In your case, you can show it by:
<?php
$sel_cus = "select Room_Type_Id,Room_Type_Name from room_type ";
$res_cus = mysqli_query($connection, $sel_cus);
while ($row = mysqli_fetch_array($res_cus)) {?>
<option value="<?php echo $row['Room_Type_Id'];?>"
<?php if ($room_type_id == $row['Room_Type_Id']) { echo 'selected="selected"';}?>>
<?php echo $row['Room_Type_Name'];?></option>
<?php
}
?>
3) Also, first fetch the arrays from database and then loop over them in the <select> element as writing fetching code directly in <select> is a bad practise and in case of any issue, it my expose your database field names.

How to set same id for multiple rows in a table

I have a table named wp_shortcode. When a form is data from the form will be inserted to multiple rows into the table. Below given is my form:
<form method="POST" action="" class="form1">
<input type="submit" name="submit" value="Generate"><br>
Post Type
<select class="taxonomy">
<option value="">Select</option>
</select>
<br>
Category
<select class="cat">
<option value="">Select</option>
</select>
<h3>Questions</h3>
<button class="new_btn">Add New</button><br>
<div class="add_ques">
<span>Question1</span>
<textarea name="ques1" id="ques1"></textarea>
<br>
Option1
<select class="option" name="opt1" id="opt1">
<option value="1">1</option>
<option value="2">2</option>
</select>
<br>
</div>
</form>
The add_ques div section will be multiplied on add new button click.I need to insert the data from the form to wp_shortcode table.Currently the table have s_id,post_types,category,question,option columns.
How can i add a common id to the rows generated during form submission.
Here is the solution:
I add an addition column group_id to the table. And when we submit the form we will check group_id values:
$post_id = $wpdb->get_results("SELECT group_id FROM $table_name");
$siz = sizeof($post_id);
$index = $siz-1;
$gid = $post_id[$index];
$group = $gid->group_id;
$group_id = (int)$group;
And last group_id value is checked:
if($group_id == 0){
$id = 1;
}
else{
$id = $group_id+1;
}
This id is inserted along with other values into table. By this set of data inserted during of form submission will get same id.
The field name should be an array, then you will get the values in post array in PHP ($_POST['ques'] and $_POST['opt'])Try this:
<div class="add_ques">
<span>Question1</span>
<textarea name="ques[]" id="ques1"></textarea><br>
Option1<select class="option" name="opt[]" id="opt1">
<option value="1">1</option>
<option value="2">2</option>
</select><br>
</div>
Also, the id of the fields should be unique.

How do I fix the selected item in a drop down box

I have edit form where I get info from database
<select name="table">
<?php
//fetch all tables from database
$user = $con->query("SELECT * FROM table") or die(mysql_error());
while($row = $table->fetch_object()) { ?>
<option value="<?php echo $row->tablename;?>">
<?php echo $row->tablename; ?>
</option> <?php }?> </select>
<label for="time">Time :</label>
<select name="time">
<option value="twotothree">2PM-3PM</option>
<option value="threetofour">3PM-4PM</option>
<option value="fourtofive">4PM-5PM</option>
<option value="fivetosix">5PM-6PM</option>
</select>
The names of the tables from drop-down menu are different. Everytime I select a table and a time slot and save the data, the selection goes back to the first row of the menu. Eg I select table 3 and 4PM-5PM after saving it goes back to table 1 and 2PM-3PM. I need to be fixed on the last selection as I might use 4PM-5PM for table 4 also. Any idea? Thanks
You can add selected attribute when rendering your select list, depending on $_POST variable, when it's available. For example for you table select element:
<select name="table">
<?php
$user = $con->query("SELECT * FROM table") or die(mysql_error());
while($row = $table->fetch_object()) { ?>
<option value="<?php echo $row->tablename;?>" <?php if (isset($_POST['table']) && $_POST['table'] == $row->tablename) echo 'selected'; ?> >
<?php echo $row->tablename; ?>
</option>
<?php }?>
</select>
In similar way you can do for time select element.

Set a PHP variable based on first option in a form?

I have a form that has a list of school courses. I have a PHP variable that is passed to an SQL statement based on the value of whatever option is selected. My issue is that when the page first loads, the variable has no value. Ideally, I'd like to be able to set the variable to whatever the first option in the form is.
Form:
<form method="post">
<select name="courseID">
<option value = "204" selected>Course 1</option>
<option value = "205"> Course 2 </option>
<option value ="206"> Course 3 </option>
</select>
<input id="button" type="submit" value = "Go" />
</form>
PHP & SQL
//get posted value from form - returns false if no value is selected
$course_id = $_POST['courseID'];
//prepared statement
//test query "SELECT * FROM [database] WHERE course_id = ?";
$sql = "SELECT A.title as course_title, B.body, C.title
FROM db.course as A,
db.objective as B,
db.competency as C,
db.course_objective_competency as D
WHERE
A.course_id = ? AND
A.course_id = D.course_id AND
B.objective_id = D.objective_id AND
C.competency_id = D.competency_id";
//prepare the query
$q = $con->prepare($sql);
//bind parameter to query (index, variable, type)
$q->bindParam(1,$course_id,PDO::PARAM_INT);
//execute the statement
$q->execute();
You can always do it like this:
$course_id = $_POST['courseID'] ?: 204;
if php code is in a separate file you have to add it to the action attribute for the form. Otherwise the values will never be sent to it
<form method="post" action='yourPhpFile.php'>
<select name="courseID">
<option value = "204" selected>Course 1</option>
<option value = "205"> Course 2 </option>
<option value ="206"> Course 3 </option>
</select>
<input id="button" type="submit" value = "Go" />
</form>

php mysql multiply database value with form selection

Hello I am really struggling with this. I was asked to develop a script to calculate oil price but cannot get it to work. I have been able to setup a form to update fuel price.
I have a table called fuel_price. In this table will be cost per litre of fuel which is stored under Price. For example if oil price per litre is £0.50 I need to multiply this value by value selected within form dropdown.
Can anyone please guide me on what I am supposed to do??
Ok heres an update code preview.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<select name="fueltype">
<option>- Select fuel type -</option>
<option value="Diesel">Diesel</option>
<option value="Red Diesel">Red Diesel</option>
<option value="Home Heating Oil">Home Heating Oil</option>
</select>
<select name="qtylitres">
<option>- Qty in Litres -</option>
<option value="100">100</option>
<option value="200">200</option>
<option value="400">400</option>
<option value="500">500</option>
<option value="900">900</option>
<option value="1000">1000</option>
</select>
<input type="hidden" name="id" value="" />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
include 'mysql_connect.php';
$pdo = '';
$stmt = $pdo->prepare("SELECT `Oil` from `fuel_price` WHERE id = '1'");
if (!$stmt->execute()) { die($stmt->errorInfo[2]); }
$row = $stmt->fetch();
$price = $row['Oil'];
echo $_POST['qtylitres'] * $price;
?>
Anyone know where I am going wrong??
Thanks
<?php
//Connect to database here. In this example, I'll assume you connected using PDO
//Although the same logic applies on any engine.
$stmt = $pdo->prepare("SELECT `price` from `fuel_price` WHERE `type` = :type"); //Prepare a query
$stmt->bindValue(':type', $_POST['type']); //Assuming the first <select> is named type
if (!$stmt->execute()) { die($stmt->errorInfo[2]); } //Display an error and terminate script if query failed.
$row = $stmt->fetch(); //Assuming you have only one row, fetch should only be called once.
$price = $row['price'];
echo $_POST['qtylitres'] * $price; //Multiply quantity with price and print result.
?>
Note that I have not tested it, but it should work. Your markup is incomplete, it lacks the opening for the first <select>. Read the comments and you should be good to go.
assuming that you have a column 'price' in your table, and that the only result contains the correct price:
include 'mysql_connect.php';
if (isset($_POST['submit'])) {
// edit: added fueltype in the where clause
$fueltype = mysql_real_escape_string($_POST['fueltype']);
$q = "SELECT * FROM fuel_price WHERE id = '1' AND fueltype='$fueltype'";
$result = mysql_query($q);
$row= mysql_fetch_array($result);
$price = $row['price'] * $_POST['qtylitres'];
echo $price;

Categories