PHP Add value to each table row data - php

i'm working on a php script wherein i must add certain score value at each row. I was able to display all the rows but i'm not sure on how would I able to store each of the given score in a variable and what query should I make to add all of them.
Here's my code
<?php
echo '<html>';
?>
<body>
<table border=0 cellspacing=0 cellpadding=0>
<?php
$connect = mysql_connect('localhost', 'root', '');
$db = 'labs';
$tb = 'comments';
$seldb = mysql_select_db($db, $connect);
echo '<form method="POST" action="..'.$_SERVER["PHP_SELF"].'">';
$query = mysql_query('SELECT com_id, comments FROM comments ORDER BY com_id ASC');
while($i = mysql_fetch_assoc($query)) {
echo'<tr><td>'.$i['comments'].'</td>';
echo'<td><select name="score" id="score" size="1">
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="35">35</option>
<option value="40">40</option>
<option value="45">45</option>
<option value="50">50</option>
</select></td></tr>';
echo'<br>';
}
echo'<input type="submit" name="submit" value="submit">';
echo'</form>';
if(isset($_POST['submit'])) {
//not sure if all the scores will be stored in here.
$id = $_POST['id'];
$query = mysql_query('insert query here');
}
?>
</table>
</body>
</html>
any suggestions are appreciated. Thanks in advance.:D

