taking the right value out of the loop - php

Below you can see my code. No need to show the other parts or the database table.
Code
<form method="POST" action="custInfo.php">
<center><input type="submit" id="btn" name="room"></center>
$query = mysqli_query($conn, "SELECT room_name, room_type, room_rate, inclusive, description, room_status, max_cap
FROM room
WHERE room_status = 'available'");
if(mysqli_num_rows($query)){
while($row = mysqli_fetch_assoc($query)){
echo "<div class='chooseRoom'>";
echo "<div class='indent'>";
echo "<h4>".$row['room_type']."</h4>
<h5>".$row['room_rate']."php</h5>";
echo "<img src='../images/".$row['room_type'].".jpg' width=250 height=160>";
echo "<h5>Number of Adult ";
echo "<select name='adult'>";
$x = 0;
while($x <= $row['max_cap']){
echo "<option>";
echo $x;
echo "</option>";
$x++;
}
echo "</select>";
echo " Number of Children ";
echo "<select name='children'>";
echo "<option>0</option>";
echo "<option>1</option>";
echo "<option>2</option>";
echo "<option>3</option>";
echo "<option>4</option>";
echo "<option>5</option>";
echo "</select></h5>";
echo "<table class='table'>";
echo "<thead>";
echo "<th>Inclusive</th><th>Description</th>";
echo "</thead>";
echo "<tbody>";
echo "<td>".$row['inclusive']."</td><td>".$row['description']."</td>";
echo "</tbody>";
echo "<tfoot>";
echo "<td colspan='2'>";
echo $row['room_status'];
echo "</td>";
echo "</tfoot>";
echo "</table>";
echo "</div>";
echo "</div>";
}
}
else{
echo "No rooms available in the date you desire!";
}
</form>
I need to take the value from the correct input. This code always takes the last input from the loop. And I have been trying to research about this for a day now. How do I fix this?

Please follow the below code:
$result = mysqli_query($connection, $query);
?>
<form method="POST" action="custInfo.php">
<center><input type="submit" id="submit_button" name="room_submit" value="Submit"></center>
<?php
while ($row = mysqli_fetch_assoc($result)) {
?>
<div class='chooseRoom'>
<div class='indent'>
<h4><?php echo $row['room_type']; ?></h4>
<h5><?php echo $row['room_rate']; ?></h5>
<img src='../images/<?php echo $row['room_type']; ?>.jpg' width="250" height="160">
<h5>Number of Adult
<select name='adult[]'> <!-- NOTICE HERE... -->
<?php
$x = 0;
while($x <= $row['max_cap']){
?>
<option><?php echo $x; ?></option>
<?php
$x++;
}
?>
</select>
Number of Children
<select name='children[]'> <!-- NOTICE HERE... -->
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</h5>
<table class='table'>
<thead>
<th>Inclusive</th>
<th>Description</th>
</thead>
<tbody>
<td><?php echo $row['inclusive']; ?></td>
<td><?php echo $row['description']; ?></td>
</tbody>
<tfoot>
<td colspan='2'><?php echo $row['room_status']; ?></td>
</tfoot>
</table>
</div>
</div>
<?php
}
?>
</form>
In the above code you will see that we are looping through some DB Rows. So there will be multiple Adult and Children selects. So for that case we are making them arrays with [] at the end. Which will preserve all inputs with same name inside an array.
/**
* After form submittion look at $_POST variable... eg.
*
* echo "<pre>";
* print_r($_POST);
* echo "</pre>";
*/
/**
*
* The $_POST['adult'] and $_POST['children'] will be an array.
* And then you can have whichever value you want by calling the right Index.
*
* Otherwise you can loop through them:
* foreach ($_POST['adult'] as $key => $value) {
* echo $value;
* }
* And ---- for children.
* foreach ($_POST['children'] as $key => $value) {
* echo $value;
* }
*
*/

Because of the names of inputs is duplicate. Try to change name of the input to Array.
For example:
<select name='children[]'></select>

Related

PHP - Rating 1-5 in stars

<table>
<tr>
<th>name</th>
<th>startDate</th>
<th>rating</th>
<th>underlay</th>
<th>edges</th>
<th>grip</th>
<th>depth</th>
<th>length</th>
<th>height</th>
<th>realname</th>
</tr>
<?php
if(isset($_GET['DS'])){
$query='SELECT * FROM KundDetaljer where rspName = :DS';
$stmt = $pdo->prepare($query);
$stmt->bindParam(':DS', $_GET['DS']);
$stmt->execute();
foreach($stmt as $key => $row){
echo '<tr>';
echo "<td>".$row['rspName']."</td>";
echo "<td>".$row['startDate']."</td>";
echo "<td>".$row['rating']."</td>";
echo "<td>".$row['underlay']."</td>";
echo "<td>".$row['edges']."</td>";
echo "<td>".$row['grip']."</td>";
echo "<td>".$row['depth']."</td>";
echo "<td>".$row['length']."</td>";
echo "<td>".$row['height']."</td>";
echo "<td>".$row['realname']."</td>";
echo "</tr>";
}
}
echo "</table>";
?>
Hi, i'm a student in Sweden who is having a problem with making numbers to stars out of rating. The code above is the code that shows the rating from customers. When the comments from customers is made i want it to be showed as stars.
inside foreach (before any echo):
$stars = "";
for($i=0;$i<$row["rating"];$i++){
$stars .= "★";
}
Then instead of
echo "<td>".$row['rating']."</td>";
use
echo "<td>".$stars."</td>";

PHP How to use for loop's variable with mysql_fetch_array to indicate row to get data?

I have trouble to use for loop's variable $counter with
$HA_Row = mysql_fetch_array($HA_Res);
to indicate which row's data I am going to get. Basically, I have no idea to use $counter and $HA_Res together.
I want to it can display different rows' data of my database.
For example, like
echo "$HA_Row[Check_In_Date]"
I have tried
echo "$HA_Row[$counter][Check_In_Date]"
and
echo "$HA_Row[Check_In_Date][$counter]", echo "[$counter]$HA_Row[Check_In_Date]"
but none of them works.
Thank you so much! Appreciate your time.
<?php
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['Hotel_User_ID']))
{
header("Location: index.php");
}
$res = mysql_query("SELECT * FROM Hotel_Info WHERE Hotel_ID =".$_SESSION['Hotel_User_ID']);
$userRow = mysql_fetch_array($res);
$HA_Res = mysql_query("SELECT * FROM Hotel_Account WHERE Hotel_ID =".$_SESSION['Hotel_User_ID']);
$HA_Row = mysql_fetch_array($HA_Res);
$HA_Count = mysql_num_rows($HA_Res);
// echo "$HA_Count". "<br>";
// echo "$HA_Row[Check_In_Date]";
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hello - <?php echo $userRow['Hotel_Email']; ?></title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
<div id="left">
<label>Welcome <?php echo $userRow['Hotel_Uname']; ?> </label>
</div>
<div id="right">
<div id="content">
Sign Out
</div>
</div>
</div>
<div id="menu">
Manage <br>
Update
</div>
<div id="body">
<center>
<div id="Hotel-InfoForm">
<form method="post" enctype="multipart/form-data">
<!-- <table.ver2 align="center" width="60%" border="0"> -->
<table align="center" width="85%" border = "1">
<tr>
<th>Check In Data</th>
<th>Check Out Data</th>
<th>Theme</th>
<th>Bed Size</th>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Age</th>
<th>Phone Number</th>
<th>Email</th>
</tr>
<?php
for($counter = 0; $counter < $HA_Count; $counter = $counter + 1)
{
// using $counter for $HA_Row[....]
echo "<tr>";
echo "<td>";
echo "$HA_Row[Check_In_Date]";
echo "</td>";
echo "<td>";
echo "$HA_Row[Check_Out_Date]";
echo "</td>";
$Theme_Res = mysql_query("SELECT * FROM Theme WHERE Theme_ID = ".$HA_Row[Theme_ID]);
$Theme_Row = mysql_fetch_array($Theme_Res);
echo "<td>";
echo "$Theme_Row[Theme_Name]";
echo "</td>";
echo "<td>";
echo "$Theme_Row[Bed_Size]";
echo "</td>";
$Guest_Res = mysql_query("SELECT * FROM Guest_Info WHERE Guest_ID = ".$HA_Row[Guest_ID]);
$Guest_Row = mysql_fetch_array($Guest_Res);
echo "<td>";
echo "$Guest_Row[First_Name]";
echo "</td>";
echo "<td>";
echo "$Guest_Row[Last_Name]";
echo "</td>";
echo "<td>";
echo "$Guest_Row[Gender]";
echo "</td>";
function ageCalculator($dob)
{
if(!empty($dob))
{
$birthdate = new DateTime($dob);
$today = new DateTime('today');
$age = $birthdate->diff($today)->y;
return $age;
}
else
{
return 0;
}
}
echo "<td>";
echo ageCalculator($Guest_Row[Birth_Day]);
echo "</td>";
echo "<td>";
echo "$Guest_Row[Phone_Num]";
echo "</td>";
echo "<td>";
echo "$Guest_Row[Email]";
echo "</td>";
echo "</tr>\n";
}
?>
</table>
</form>
</div>
</center>
</div>
</body>
</html>
You could use mysql_fetch_assoc and while looping, like this:
while($HA_Row = mysql_fetch_assoc($HA_Res)){
echo $HA_Row[Check_In_Date]."<br>";
};
This while will loop in each instance!
You don't normally use a counter to control fetch, especially if you just want to process the records in sequence. Each call to fetch will return the next row in the result set without further action on your part.
First, replace all your mysql_* calls with their mysqli_* counterparts. Then replace your line
for($counter = 0; $counter < $HA_Count; $counter = $counter + 1)
with
while ($HA_Row = mysqli_fetch_array($HA_Res))
On each loop, mysqli_fetch_array returns the next row, and after reading the last row the next call returns false, which exits the loop.
Switching to mysqli_* or PDO will also gain you prepared statements, which help to protect against SQL injection, among numerous other benefits.

