I have 2 tables, group1 and group2.
With 3 columns, 'id',
'status' (0-Available, 1-Not available) and
'description' for the number 0 and 1 (Available and Not available)
When there is a 0 in the column it works well, and it shows the 'description' for that number,but
when all the numbers in the column are 1 it will not output my
else statement, dont know why? It standing still in the if statament.
I do not know how to output more rows
when i have more zeros in the table.
<?php include('config.php'); ?>
<!DOCTYPE>
<head>
<title>test</title>
<meta charset="UTF-8">
</head>
<body>
<form name='search' method="post">
<select name='onoroff'>
<option value='group1' >Group 1</option>
<option value='group2' >Group 2</option>
</select>
</datalist>
<input type='submit' name='run' value="Go"/>
</form>
<?php
//////////////////////////////////////////////
$group = ($_POST['onoroff']);
$q= mysqli_query($dbc, "SELECT * FROM $group WHERE status = 0");
$r= mysqli_fetch_assoc($q);
if (isset($_POST['run'])) {
echo '<p>'.$r['description'].'</p>';
} else { echo '<p>Not available</p>';}
///////////////////////////////////////////////
?>
</body>
</html>
You should put the database query inside the if(isset($_POST['run'])) block. Otherwise, you're trying to use $_POST['onoroff'] even though the user hasn't submitted the form yet.
if (isset($_POST['run'])) {
$group = ($_POST['onoroff']);
$q= mysqli_query($dbc, "SELECT * FROM $group WHERE status = 0");
$r= mysqli_fetch_assoc($q);
echo '<p>'.$r['description'].'</p>';
} else {
echo '<p>Not available</p>';
}
Adding the if statements with the returned value of the status will choose what is displayed depending on their status.
<?php include('config.php'); ?>
<!DOCTYPE>
<head>
<title>test</title>
<meta charset="UTF-8">
</head>
<body>
<form name='search' method="post">
<select name='onoroff'>
<option value='group1' >Group 1</option>
<option value='group2' >Group 2</option>
</select>
</datalist>
<input type='submit' name='run' value="Go"/>
</form>
<?php
//////////////////////////////////////////////
$group = ($_POST['onoroff']);
if (isset($_POST['run']))
{
$q= mysqli_query($dbc, "SELECT * FROM $group");
while ($r = mysqli_fetch_assoc($q))
{
if($r['status'] == 0) {
echo '<p>'.$r['id'].' : '.$r['description'].'</p>';
}
else {
echo '<p>'.$r['id'].' Not available</p>';
}
}
}
else
{
echo '<p>You need to submit to choose a group</p>';
}
///////////////////////////////////////////////
?>
</body>
</html>
Related
unable to list the information in LOV list from mysql table . I need to list the categories(catname) in the dropdown box and also let me know how to select the value(catno) for further action.
<?php
require_once('dbconnect.php');
$selsql="SELECT catno,catname FROM category"; //catno-integer and catname-
varchar
$res=mysqli_query($con,$selsql);
//$r=mysqli_fetch_assoc($res);
if (mysqli_query($con,$selsql)) {
}
else
{
echo "No connection";
die(mysqli_error($con));
}
?>
<html>
<head>
<title>Drop down list </title>
<meta charset=UTF-8">
<meta name="viewport">
</head>
<body>
<select name="categories"
style="width:250px;"onchange="this.form.submit();">
<?php while($row=mysqli_fetch_assoc($res)):;?>
<option value="<?php echo $row[0];?>"<?php echo $row[1];?></option>
<?php endwhile;?>
<!---<option value="<?php echo $row[0];?>""<?php echo $row[1];?>"</option>->
<!----$options.='<option value="'.$row[0].'"selected>'.$row[1].'</option>'->
</select>
</body>
</html>
This should work.
<?php
require_once('dbconnect.php');
$selsql="SELECT catno,catname FROM category";
$res=mysqli_query($con,$selsql);
if ($res == '')
{
echo "No connection";
die(mysqli_error($con));
}
?>
<html>
<head>
<title>Drop down list </title>
<meta charset="UTF-8">
<meta name="viewport">
</head>
<body>
<select name="categories" style="width:250px;" onchange="this.form.submit();">
<?php while($row=mysqli_fetch_assoc($res)) {?>
<option value="<?php echo $row['catno'];?>"><?php echo $row['catname'];?></option>
<?php } ?>
</select>
</body>
</html>
I am new to PHP coding. I have different preferences for the user to select from my html page. I want to retrieve all the check boxes selected by the user and display the hotel names which have all those preferences in them. For example if a user selects "Roof top", "Sea side" and "Swimming pool" check boxes, then the hotels against which their is a 1 placed in the respective columns in the mytrip.db database must be retrieved all at once and get displayed. My code takes only one checkbox value and displays the hotel name against that only. I want to display the hotels that contain all the preferences.
My code is below:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>PHP: Get Values of Multiple Checked Checkboxes</title>
<link rel="stylesheet" href="css/php_checkbox.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP: Get Values of Multiple Checked Checkboxes</h2>
<select id="mySelect" name="list">
<option selected>Select a place</option>
<option value="1">Lahore</option>
<option value="2">Dubai</option>
<option value="3">New York</option>
<option value="4">Canberra</option>
<option value="5">London</option>
</select>
<form action="php_checkbox.php" method="post">
<label class="heading">Select Your Preferences:</label>
<input type="checkbox" name="check_list[]" value="Swimming pool"><label>Swimming pool</label>
<input type="checkbox" name="check_list[]" value="Roof top"><label>Roof top</label>
<input type="checkbox" name="check_list[]" value="Sea side"><label>Sea side</label>
<input type="submit" name="submit" Value="Submit"/>
</html>
<?php include 'checkbox_value.php';?>
</form>
</div>
</div>
</body>
</html>
checkbox_value.php code is below:
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('mytrip.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
if(isset($_POST['submit'])){
if(!empty($_POST['check_list'])) {
// Counting number of checked checkboxes.
$checked_count = count($_POST['check_list']);
echo "You have selected following ".$checked_count." option(s): <br/>";
$prefarray=array();
$i=0;
// Loop to store and display values of individual checked checkbox.
foreach($_POST['check_list'] as $selected) {
$prefarray[$i]= $selected;
echo "<p>".$prefarray[$i] ."</p>";
echo "<p>".$selected ."</p>";
$i++;
}
echo "<p>".$i ."</p>";
$sql =<<<EOF
SELECT hotel_name from Dubai WHERE $prefarray[i]==1 AND $prefarray[i-1]==1 ;
EOF;
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "<p> <br /></p>\n";
echo "\n". $row['hotel_name'] . "\n";
}
$db->close();
echo "<br/><b>Note :</b> <span>Similarily, You Can Also Perform CRUD Operations using These Selected Values.</span>";
}
else{
echo "<b>Please Select Atleast One Option.</b>";
}
}
?>
The problem with this code is that it only displays one checkbox value if I use query
SELECT hotel_name FROM Dubai WHERE $selected==1
I tried to save the check box values selected by making an array "prefarray". But when I execute the query that I have posted in my checkbox_value.php code it gives me error of "Undefined offset 3 in prefarray". I want the data base query to have only those checkbox values that have been selected by the user. For example if the user has selected 2 out of three checkboxes then my query should look like
SELECT hotel_name FROM Dubai WHERE $checkbox==1 AND $checkbox2==1;
Any help to achieve two of these tasks will be appreciated!
I have fixed and refactored (couldn't stop myself) your code.
I have changed column names to proper ones. There was some redundant code which did nothing so I got rid of it. The main thing you were looking for is concatenating each chosen column in foreach loop. I'm also checking selected values against hard coded $hotelOptions for protection against sql injection.
Here is what I got:
checkbox_value.php:
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('mytrip.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
$hotelOptions = array('swimming_pool', 'roof_top', 'sea_side');
if (isset($_POST['submit'])) {
if (!empty($_POST['check_list']) && is_array($_POST['check_list'])) {
// Counting number of checked checkboxes.
$checked_count = count($_POST['check_list']);
echo "You have selected following ".$checked_count." option(s): <br/>";
// Loop to store and display values of individual checked checkbox.
$where = '';
foreach($_POST['check_list'] as $selected) {
echo "<p>".$selected ."</p>";
if (array_search($selected, $hotelOptions) !== false) {
$where .= " AND {$selected} = 1";
}
}
$where = substr($where, 5, strlen($where));
$sql = "SELECT hotel_name FROM Dubai WHERE {$where};";
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "<p> <br /></p>\n";
echo "\n". $row['hotel_name'] . "\n";
}
$db->close();
echo "<br/><b>Note :</b> <span>Similarily, You Can Also Perform CRUD Operations using These Selected Values.</span>";
} else {
echo "<b>Please Select Atleast One Option.</b>";
}
}
html layout:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>PHP: Get Values of Multiple Checked Checkboxes</title>
<link rel="stylesheet" href="css/php_checkbox.css"/>
</head>
<body>
<div class="container">
<div class="main">
<form action="checkbox_value.php" method="post">
<h2>PHP: Get Values of Multiple Checked Checkboxes</h2>
<select id="mySelect" name="list">
<option selected>Select a place</option>
<option value="1">Lahore</option>
<option value="2">Dubai</option>
<option value="3">New York</option>
<option value="4">Canberra</option>
<option value="5">London</option>
</select>
<p class="heading">Select Your Preferences:</p>
<input type="checkbox" name="check_list[]" value="swimming_pool" id="checkbox_1">
<label for="checkbox_1">Swimming pool</label>
<input type="checkbox" name="check_list[]" value="roof_top" id="checkbox_2">
<label for="checkbox_2">Roof top</label>
<input type="checkbox" name="check_list[]" value="sea_side" id="checkbox_3">
<label for="checkbox_3">Sea side</label>
<div>
<input type="submit" name="submit" Value="Submit"/>
</div>
<?php include 'checkbox_value.php';?>
</form>
</div>
</div>
</body>
</html>
I created a search function, where each result has 2 dependent select menus, that are populated depending on the search result.
Now when the search results are more than one, the select menus for the first result work just fine. [see link image 1]
image 1
The problem comes on the second result. When I select and option from the first select menu of the 2nd result. Instead of putting the data, on the select menu next to it, the data is placed in the second select menu of the first result.[see link image 2]
image 2
I cant seem to solve this problem. I have searched the forums here and all around the web. Can't seem to find the solution. Can someone please help. i hope i have explained the problem well enough.
My code:
Index.php
<!DOCTYPE html>
<?php
include("search.php");
?>
<html>
<head>
<title>Search and Drop</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
</head>
<body>
<form action="index.php" method="POST">
<input type="search" name="search" autocomplete="off" />
</form>
<?php product(); ?>
</body>
<script type="text/javascript" src="ajax.js"></script>
</html>
search.php
<!DOCTYPE html>
<?php
include("dbcon.php");
?>
<html>
<?php
function product() {
include("dbcon.php");
if (isset($_POST['search']))
{
$str = $_POST['search'];
$keywords = preg_replace("#[^0-9a-z]#i","", $str);
$query = "SELECT * FROM product WHERE product LIKE '%$keywords%'";
$result = mysqli_query($conn,$query);
$count = mysqli_num_rows($result);
if ($count > 0)
{
while($row = mysqli_fetch_array($result))
{
echo '<option value="$row["pro_id"]">'.$row["product"].'</option>';
containers($row['pro_id']);
}
}else
echo "Nothing";
}
}
function containers($parent_id) {
?>
<select id="containers" onchange="getSizes(this.value)">
<option value="0">Choose</option>
<?php
include ('dbcon.php');
$select = mysqli_query($conn, "SELECT * FROM product, container
WHERE ($parent_id = product.pro_id) AND ($parent_id = container.pro_id)");
?>
<?php
while ($row = mysqli_fetch_assoc($select)) {
?>
<option value="<?php echo $row["con_id"]; ?>"><?php echo $row["container"]; ?></option>
<?php
}
?>
</select>
<select id="sizes" onchange="getQuan(this.value);"></select>
<?php
}
?>
</html>
get_sizes.php
<!DOCTYPE html>
<html>
<?php
include("dbcon.php");
$query = "SELECT * FROM sizes WHERE con_id='".$_POST["con_id"]."'";
$result = $conn->query($query);
?>
<option value="0">Choose</option>
<?php
while ($rs=$result->fetch_assoc()) {
?>
<option value="<?php echo $rs["size_id"]; ?>"><?php echo $rs["sizes"]; ?></option>
<?php
}
?>
</html>
ajax.js
//function to show and hide sizes select menu
$(document).ready(function(){
$('#containers').change(function() {
var value = $(this).val();
if (value == 0) {
$('#sizes').hide();
$('#quantity').hide();
}else {
$('#sizes').show();
}
});
});
//function to pull data from database onto sizes select menu
function getSizes(val) {
$.ajax({
type:"POST",
url:"get_sizes.php",
data:'con_id='+val,
success: function(data){
$("#sizes").html(data);
$("#quantity").html('<option>Choose<option>');
}
});
}
this code run but when test it .. the data not correct i select data from database and i make it in array ad show it id by select tag but when select any id and submit .. example i select 5 and click on submit the record will delete is 2 not 5
<?php
require_once "config.php";
$qid="select id from info_user";
$arrayid=array();
$result=mysql_query($qid);
while($res=mysql_fetch_array($result)){
$arrayid[]=$res['id'];
}
var_dump($arrayid);
if(isset($_POST['sub'])){
$id=$_POST['id'];
$q="delete from info_user where id=$id ";
$qq=mysql_query($q);
if($qq){
echo "you delete record ";
}
else{
echo "error in deleting";
}}
?>
<html>
<head>
<title>delete</title>
</head>
<form action="delete.php" method="post">
<select name="id"><?php for($i=0;$i<count($arrayid);$i++){?>
<option value="<?php echo $i;?>"><?php echo $arrayid[$i];} ?></option></select> <br />
<input type="submit" name="sub" />
</form>
</html>
I think that problem is in value for the options.
Try changing option line to
<option value="<?php echo $arrayid[$i];?>"><?php echo $arrayid[$i];} ?></option></select> <br />
Your <option> markup is wrong. Make your markup like this;
<select name="id">
<?php for ($i = 0; $i < count($arrayid); $i++) { ?>
<option value="<?php echo $i; ?>"><?php echo $arrayid[$i]; ?></option>
} ?>
</select>
Tip: You'll find debugging easier if you indent your code. IDE's generally have this option. NetBeans is my favourite.
Instead of sending the ids, you're sending an array key associated to the id.
For instance, assume that: $arrayid = array(10, 11, 12);.
This is equivalent to: $arrayid = array(0 => 10, 1 => 11, 2 => 12);.
You'll see the options 10, 11 and 12, but you'll send either 0, 11 or 12, because that's what you're setting to the options values:
<select name="id">
<option value="0">10</option>
<option value="1">11</option>
<option value="2">12</option>
</select>
If you select the option "11", the SQL statement to delete an entry will be:
delete from info_user where id=1
I did not test this code and I'm assuming the ids are integers, but try it:
<?php
require_once "config.php";
$qid = "select id from info_user";
$arrayid = array();
$result = mysql_query($qid);
while( $res = mysql_fetch_array($result) ){
$arrayid[] = $res['id'];
}
if( isset($_POST['sub']) ){
$id = (int)$_POST['id']; // make sure it's an integer to avoid SQL injections
$q = "delete from info_user where id=$id";
$qq = mysql_query($q);
if( $qq ) {
$error = "you delete record ";
} else {
$error = "error in deleting";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>delete</title>
</head>
<body>
<?php
if( isset($error) ) :
echo '<p>', htmlspecialchars($error), '</p>';
elseif( !empty($arrayid) ) :
var_dump($arrayid);
endif;
?>
<form action="delete.php" method="post">
<select name="id">
<?php foreach($arrayid as $id): ?>
<option value="<?php echo (int)$id;?>">
<?php echo (int)$id; ?>
<?php endforeach; ?>
</option>
</select>
<br />
<input type="submit" name="sub" />
</form>
</body>
</html>
I am trying to use the $_POST feature or $_SESSION feature of php to get an array based off form data from a previous pagepage. Whenever I try using $_SESSION I get the error:"The script tried to execute a method or access a property of an incomplete object." Here is an idea of what I'm trying to do. Any help would be great and thanks in advance!
<?php
// initialize a session
include 'hoteldetails.php';
session_start();
?>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<center><h1>Room Reserves</h1>
<h2>Search</h2></center>
<h3>Login <br/> Sign up</h3>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
Please enter City, State or Zipcode:<input type="text" name="location">
<input type="date" name="startdate" value="startdate">
to <input type="date" name="enddate" value="enddate">
<br/>
Minimum price:<select name="minimumprice">
<option value="0">No Minimum</option>
<option value="49">$50</option>
<option value="99">$100</option>
<option value="199">$200</option>
</select>
Maximum price:<select name="maximumprice">
<option value="9999">No Maximum</option>
<option value="101">$100</option>
<option value="201">$200</option>
<option value="301">$300</option>
</select>
Beds:<select name="beds">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
Bathrooms:<select name="baths">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
<input type="submit" name="Search" value="Search">
</form>
<?php
try{
$dbconn= pg_connect("host=localhost port=5432 dbname=roomReserves user=superUser password=F3Poriginal");
}
catch(PDOException $e){
echo $e->getMessage();
}
if(isset($_POST['Search'])){
if($_POST['startdate']==null || $_POST['enddate']==null || $_POST['location']==null){
echo "One or more fields are empty, please try again.";
}
else{
$query = "SELECT * FROM hotellist WHERE zip=75007";
$rs = pg_query($dbconn, $query) or die("Cannot execute query: $query\n");
// $hotelsdetail=array();
$_SESSION['hotelsdeets']=array();
$hotelpos=0;
while ($row = pg_fetch_row($rs)) {
$serverInfo= explode(" ",$row[2]);
$hotelsdb= pg_connect("host=$serverInfo[0] port=$serverInfo[1] dbname=$serverInfo[2] user=$serverInfo[3] password=$serverInfo[4]");
$queryresult = "SELECT * FROM hotelinfo where beds= CAST('".$_POST['beds']."' AS INT) AND baths= CAST(baths='".$_POST['baths']."' AS INT) AND price BETWEEN CAST('".$_POST['minimumprice']."' AS INT) AND CAST('".$_POST['maximumprice']."' AS INT)";
$hotelrs = pg_query($hotelsdb, $queryresult) or die("Cannot query hotel info: $queryresult\n");
$matchesquery=false;
while($hotelrow=pg_fetch_row($hotelrs) && $matchesquery==false){
$matchesquery=true;
$date = $_POST['startdate'];
$endDate= $_POST['enddate'];
$hotelroomrs=pg_fetch_row($hotelrs);
$hotelroom=$hotelroomrs[0];
$hotelprice=$hotelroomrs[1];
while ($date < $endDate && $matchesquery==true && $hotelroomrs[0]!=null) {
$isavail="SELECT * FROM hotelinfo where roomnumber= CAST('".$hotelroom."' AS INT) AND date= CAST('".$date."' AS date)";
$roomexists=pg_query($hotelsdb, $isavail);
$roomdets=pg_fetch_row($roomexists);
if($roomdets[0]==null){
$matchesquery=false;
}
$date = date ("Y-m-d", strtotime("+1 day", strtotime($date)));
}
if($matchesquery==true && $hotelroomrs[0]!=null){
$_SESSION['hotelsdeets'][$hotelpos]=new hoteldetails();
$_SESSION['hotelsdeets'][$hotelpos]->sethotelinfo($row);
$_SESSION['hotelsdeets'][$hotelpos]->setprice($hotelprice);
$hotelpos++;
}
}
pg_close($hotelsdb);
}
header("Location: ./searchresults.php");
}
}
pg_close($dbconn);
?>
<?php
session_start();
?>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<center><h1>Room Reserves</h1>
<h2>Results</h2></center>
<h3>Login<br/>Sign up</h3>
</head>
<body>
<?PHP
//$searchinfo->$hotelsdetail[0]->sethotelinfo(1);
echo $_SESSION['hotelsdeets'][0]->gethotelinfo()[1];
?>
</body>
</html>
class hoteldetails {
private $hotelinfo;
private $price;
public function sethotelinfo($hotelinfo){
$this->hotelinfo=$hotelinfo;
}
public function setprice($price){
$this->price=$price;
}
public function gethotelinfo(){
return $this->hotelinfo;
}
public function get($var){
return $this->{$var};
}
}
Once again, THANKS!
As a starting point, you need to open and close the php tags:
<?PHP
session_start();
?>
<html>
<head>
</head>
<body>
<?PHP
$colors=array();
array_push($colors, "green");
array_push($colors, "white");
array_push($colors, "yellow");
array_push($colors, "black");
$_SESSION['color']=$colors;
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="submit" name="Search" value="Search">
</form>
<?php
if(isset($_POST['Search'])){
header("Location: page2.php");
}
?>