for loop deducting a value from combobox - php

I have a dynamic combobox that displays Seat Numbers. I have a for loop that deducts a selected value from the combobox.
function display_seatNo() {
$query = "SELECT * FROM table1 WHERE ID = 1";
$result = mysql_query($query) or die("Failed to fetch records");
$rows = mysql_fetch_array($result);
$seatNo = $rows['SeatNo'];
$totalSeat = $rows['TotalSeats'];
$seatReserved = $rows['SeatsReserved'];
$remain = $totalSeat - $seatReserved;
$length = count($remain);
for($i=1; $i<=$remain-1; $i++){
echo "<option value=\"$i\" ";
echo " $i";
echo "> $i </option>";
}
}
<select name="cbSeatNo" id="cbSeatNo" class="cb1">
<?php display_seatNo(); ?>
</select>
Problem is that the selected value is not eliminating. Example:- Once Seat Number 1 is reserved, it shouldn't display in the combobox.

You loop through all numbers from 1 to $remain-1. That is a logic error. Example:
You have 10 seats. Seat 3 is taken. You loop through 1 to (10-1 = 9). Seat 3 will show in the list.
Instead you need to fetch the actually available (or taken) seats from your database, not just a count.

Instead of looping through the result set.
Better change your query to something like this
Select * from table1 where seatsReserved = false ;
For each reservation, set the seatsReserved value to false.

Search $seatReserved for $i then skip it.
$seatReserved = empty($seatReserved) ? array() : $seatReserved;
for($i=1; $i<=$remain-1; $i++){
if((array_search( $i, $seatReserved)) !== false) {
continue;
}
echo "<option value=\"$i\" ";
echo " $i";
echo "> $i </option>";
}
Edit: just in case 0 seats are reserved I gave $seatReserved a default value of array().

Related

PHP- is unable to read the other checked checkbox

I stored the data in a supposed to be an array but what happens is that only the last checked checkbox is the only one that is registered in the idSkills. This is the part of the code wherein the skills are displayed through a query in the database
<?php
$i=0;
while ($row = mysqli_fetch_assoc($result)) {
$id=$row['id'];
$skillName=$row['skillName'];
?>
<input type="checkbox" name="skills[]" value="<?php echo $id; ?>"><?php echo $skillName; ?><br>
<?php
$i++;
}
?>
Here is the part where the loop unveil all of the selected checkbox
//QUERY TO INSERT
$conn = new mysqli($config['servername'], $config['username'], $config['password'], $config['database']);
$idSkills = $_GET['skills'];
if(empty($idSkills))
{
echo("You didn't select any buildings.");
}
else
{
$N = count($idSkills);
echo("You selected $N door(s): ");
echo("$idSkills[1] ");
for($i=0; $i < $N; $i++) {
echo "Skill ID: "
$sql = "INSERT INTO volunteer_skills (idskill,idVolunteer)
VALUES ('$idSkills[$i]','$idVolunteer')";
$result = $conn->query($sql);
}
}
$conn->close();
It would be best to use a prepared statement instead of substituting a variable into the SQL. But if you're going to do it this way, you need to use the correct syntax:
$sql = "INSERT INTO volunteer_skills (idskill,idVolunteer)
VALUES ('{$idSkills[$i]}','$idVolunteer')";
You need to put {} around an array reference in order to get the variable inside the brackets to be evaluated. See the section on Complex (curly) Syntax in the PHP Strings documentation.

Storing values from dropdowns to Database using PHP

I am working on an attendance module. Initially, it will show the list of all students along with a dropdown having options Present/Absent. The faculty member will choose Present/Absent accordingly & submit the same.
I am having problem in storing the corresponding values to the DB.
$sql = "select a.student_id, r.student_name, r.section, r.group_name, a.$subject from result.$batch r, attendance.$batch a where a.student_id = r.student_id AND r.section='$section'";
$c = 1;
$result1 = $result->query($sql);
if ($result1->num_rows > 0)
{
while($row = $result1->fetch_assoc())
{
echo '<tr>';
echo "<td>$c </td>";
echo "<td>{$row['student_id']}</td>";
echo "<td>{$row['student_name']}</td>";
echo "<td>{$row['section']}</td>";
echo "<td>{$row['group_name']}</td>";
echo "<td>
<select class='dropdown' id='attend' name='attend[$c]' > <option value='1'>Present</option> <option value='2'>Absent</option>
</td>";
echo '</tr>';
++$c;
}
}
else
{
echo "No Results Found";
}
Can someone please help me with the updation code. Updation is to be made in the table $batch (batch is a variable containing Table Name to use) and column $subject (contains variable name).
well, you can do one thing.when user clicks on the check-box to mark absent or present, save it into an array using Javascript like :
onclick='array.push(this.id);'
this would push the id of current element to an array in Javascript.
When you finally submit the form, just do this,
onsubmit="passValues();"
in script tag, do this
function passValues()
{
var x = array // the array to which elements were pushed
document.getElementById('someBlankElement').innerHTML = "<input type='hidden' value = 'display array here' name='get_this_name_through_php_when_form_submits' >"
}
and done !