fetch data in rows/column using php

I want to make 4 columns in table. In code all the images are comes in single row and single column. But I want a single row containing 4 columns with 4 images (images fetching from database), then create another row and automatically add next 4 images & so on. I don't know how I do this can anyone please suggest me how I do this.
<form name="form">
<select id="sorting" style="width:140px" onChange="optionCheck()">
<option id="s">---Sort By----</option>
<option value="bydate">Sort By Date</option>
<option value="bytopic">Sort By Topic</option>
</select>
</form>
<br />
</div>
<?php include 'connection.php'; ?>
<div id="showByDefault">
<table style="width:60%">
<tr>
<?php include 'connection.php'; ?>
<div id="showByDefault">
<!--<table style="width:60%"><tr>-->
<?php
$sql1=mysqli_query($con,"select * from `insert-n-retrive-pdf` ORDER BY date DESC") or die(mysqli_error($con));
$i=0;
echo "<table><tr>";
while($row=mysqli_fetch_array($sql1))
{
if($i != 0 && $i%4 == 0) {
echo '<tr></tr>';
}
?> <td style="padding:20px;">
<img src="<?php echo $row["thumbnails"]; ?>" /></td><?php
echo '</tr>';
$i++;
}
?></tr></table>
</div>
<div id="hideall">
<div id="topic1">
<?php include 'pdf-sort-by-topic.php'; ?>
</div>
<div id="topic">
<?php include 'pdf-sort-by-date.php'; ?>
</div>
</div>
Try this one 100% working: Nice and easy.
<?php
$sql1=mysqli_query($con,"select * from `insert-n-retrive-pdf` ORDER BY date DESC") or die(mysqli_error($con));
$i = 0;
echo "<tr>";
while($row=mysqli_fetch_array($sql1)) {
if($i != 0 && $i%4 == 0) {
echo "</tr><tr>";
}
?>
<td style="padding:20px;"><img src="<?php echo $row["thumbnails"]; ?>" /></td>
<?php
$i++;
}
?>
Hope this helps!
You can try this code
$query = mysql_query("SELECT * FROM insert-n-retrive-pdf ORDER BY date DESC");
echo '<table width="960">';
$i = 0; //first, i set a counter
while($fetch = mysql_fetch_assoc($query)){
//counter is zero then we are start new row
if ($i==0){
echo '<tr>';
}
//here we creating normal cells <td></td>
$image_name = $fetch['thumbnails'];
$image_location = $fetch['path'];
echo '<td>'.'<img src="'.$image_location.'" alt="'.$image_name.'"/>'.'</td>';
//there is a magic - if our counter is greater then 4 we set counter to zero and close tr tag
if ($i>4){
$i=0;
echo '</tr>';
};
$i++; //$i = $i + 1 - counter + 1
}
echo '</table>';
You can fetch all your images into one-dimensional array and then use function array_chunk(). It will split an array into smaller parts you need. Here's a manual page.
Actually, You can get something like this:
<?php
$images = array();
while($row=mysqli_fetch_array($sql1))
{
$images[] = $row;
}
$images = array_chunk($images, 4);
?>
<?php foreach($images as $imagesChunk): ?>
<tr>
<?php foreach ($imagesChunk as $image): ?>
<td style="padding:20px;">
<a href="<?=$image["path"];?>" target="_blank">
<img src="<?=$image["thumbnails"];?>" />
</a>
</td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
<table style="width:60%">
<tr>
<?php
$counter = 0;
$sql1 = mysqli_query($con, "select * from `insert-n-retrive-pdf` ORDER BY date DESC"
) or die(mysqli_error($con));
while($row=mysqli_fetch_array($sql1))
{
?>
<td style="padding:20px;">
<a href="<?php echo $row["path"]; ?>" target="_blank">
<img src="<?php echo $row["thumbnails"]; ?>" />
</a>
</td>
<?php
if($counter == 4)
{
echo "</tr>";
echo "<tr>";
$counter = 0;
}
$counter++;
}
?>
</tr>
</table>