I think you need the id of each changed row (maybe as a hidden field for each row. Then just do a loop through all received rows and UPDATE each one.
You might also want to change all of your form field names to use the array format. This way it's easier to make your PHP loop throught them.
Sample row:
echo'<tr><td>'.$i['comments'].'</td>';
echo'<td><select name="score['.$i["id"].']" id="score" size="1">
<option value="5">5</option>
<option value="5">10</option>
<option value="5">15</option>
<option value="5">20</option>
<option value="5">25</option>
<option value="5">30</option>
<option value="5">35</option>
<option value="5">40</option>
<option value="5">45</option>
<option value="5">50</option>
</select></td></tr>';
Now just loop through the $_POST["score"] array and use the appropriate ID for your update.
foreach($_POST["score"] as $id => $value{
// ESCAPE your db values!!!!!
// query stuff with $value and $id
}
Also keep in Mind
mysql is deprecated! Use mysqli
Escape anything from outside sources like $_POST before use in SQL

You just needs to make an array of your drop down box like below,
while($i = mysql_fetch_assoc($query)) {
echo'<tr><td>'.$i['comments'].'</td>';
echo'<td><select name="score[".$i['com_id']."]" id="score" size="1">
<option valyue="5">5</option>
<option valyue="5">10</option>
<option valyue="5">15</option>
<option valyue="5">20</option>
<option valyue="5">25</option>
<option valyue="5">30</option>
<option valyue="5">35</option>
<option valyue="5">40</option>
<option valyue="5">45</option>
<option valyue="5">50</option>
</select></td></tr>';
echo'<br>';
}
and you can access it for all of your comments

<option valyue="5">50</option>
should be
<option value="5">50</option>
To send the value of a comment to database you need to add a ID of the comment
you should loop something like this.
$query = mysql_query('SELECT com_id, comments FROM comments ORDER BY com_id ASC');
while($i = mysql_fetch_assoc($query)) {
echo '<form method="POST" action="..'.$_SERVER["PHP_SELF"].'">';
echo '<input type="hidden" name="id" value="'.$i['com_id'].'">';
echo'<tr><td>'.$i['comments'].'</td>';
echo'<td><select name="score" id="score" size="1">
<option value="5">5</option>
<option value="5">10</option>
<option value="5">15</option>
<option value="5">20</option>
<option value="5">25</option>
<option value="5">30</option>
<option value="5">35</option>
<option value="5">40</option>
<option value="5">45</option>
<option value="5">50</option>
</select></td></tr>';
echo'<br>';
echo'<input type="submit" name="submit" value="submit">';
echo'</form>';
}

I guess the easiest way for you is the following (a mix of the other solutions and comments):
<?php
echo '<html>';
?>
<body>
<table border=0 cellspacing=0 cellpadding=0>
<?php
$x = 0;
$connect = mysql_connect('localhost', 'root', '');
$db = 'labs';
$tb = 'comments';
$seldb = mysql_select_db($db, $connect);
echo '<form method="POST" action="..'.$_SERVER["PHP_SELF"].'">';
$query = mysql_query('SELECT com_id, comments FROM comments ORDER BY com_id ASC');
while($i = mysql_fetch_assoc($query)) {
$x++;
echo'<tr><td>'.$i['comments'].'</td>';
echo'<td><select name="score_'.$x.'" id="score" size="1">
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="35">35</option>
<option value="40">40</option>
<option value="45">45</option>
<option value="50">50</option>
</select></td></tr>';
echo'<br>';
}
echo'<input type="submit" name="submit" value="submit">';
echo'</form>';
if(isset($_POST['submit'])) {
//not sure if all the scores will be stored in here.
$id = $_POST['id'];
for($y = 0;$y <= $x; $y++)
{
//This query is no sql injection save. Please add filters for productive uses!!
$query = mysql_query('UPDATE table_name SET score = '.$_POST["score_".$y].' WHERE id='.$id);
}
?>
</table>
</body>
</html>
Code is no tested!

Related

How to unset and remove blank options from a submitted drop down menu?

Here is my code to use Condorcet:
use CondorcetPHP\Condorcet\Condorcet;
use CondorcetPHP\Condorcet\Election;
use CondorcetPHP\Condorcet\Candidate;
use CondorcetPHP\Condorcet\CondorcetUtil;
use CondorcetPHP\Condorcet\Vote;
if (isset($_POST) && $_POST != "") {
Condorcet::setDefaultMethod('Schulze');
$election = new Election ();
print("<pre>");
print_r($_POST['item']);
// To get Candidates by Category via Doctrine orm
$category = $em->getRepository('Entities\Category')->findOneBy(['id' => 1]);
$candidates = $category->getCandidates();
$total_items = 0;
foreach ($candidates as $candidate) {
$candidate = $candidate->getCandidate();
$election->addCandidate(new Candidate($candidate));
++$total_items;
}
$votes = array();
foreach ($_POST['item'] as $item => $ranking) {
$vote_factor = 1 + $total_items - $ranking;
if (isset($votes[$vote_factor])) {
$votes[$vote_factor] = (array) $votes[$vote_factor];
$votes[$vote_factor][] = $item;
} else {
$votes[$vote_factor] = $item;
}
}
$result = $election->addVote(new Vote($votes));
print("<br />");
foreach ($election->getResult('Schulze') as $rank => $candidates) :
echo 'Rank ' . $rank . ': ';
echo implode(', ', $candidates);
echo '<br />';
endforeach;
print_r($result->getSimpleRanking()); // To be saved in db.
echo 'Schulze winner is : ' . $election->getWinner('Schulze')->getName() . '<br />';
}
?>
<html>
<body>
<form method="post">
Wingspan: <select name="item[Wingspan]" id="Wingspan">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br />
Scythe: <select name="item[Scythe]" id="Scythe">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br />
Spirit Island: <select name="item[Spirit Island]" id="Spirit Island">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br />
Everdell: <select name="item[Everdell]" id="Everdell">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br />
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
I want to add a blank select option, that my users if they don't want to have some candidates in voting just use the blank select option and don't be forced to select a ranking number from the drop down menu. How to omit blank options completely from listing and voting? I think I have to unset blank options in a foreach? If yes, how?

Values not being submitted from PHP HTML form [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am trying to take the input from drop down menus that users enter and submit them to a table in my database. I am trying to submit the values into this table:
I use the POST to check that the values are being pulled from the HTML form and they are, but they won't submit into my table. I've made sure that all of the names with the columns and HTML forms are correct, why won't the values post to the table?
<?php
$databaseName = 'pizza_db';
$databaseUser = 'root';
$databasePassword = 'root';
$databaseHost = '127.0.0.1';
$conn = new mysqli($databaseHost, $databaseUser, $databasePassword, $databaseName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected sucessfully\n";
if(isset($_POST['submit'])){
$value = mysqli_real_escape_string($conn,$_POST['drink']);
$value2 = mysqli_real_escape_string($conn,$_POST['cheese']);
$value3 = mysqli_real_escape_string($conn,$_POST['veggies']);
$value4 = mysqli_real_escape_string($conn,$_POST['meat']);
$value5 = mysqli_real_escape_string($conn,$_POST['sauce']);
$value6 = mysqli_real_escape_string($conn,$_POST['crust']);
$value7 = mysqli_real_escape_string($conn,$_POST['size']);
$sql = "INSERT INTO order_info(drink,cheese,veggies,meat,sauce,crust,size)
VALUES('$value','$value2','$value3','$value4','$value5','$value6','$value7')";
//Here I am posting the values to check that they are being submitted
echo $_POST["size"];
echo "\n";
echo $_POST["sauce"];
echo "\n";
echo $_POST["crust"];
echo "\n";
echo $_POST["cheese"];
echo "\n";
echo $_POST["meat"];
echo "\n";
echo $_POST["veggies"];
echo "\n";
echo $_POST["drink"];
$conn->close();
}
?>
<!DOCTYPE html>
<html>
<body>
<form action='' method='post'>
<p>Choose a size<p>
<select id="size" name="size">
<option value="small">Small</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
<option value="x-large">X-large</option>
</select>
<p> Choose a sauce <p>
<select id="sauce" name="sauce">
<option value="none">None</option>
<option value="marinara">Marinara</option>
<option value="alfredo">Alfredo</option>
<option value="ranch">Ranch</option>
<option value="bbq">BBQ</option>
</select>
<p> Choose a cheese<p>
<select id="cheese" name="cheese">
<option value="none">None</option>
<option value="mozzarelaa">Mozarella</option>
<option value="cheddar">Cheddar</option>
<option value="parmesan">Parmesan</option>
<option value="three cheese">Three-Cheese</option>
</select>
<p> Choose a meat <p>
<select id="meat" name="meat">
<option value="none">None</option>
<option value="Pepperroni">Pepperroni</option>
<option value="sausage">Sausage</option>
<option value="bacon">Bacon</option>
<option value="canadian bacon">Canadian Bacon</option>
<option value="chicken">Chicken</option>
<option value="salami">Beef</option>
<option value="anchovies">Anchovies</option>
</select>
<p> Choose a veggies <p>
<select id="veggies" name="veggies">
<option value="none">None</option>
<option value="onions">Onions</option>
<option value="green peppers">Green Peppers</option>
<option value="Red peppers">Red peppers</option>
<option value="Black olives">Mushrooms</option>
<option value="jalapenos">Jalapenos</option>
<option value="tomatoes">Tomatoes</option>
<option value="pineapple">Pineapple</option>
</select>
<p> Choose a crust <p>
<select id="crust" name="crust">
<option value="regular">Regular</option>
<option value="deep-dish">Deep-dish</option>
<option value="thin-crust">Thin Crust</option>
<option value="stuffed crust">Stuffed Crust</option>
<option value="gluten free">Gluten Free</option>
</select>
<p> Choose a drink <p>
<select id="drink" name="drink">
<option value="none">None</option>
<option value="rootbeer">Root Beer</option>
<option value="coke">Coke</option>
<option value="diet coke">Diet Coke</option>
<option value="dr pepper">Dr Pepper</option>
</select>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
Seems like you are not running the query.
// sql
$sql = "INSERT INTO order_info(drink,cheese,veggies,meat,sauce,crust,size)
VALUES('$value','$value2','$value3','$value4','$value5','$value6','$value7')";
// run query
mysqli_query($conn, $sql);
// or
$conn->query($sql);
You prepared string query but you are not executing it.
$sql = "INSERT INTO order_info(drink,cheese,veggies,meat,sauce,crust,size)
VALUES('$value','$value2','$value3','$value4','$value5','$value6','$value7')";
// run query with below mentioned function
mysqli_query($conn, $sql);
Then check your table. You will see the data saved.

php code to get listbox selected value in variable for where clause

below is my select tag code..I need to get selected input in temp variable.
and use this variable to search.
FOR EX-
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="vw">VW</option>
<option value="audi" selected>Audi</option>
</select>
Now I selected Saab from listbox. then get this value in variable in temp
and use this temp variable in search query.
<?php
$temp = "Saab";
$book_no2 = $temp;
$receipt = $database->getRows("SELECT receipt_no FROM scheme_master WHERE book_no2 = :book_no2", array(':book_no2'=>$book_no2));
?>
<select name="book" onChange="showUser(this.value)">
<?php foreach ($book as $load_book){ ?>
<option value=""></option>
<option value="<?php echo $load_book["book_no"]; ?>"><?php echo $load_book["book_no"]; ?></option>
<?php }?>
</select>
<?php
$book_no2 = $load_book["book_no"];
$receipt = $database->getRows("SELECT receipt_no FROM scheme_master WHERE book_no2 = :book_no2", array(':book_no2'=>$book_no2));
?>
You should you form and get the selected book from global $_POST variable, but make sure you properly escaped all the variables coming from the client side (e.g. using mysql_real_escape_string PHP function).
<?php
$book_no2 = mysql_real_escape_string($_POST['book']);
$receipt = $database->getRows("SELECT receipt_no FROM scheme_master WHERE book_no2 = :book_no2", array(':book_no2'=>$book_no2));
?>
<form method="POST">
<select name="book" onChange="showUser(this.value)">
<?php foreach ($book as $load_book){ ?>
<option value=""></option>
<option value="<?php echo $load_book["book_no"]; ?>"<?php if ($load_book["book_no"] == $temp):?> selected="selected"<?php endif?>><?php echo $load_book["book_no"]; ?></option>
<?php }?>
</select>
<input type="submit" value="Send" />
</form>
Plz see ...this will resolve my problem....
<select name="book" onChange="showUser(this.value)">
<option value="<?php if(isset($_GET['edit'])){ echo $data['book']; }?>"><?php if(isset($_GET['edit'])){echo $data['book'];}?></option>
<?php foreach ($book as $load_book){ ?>
<option value=""></option>
<option value="<?php echo $load_book["book_no"]; ?>"><?php echo $load_book["book_no"]; ?></option>
<?php }?>
</select>
<?php
$book_no2 = $load_book["book_no"];
$receipt = $database->getRows("SELECT DISTINCT receipt_no FROM scheme_master WHERE book_no2 = :book_no2", array(':book_no2'=>$book_no2));
?>
Make your first file
<form action="second page" method="post"
<select name="car">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="vw">VW</option>
<option value="audi" selected>Audi</ option>
</select>
<input type="submit">
</form>
Then pass this to your temp var
$temp=$_POST[`car`];

php script won't connect MySQL

This is the code. and for some reason I can't find out why it is not working.
As you can see I've added a test query to see if it affects any changes on my db but nope :(
The funny thing is that in another php script I have succeeded to connect the db and even added some records to it thru the php script. Can't find the problem, Thanks from advance.
BTW. as you can see I have already defined the var "month" as string "hey" and echo it in the end of the php script to see if it changes. but nothing is happen!!
<form action="" name="form" id="form">
<label>
Select the month which you want to display its days.
<select name="month" form="form" required>
<option value="january">January</option>
<option value="february">February</option>
<option value="march">March</option>
<option value="april">April</option>
<option value="may">May</option>
<option value="june">June</option>
<option value="july">July</option>
<option value="august">August</option>
<option value="september">September</option>
<option value="october">October</option>
<option value="november">November</option>
<option value="december">December</option>
</select>
</label>
<input type="submit" name="update" value="Display" />
</form>
<?php
$month = "hey";
if(isset($_POST["update"]))
{
$month = $_POST["month"];
$query = "SELECT * FROM `days` WHERE `month`='{$month}';";
$conn = mysqli_connect("localhost","root","","db123");
$result = mysqli_query($conn,$query);
mysqli_query($conn,"INSERT INTO `days`(`month`,`day`) VALUES ('test','10');");
if($result)
{
die("Sorry!");
}
while($row = mysqli_fetch_row($result))
{
echo $month;
print_r($row);
}
mysqli_close($conn);
echo $month;
}
?
You didn't specified the method , its GET by default if.Change this line
if(isset($_POST["update"]))
to this
if(isset($_GET["update"]))
. Or if you want to use method as POST than just specify the method as POST
use the code below
<form action="" name="form" id="form" method="POST">
<label>
Select the month which you want to display its days.
<select name="month" form="form" required>
<option value="january">January</option>
<option value="february">February</option>
<option value="march">March</option>
<option value="april">April</option>
<option value="may">May</option>
<option value="june">June</option>
<option value="july">July</option>
<option value="august">August</option>
<option value="september">September</option>
<option value="october">October</option>
<option value="november">November</option>
<option value="december">December</option>
</select>
</label>
<input type="submit" name="update" value="Display" />
</form>
<?php
$month = "hey";
if(isset($_POST["update"]))
{
$month = $_POST["month"];
$query = "SELECT * FROM `days` WHERE `month`='{$month}';";
$conn = mysqli_connect("localhost","root","","db123");
$result = mysqli_query($conn,$query);
mysqli_query($conn,"INSERT INTO `days`(`month`,`day`) VALUES ('test','10');");
if($result)
{
die("Sorry!");
}
while($row = mysqli_fetch_row($result))
{
echo $month;
print_r($row);
}
mysqli_close($conn);
echo $month;
}
?>
Hope this helps you
<?php
$mysqli = new mysqli("localhost", "root", "", "db123");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$month = "hey";
if(isset($_POST["update"]))
{
$month = $_POST["month"];
$res = $mysqli->query("SELECT * FROM `days` WHERE `month`='{$month}'");
mysqli_query($conn,"INSERT INTO `days`(`month`,`day`) VALUES ('test','10');");
while($row = $res->num_rows)
{
echo $month;
print_r($row);
}
mysqli_close($conn);
echo $month;
}
?>

Html form select blank to search all of the table where the other fields match

I have a form that searches a database and returns rows that match the fields specified. I want to give an option to the user that if the field is left blank, it won't matter what is is that column as long as the other fields match. Right now, if I leave a field 'blank' it will return every entry in the database.
Hair Color: <select name="hair">
<option value="hairall" selected="selected">--</option>
<option value="black" >Black</option>
<option value="brown">Brown</option>
<option value="blonde">Blonde</option>
<option value="white">White</option>
<option value="red">Red</option>
<option value="other">Other</option>
</select>
Height: <select name="height">
<option value="heightall" selected="selected">--</option>
<option value="smaller">Smaller</option>
<option value="small">Small</option>
<option value="average">Average - 70in</option>
<option value="tall">Tall</option>
<option value="taller">Taller</option>
</select>
Body Type: <select name="body">
<option value="bodyall" selected="selected">--</option>
<option value="skinny">Skinny</option>
<option value="average">Average - 194lb</option>
<option value="heavy">Heavy</option>
</select>
Ethnicity: <select name="ethnicity">
<option value="ethnicityall" selected="selected">--</option>
<option value="white">White</option>
<option value="black">Black</option>
<option value="asian">Asian</option>
<option value="hispanic">Hispanic</option>
<option value="middleeast">Middle Eastern</option>
<option value="other">Other</option>
</select><br/>
<center><input type="submit" value="Find Me" name="submit" ></center>
</form>
</div>
<div id="results">
<?php
$submit = $_GET['submit'];
$gender = $_GET['gender'];
$hair = $_GET['hair'];
$height = $_GET['height'];
$body = $_GET['body'];
$race = $_GET['ethnicity'];
//Hair All/Specific
if ($hair=='hairall'){
$newhair = "black' OR `hair`='brown' OR `hair`='blonde' OR `hair`='white' OR `hair`='red' OR `hair`='other";
}else
$newhair=$hair;
//Height All/Specific
if ($height=='heightall'){
$newheight = "smaller' OR `height`='small' OR `height`='average' OR `height`='tall' OR `height`='taller";
}else
$newheight=$height;
//Body Type All/specific
if ($body=='bodyall'){
$newbody = "skinny' OR `body`='average' OR `body`='heavy";
}else
$newbody=$body;
//Etnicity All/Specific
if ($race=='ethnicityall'){
$newrace = "white' OR `race`='black' OR `race`='asian' OR `race`='hispanic' OR `race`='middleeast' OR `race`='other";
}else
$newrace=$race;
//echo "$newhair <br/> $newheight <br/> $newbody <br/> $newrace<br/>";
require 'connect.inc.php';
$query = "SELECT * FROM `table` WHERE `gender`='$gender' AND `hair`='$newhair' AND `height`='$newheight' AND `body`='$body' AND `race`='$race' ORDER BY `id` DESC";
Put parenthesis around each of your values - i.e. ('$gender') instead of '$gender'. That will prevent your OR clauses from messing up your AND clauses, which is the problem you're having.
A better solution would be to remove the check from the query entirely if the field is left blank, but that would require rewriting about half your code. In any case, here's roughly how I would do it:
// Only accept the specific fields that are expected
$query_fields = array_intersect_key($_GET, array(
'gender'=>true,
'hair'=>true,
'height'=>true,
'body'=>true,
'ethnicity'=>true,
));
// Exclude blank fields
$query_fields = array_filter($query_fields, 'strlen');
$database = (require 'connect.inc.php'); // Get connection to database in this variable somehow
$where_parts = array();
foreach($query_fields as $k=>$v) {
$v = $database->real_escape_string($v);
$where_parts[] = "`$k` = '$v'";
}
if(!$where_parts)
die('No filters selected!');
$query = 'SELECT * FROM `table` WHERE '.implode(' AND ', $where_parts).' ORDER BY `id` DESC';

Categories