Sum values from rows in PHP

I'm trying to add values from row['scores'].
For example, if I have 6 rows that have a value of 1 for each row .. I want to be able to echo -> value of rows = 6.
The += is not working for me: I still get only the values themselves, e.g. 1,2,3,4,5,6,7 but I want the sum of it, let's say 1+2+3+4+5+6+7=28.
Thanks
<?php include("connect.php"); ?>
<html>
<head>
<title>Score Predictions</title>
</head>
<body>
<div id = "id">
<?php
$query = "SELECT * FROM test";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$home = $row['home'];
$away = $row['away'];
}
?>
<?php
if (isset($_POST['submit'])) {
$x = $_POST["test"];
mysql_query("INSERT INTO test (home, away, score) VALUES ('$home', '$away', '$x')");
}
?>
<?php echo $home," - ",$away; ?>
<form method = 'post' action = 'http://albsocial.us/test/index.php'>
<select name = 'test'>
<option value = "" selected = 'selected'></option>
<option VALUE = '1'>1</option>
<option VALUE = 'X'>X</option>
<option VALUE = '2'>2</option>
</select>
<INPUT TYPE = 'submit' name = 'submit' />
</form>
<?php
$query = "SELECT * FROM test";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$id = $row['id'];
$score = $row['score'];
if ($score == "1") {
echo $sum += $score - 1;
}
}
?>
</div>
</body>
</html>
$sum=0;
while($row=mysql_fetch_array($result)){
$id = $row['id'];
$score = $row['score'];
if ($score == "1"){
$sum = $sum+$score;
}
}
echo $sum;
try this.
it sume al $score values.
You have to remove the if condition and add the database value to $sum variable
$sum = 0;
while($row=mysql_fetch_array($result)){
$id = $row['id'];
$score = $row['score'];
$sum += (int)$score;
}
echo $sum;
Several problems here, as other answers mostly fix, but to make clear:
your if $score == 1 doesn't seem relevant to your purpose. Did you mean if $id == 1, or were you just trying to ignore zeros? (anything + zero stays the same anyway, so you don't need to)
there doesn't seem to be a reason for subtracting one in $sum += $score-1 either
you need to finish the adding up first, and then call echo once. Currently, you have an echo for every database row, which is why you're seeing multiple numbers output.
if you're only displaying the sum anyway, you don't need to do this in a loop at all, just get the DB to add up for you, e.g. SELECT SUM(score) AS total_score FROM test or SELECT id, SUM(score) AS total_score FROM test GROUP BY id

Display checked checkbox record from database