multiple arrays value fetching with session

Insert Is Fine But if I select this value from database All Values are fine but single values fetch array problem I don't know how to solve this task. Please Update this code asap.
This Is Insert Code .....
<?php
if(isset($_POST['sendmessage'])){
$entermessage = $_POST['teachermessage'];
$checkbox_user = $_POST['usernameallcheckbx'];
$arr = implode(',',$checkbox_user);
//$arr2 = explode(',',$arr);
$insert = mysql_query("INSERT into usermessages(fromteacher,toparent,messages) VALUES('".$_SESSION['username']."','$arr','$entermessage')");
if($insert == 1){
echo "<h1>successful</h1>";
}
else{
echo mysql_error();
}
}
?>
<form method="post">
<div style="float:left; width:450px;"><br/><br/>Message: <br/>
<textarea style="width:400px; height:300px;" name="teachermessage"></textarea><br/>
<input type="submit" value="Send" name="sendmessage" /></div>
<div style="float:left; with:200px; padding-top:55px;">
<table>
<tr>
<?php
$select_query1 = mysql_query("SELECT * FROM register_user WHERE teacher='$teachername'");
while($chckbx=mysql_fetch_array($select_query1))
{
?>
<td><?php echo "<input type='checkbox' name='usernameallcheckbx[]' value=". $chckbx['userid']." />"; ?></td>
</tr>
<tr>
<td><?php echo $chckbx['parent_fname']." ".$chckbx['parent_lname']; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</form>
And This Is Select Code....
<h2>Messages</h2>
<?php
$select_query3 = mysql_query("SELECT * FROM usermessages");
$fetch= mysql_fetch_array($select_query3);
$data=$fetch['toparent'];
$arr=explode(',',$data);
//$userids=explode(',',$data);
$sessionshow=$_SESSION['userid'];
$userids=in_array("$sessionshow",$arr);
$select_query2 = mysql_query("SELECT * FROM usermessages WHERE toparent in ('$userids')='".$_SESSION['userid']."'");
?>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<th>Teacher Name</th>
<th>Message</th>
</tr>
<?php
while($fetch_name2=mysql_fetch_array($select_query2))
{
echo "<tr>";
echo "<td>".$fetch_data=$fetch_name2['fromteacher']."</td>";
echo "<td>".$fetch_data=$fetch_name2['messages']."</td>";
echo "</tr>";
}
?>
</table>
I have only put this as an answer to show some incorrect code - remove fetch data from your loop as it doesn't do anything
while($fetch_name2=mysql_fetch_array($select_query2))
{
echo "<tr>";
echo "<td>".$fetch_name2['fromteacher']."</td>";
echo "<td>".$fetch_name2['messages']."</td>";
echo "</tr>";
}
even better is use of a HEREDOC:
while($fetch_name2=mysql_fetch_array($select_query2))
{
echo <<<EOF
<tr>
<td>{$fetch_name2['fromteacher']}</td>
<td>{$fetch_name2['messages']}</td>
</tr>
EOF;
}
I really can't figure out what you're trying to do, but maybe this is the query you want:
SELECT * FROM usermessages WHERE FIND_IN_SET('$sessionshow', toparent)
FIND_IN_SET(str, strlist) searches the comma-separated list in strlist for an element that equals str, and returns the position in the list; if it's not found it returns 0, which counts as false.
I can't see any purpose to any of the code that uses $select_query3.

Show all rows in mysql table then give option to delete specific ones

I want to have the ability to show all the entries in a database table and by each one give the user the ability to delete specific ones.
I am currently using a for each loop that loops through the database showcasing each entry.
$result = mysql_query("SELECT * FROM KeepScores");
$fields_num = mysql_num_fields($result);
echo "<table><tr>";
// printing table headers
echo "<td>Recent Posts</td>";
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
How would to add a delete button that appears by each one and removes the entry from the database table?
You can do it with forms:
//main.php
<?php $result = mysql_query("SELECT * FROM KeepScores"); ?>
<table>
<tr>
<td>Recent Posts</td>
</tr>
<?php while($row = mysql_fetch_array($result)) : ?>
<tr>
<td><?php echo $row['field1']; ?></td>
<td><?php echo $row['field2']; ?></td>
<!-- and so on -->
<td>
<form action="delete.php" method="post">
<input type="hidden" name="delete_id" value="<?php echo $row['id']; ?>" />
<input type="submit" value="Delete" />
</form>
</td>
</tr>
<?php endwhile; ?>
</table>
//delete.php:
<?php
if(isset($_POST['delete_id'] && !empty($_POST['delete_id']))) {
$delete_id = mysql_real_escape_string($_POST['delete_id']);
mysql_query("DELETE FROM KeepScores WHERE `id`=".$delete_id);
header('Location: main.php');
}
Or you can do it with jQuery and AJAX:
//main.php
<?php $result = mysql_query("SELECT * FROM KeepScores"); ?>
<table>
<tr>
<td>Recent Posts</td>
</tr>
<?php while($row = mysql_fetch_array($result)) : ?>
<tr id="<?php echo $row['id']; ?>">
<td><?php echo $row['field1']; ?></td>
<td><?php echo $row['field2']; ?></td>
<!-- and so on -->
<td>
<button class="del_btn" rel="<?php echo $row['id']; ?>">Delete</button>
</td>
</tr>
<?php endwhile; ?>
</table>
<script>
$(document).ready(function(){
$('.del_btn').click(function(){
var del_id = $(this).attr('rel');
$.post('delete.php', {delete_id:del_id}, function(data) {
if(data == 'true') {
$('#'+del_id).remove();
} else {
alert('Could not delete!');
}
});
});
});
</script>
//delete.php
<?php
if(isset($_POST['delete_id'] && !empty($_POST['delete_id']))) {
$delete_id = mysql_real_escape_string($_POST['delete_id']);
$result = mysql_query("DELETE FROM KeepScores WHERE `id`=".$delete_id);
if($result !== false) {
echo 'true';
}
}
It's all untested and sure needs some adjustment for your specific project, but I think you get the idea and I hope it helps.
Next time, please post your schema if you ask stuff about database.
I thought I would improve on this a little bit by wrapping the delete post in a class and function. I was having the same problem. and this worked great for me. Thanks again # Quasdunk
<?php
// Class to hold the remove post function
class someClass{
//Function for removing the post
function removePost(){
if(isset($_POST['delete_id']) && (!empty($_POST['delete_id']))) {
$delete_id = mysql_real_escape_string($_POST['delete_id']);
$result = mysql_query("DELETE FROM post WHERE post_id='".$delete_id."' AND post_member='" . $_SESSION['SESS_USER'] . "'");
if($result !== false) {
echo 'true';
}
}
}
}
if(isset($_SESSION['SESS_MEMBER_ID'])){
$member = $_SESSION['SESS_USER'];
$res = mysql_query("SELECT * FROM post WHERE post_member='$member' ORDER BY timestamp DESC") or die(mysql_error());
$i = new someClass;
while($row = mysql_fetch_array($res)){
echo '<div style="width:100%;margin:0 auto;border-top:thin solid #000;">';
echo '<div style="width:600px;margin:0 auto;padding:20px;">';
echo $row['post_text'] . '<br>';
$postID = $row['post_id'];
echo '<div style="border-top:thin solid #000;padding:10px;margin-top:5px;background-color:#CCC;">';
echo 'You posted this on: ' . $row['post_date'] . '#' . $row['post_time'];
echo '<div style="float:right;">
<form method="post" action="'. $i->removePost() .'">
<input type="hidden" name="delete_id" value="'.$row['post_id'].'" >
<input type="submit" value="Delete Post">
</form>
</div>';
echo '</div>';
echo '</div>';
echo '</div>';
}
}
?>
Produce a key to each table, using jquery,then link it to a php file which an accept the key and delete from the specific table (which also can be passed through jquery)

Categories