I have looked through similar problems and solution but somehow only half way help me with my problem. I'm trying to make a form to checked more than one record from MySQL database and display the checked record to another page. Somehow I managed to do the page with check boxes but I don't know how to display the record checked. It can only display the first row of the record or all the records regardless which box are checked.
This is checkbox page
$columns = count($fieldarray);
//run the query
$result = mysql_query(
"SELECT * FROM request_item
ORDER BY request_item.IllNo DESC LIMIT 0, 6") or die(mysql_error());
$row = mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
{
$rows[] = $row['IllNo'];
}
foreach($rows as $value);
echo "";
echo " ";
echo $row['IllNo'];
echo "";
}
echo "";
?>
This is display record checked
$columns = count($fieldarray);
//run the query
$result = mysql_query(
"SELECT * FROM request_item
ORDER BY request_item.IllNo DESC LIMIT 0, 6") or die(mysql_error());
$row = mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
$rows[]=$row['IllNo'];
foreach($rows as $value);
if ($rows= 'checked') {
echo "";
echo $value;
}
Any help are welcome. Thank you.
There's actually a lot of problems with that script including syntax errors, calling the wrong variable name, form not opening where it should, invoking PHP after you already have, etc...
To get a good answer to you, you should share what make $row['IllNo'] should equal to indicate if it should be checked or not.
I reformatted it a bit and this may give you a good start.
<form NAME ="form1" METHOD ="POST" ACTION ="dari.php">
<table>
<?php
$columns = count($fieldarray);
//run the query
$result = mysql_query("SELECT * FROM request_item ORDER BY request_item.IllNo DESC LIMIT 0, 6") or die(mysql_error()) ;
$row = mysql_num_rows($result);
while($row=mysql_fetch_array($result)) {
echo "<tr><td>";
echo "<Input type = 'Checkbox' Name ='ch1' value ='ch1'";
// check checked if it is. this will be checked if $row['IllNo'] has a value
// if there were a condition to make it checked, you would put the condition
// before the ?
echo $row['IllNo'] ? ' checked' : '';
echo ' />';
echo $row['IllNo'];
echo "</td></tr>";
}
?>
</table>
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Choose your books">
</FORM>

Need help pulling into multiple columns from one database table - mysql_query

Afternoon all,
A very quick question... a friend has set up a form for me using mysql_query. Since he wrote this, I have added an extra column into the database, which I want to pull through into the form.
However I can't seem to get this extra column to appear (labelled Currency). The reason I need it is the query below will pulls back a value and the £ symbol. Because I want to display not only £, but also € prices, I need this extra column to pull through (obviously I will have to remove the £ from the echo below too).
I've tried adding the extra column (Currency) to the code, e.g. "SELECT Room, Currency, Price FROM Spa_Upgrades
but this hasn't worked.
The code is:
<?php
if (isset($id))
{
$query2 = mysql_query("SELECT Room, Price FROM Spa_Upgrades WHERE Spa_Upgrades.Spa_Id = '".$id."' AND Spa_Upgrades.Id = '".$pack."' order by Spa_Upgrades.Order");
$rows = mysql_num_rows($query2);
if($rows==0) {echo "disabled='disabled'/>";}
else
{
echo "/>";
echo "<option value='Default'>Please Select</option>";
for($i=0; $i<$rows; $i++)
{
$result2 = mysql_fetch_array($query2);
echo "<option value='".$result2[0]." £".$result2[1]."pp'>$result2[0] £$result2[1]pp</option>";
}
}
}
Hugely grateful if someone can solve this!
Thanks,
Motley
Alter the query as follows:
SELECT Room, Price, Currency FROM Spa_Upgrades ...
Alter the line beginning echo inside the for loop: replace £ with $result2[2] wherever it appears. (Or if the Currency column doesn't contain the HTML entity for the currency symbol, then replace £ with appropriate code to obtain the symbol from the Currency column entry.)
You also need to add the column to the output... I would also switch to an associative array otherwise if you add a column and its not at the end you have to change all the indexes.
if (isset($id))
{
$query2 = mysql_query("SELECT Room, Price, Currency FROM Spa_Upgrades WHERE Spa_Upgrades.Spa_Id = '".$id."' AND Spa_Upgrades.Id = '".$pack."' order by Spa_Upgrades.Order");
$rows = mysql_num_rows($query2);
if($rows==0) {echo "disabled='disabled'/>";}
else
{
echo "/>";
echo "<option value='Default'>Please Select</option>";
for($i=0; $i<$rows; $i++)
{
$result2 = mysql_fetch_assoc($query2);
$value = $result2['Room'] . ' ' . $result2['Currency'].$result2['Price'].'pp';
echo sprintf('<option value="%s">%s</option>', $value, $value);
}
}
}
Use mysql_fetch_assoc() instead of mysql_fetch_array()
A good practice as well is to separate data retrieving from display logic
Try this:
<?php
$results = array();
if (isset($id))
{
$resource = mysql_query("SELECT room, currency, price FROM Spa_Upgrades
WHERE Spa_Upgrades.Spa_Id = '".intval($id)."' AND Spa_Upgrades.Id = '".intval($pack)."'
order by Spa_Upgrades.Order");
while($row = mysql_fetch_assoc($resource))
$results[] = $row;
}
?>
<select name="..." <?php echo (count($results) > 0 ? '' : 'disabled') ?>>
<option value="Default">Please Select</option>
<?php
foreach($results as $result)
{
$value = $result['room'].' '.$result['currency'].$result['price'].'pp';
echo '<option value="'.htmlspecialchars($value).'">'.htmlspecialchars($value).'</option>'."\n";
}
?>
</select>

Categories