Have to value else print nothing in php/(postgreSQL/MySQL) - php

Here is my code. I have to print the whole state name in one column. if any value is there it should print some value in front of that state name otherwise it should print null or zero or empty in front of that state.. state is one table and asset_stage1 is another table. All state name should display on the selection of the date. attaching my current screenshot also. I have to match with state code if state code is there in the state and same state code value is present in asset stage1 it should display value otherwise it should display null
<div class="container">
<form action="<?php $_PHP_SELF ?>" method="POST">
<input type="date" name="timestamp" class="btn" placeholder="Enter date"/>
<input type="submit" name="search" class="btn" value="Search by date">
</form>
<table>
<tr>
<th>Date</th>
<th>State Name</th>
<th>Asset Download Stage1</th>
<th>Asset Download Stage2</th>
<br>
<?php
ini_set("display_errors","Off");
$pgcon = pg_connect("dbname=nrega host=localhost port=5432 user= postgres");
if(isset($_POST['search']))
{
$timestamp = $_POST['timestamp'];
//Stage 1
$query1 = " select count(*) as stage1, a.state_code,b.state_name,
timestamp::date from asset_stage1 a,states b where timestamp::date >= '$timestamp' and
a.state_code not in ('06') and a.state_code=b.state_code group by 2,3,4 order by b.state_name
";
//Stage 2
$query2 = "select count(*) as stage2, a.state_code,b.state_name, timestamp::date from asset_stage2 a,
states b where timestamp::date >= '$timestamp' and
a.state_code not in ('06') and a.state_code=b.state_code group by 2,3,4 order by b.state_name
";
// state_code
$query4 = "select distinct state_name, state_code from states order by state_name";
$result4 = pg_query($pgcon,$query4);
$m=0;
global $state_code;
while($row = pg_fetch_array($result4))
{
$state_name[$m]=$row ['state_name'];
$state_code[$m]= $row ['state_code'];
$m++;
}
$result = pg_query($pgcon,$query1);
$i=0;
while($row = pg_fetch_array($result))
{
if($state_code[$i] == $row['state_code'])
{
//echo $row['state_code'];
$stage1_count[$i]=$row ['stage1'];
}
else
{
$stage1_count[$i]=0;
}
$date_store[$i]=$row ['timestamp'];
$i++;
}
$result2 = pg_query($pgcon,$query2);
$j=0;
while($row = pg_fetch_array($result2))
{
if($state_code[$j] == $row['state_code']){
$stage2_count[$j]=$row ['stage2'];
}
else
{
$stage2_count[$j]= 0;
}
//$stage2_count[$j]=$row ['stage2'];
$j++;
}
$len= sizeof($state_name);
for($i=0;$i<=33;$i++)
{
?>
<tr>
<td><?php echo $timestamp;?></td>
<td><?php echo $state_name[$i];?></td>
<td><?php echo $stage1_count[$i];?></td>
<td><?php echo $stage2_count[$i];?></td>
</tr>
<?php
}
}
?>
</table></div>

For table asset_stage1:
SELECT state_name, count(*) FROM states, asset_stage1 WHERE states.state_code=asset_stage1.state_code GROUP BY state_name;
For table asset_stage2:
SELECT state_name, count(*) FROM states, asset_stage2 WHERE states.state_code=asset_stage2.state_code GROUP BY state_name;

Related

Can i use AND operator 2 times in SQL?

So i been trying this for a week, which is the value inside the table is missing after i select submit button for the date
So when enter the this page it will display
'SELECT * FROM attendance WHERE lect_id = 'CS0198289' AND dateofupdate LIKE '%0%' AND codeofsubject = 'CSNB214' ORDER BY studname ASC'
which is it will display my lect_id, dateofupdate=0, and the code of subject. When I select the submit(SELECT) button which is to date it will become
'SELECT * FROM attendance WHERE lect_id = 'CS0198289' AND dateofupdate LIKE '%2019-01-23%' AND codeofsubject = '' ORDER BY studname ASC'
so can anyone help me? much appreciate
<?php
$connect = mysqli_connect ("localhost","root","","ubas")
or die("Cannot connect to server".mysqli_error($connect));
if (!isset($_POST['dates'])){
$_POST['dates']=0;
}
$id = #$_POST["lect_id"];
$codeofsubject = #$_POST['code'];
$display = "SELECT * FROM attendance WHERE lect_id = '$_SESSION[id]' AND dateofupdate LIKE '%".$_POST['dates']."%'
AND codeofsubject = '$codeofsubject' ORDER BY studname ASC";
echo $display;
$result = mysqli_query ($connect,$display)
or die ("Cannot view due to".mysqi_error($connect));
echo"<form role='form' method='post'>
<div class='form-group'>
<label>Date</label>
<input style='width:180px; display:inline' class='form-control' type='date' name='dates' id='dates'>
<button type='submit' style='display:inline' name='select'>Select</button>
</div>
</form>";
echo"
<form method = post action = updateattend.php>
<table width='100%' class='table table-striped table-bordered table-hover' id='dataTables-example'>
<thead>
<tr>
<th><center>Date</center></th>
<th><center>Student Name</center></th>
<th><center>Student ID</center></th>
<th><center>View</center></th>
<th><center>Attend Status</center></th>
</tr>
</thead>";
while($row = mysqli_fetch_array($result,MYSQLI_NUM))
{
$attendid = $row [0];
$studname = $row [1];
$studid = $row [2];
$lect_id = $row [3];
$codeofsubject = $row [4];
$date = $row [5];
$dateofenroll = $row [6];
$attendstatus = $row [7];
echo"<tbody>
<tr>
<td><center>$date</center></td>
<td><center>$studname</center></td>
<td><center>$studid</center></td>
<td align = center>
<a class ='btn-warning btn' href ='updatestud.php?id=".$row['2']."'>VIEW</a>
</td>";
echo"
<td align = center>
<select class = 'form-control' name = 'attendstatus[]'>
<option value='$attendstatus' selected>$attendstatus</option>";
if($attendstatus =="Attend")
{
echo "<option value='Not Attending'>Not Attending</option>
<option value='Not Attending with Reason'>Not Attending with Reason</option>";
}
elseif ($attendstatus =="Not Attending") {
echo"<option value='Attend'>Attend</option>
<option value='Not Attending with Reason'>Not Attending with Reason</option>";
}
else{
echo"<option value='Attend'>Attend</option>
<option value='Not Attending'>Not Attending</option>";
}
echo"</select>
</td>
</tr>
</tbody>";
}
?>
</table>
There is no limit of AND operator in SQL statement. You can use as many ANDs as you need but your logic should be correct in the sense of SQL statement.
For Example
SELECT something FROM something WHERE something=something AND something=something AND something=something AND something=something;
So, the part something=something becomes a separate logical statement that is separately evaluated from other something=something statements based on the AND operator. But keep in mind that the whole statement above is a single statement.

Php mysql search option

I'm currently self studying PHP and right now, I'm trying to create a simple library system. And now, I'm having some trouble with the search option. I believe that my query and conditional statement are correct but I still can't show the output.
This are the codes:
<html>
<link rel="stylesheet" type="text/css" href="style.css">
<head>Home Page!</head>
<h1>List of Books</h1>
<?php include 'show.php'; ?>
<?php
require 'dbcon.php';
$Terror = $Aerror = $Derror = $Cerror = $matches = "";
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$T = $_POST['title'];
$A = $_POST['Author'];
$D = $_POST['Desc'];
$C = $_POST['Category'];
$X = $_POST['Opt'];
$del_sql = "delete from a where Title = '".$T."' AND Author = '".$A."' ";
"delete from b where Title = '".$T."' AND Description = '".$D."' AND Category = '".$C."' ";
if($X == 'Add'){
$in_sql = "insert a (Title, Author) values ('".$T."', '".$A."'); insert b (Title, Description, Category) values ('".$T."', '".$D."', '".$C."')";
if(empty($T) || empty($A) || empty($D) || empty($C)){
if(empty($A)) $Aerror = "Fill up Author";
if(empty($T)) $Terror = "Fill up Title";
if(empty($D)) $Derror = "Fill up Description";
if(empty($C)) $Cerror = "Fill up Category";
}
else if(mysqli_multi_query($dbcon, $in_sql)){
echo "New recored added";
}
}
else if ($X == 'Del'){
if (mysqli_multi_query($dbcon, $del_sql)){
echo "Record deleted";
}
}
else if ($X == 'Search'){
$sea1_sql = "select count(Title) from a where Title = '".$T."'";
$sea_sql = mysqli_multi_query($dbcon, "select * from a where Title = '".$T."' AND Author = '".$A."'");
"select Description, Category from b where Title = '".$T."' AND Description = '".$D."' AND Category = '".$C."'";
if (mysqli_query($dbcon, $sea1_sql) > 0){
while ($row = mysqli_fetch_array($sea_sql)){
echo "<table class = fix>";
echo "<tr><th>Title</th> <th> ". $row['Title'] . " </th></tr>";
echo "<tr><th>Author </th> <th> ". $row['Author'] . " </th></tr>";
echo "<tr><th>Description </th> <th> ". $row['Description'] . " </th></tr>";
echo "<tr><th>Category </th> <th> ". $row['Category'] . " </th></tr>";
echo "</table><br>";
}
}
else if (mysqli_query($dbcon, $sea1_sql) < 0){
echo "Can't find data!";
}
}
}
?>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<br>Title: <input type="text" name="title"> <?php echo $Terror; ?><br>
Author: <input type="text" name="Author"><?php echo $Aerror; ?><br>
Description: <input type="text" name="Desc"><?php echo $Derror; ?><br>
Category: <input type="text" name="Category"><?php echo $Cerror; ?><br>
<select name="Opt">
<option disabled selected>N/A</option>
<option value='Add'>Add</option>
<option value='Edit'>Edit</option>
<option value='Del'>Del</option>
<option value='Search'>Search</option>
</select><br>
<input type="submit" name="submit">
</form>
</body>
</html>
This is wrong:
if (mysqli_query($dbcon, $sea1_sql) > 0){
myqli_query() doesn't return the value of count(Title). You need to fetch the row.
$sea1_result = mysqli_query($dbcon, $sea1_sql);
$row = mysqli_fetch_assoc($sea1_result);
if ($row['count(Title)'] > 0) {
You're also using mysqli_multi_query() incorrectly. It doesn't return a mysqli_result object that you can fetch results from, it returns a boolean that indicates whether the first query was successful or got an error. You need to call mysqli_use_result() to get the results of each query, and then call mysqli_fetch_array() on this.
But it looks like you shouldn't be using mysqli_multi_query() at all. You want to get the rows from a and b for the same title together, not all a rows before all b rows. You should join the two tables:
$sea_result = mysqli_query("SELECT a.*, b.Description, b.Category
FROM a JOIN b ON a.Title = b.Title
WHERE a.Title = '$T' AND a.Author = 'A'
AND b.Description = '$D' AND b.Category = '$C'");

Pass PHP array through Select Option Fields

I am writing a basic CMS system and have come across something which should be seemingly simple -but is beginning to frustrate me.!
I am trying to pass an array through a select option field to populate a list of categories in which I can save a post.
I have a 'posts' form which comprises of 3 fields. Title, content and Category ID (CatID).
When the user creates a post, they can select the category they wish to assign the post assigned to by using a drop down list - (this is populated by using a different form).
So the technical bit; -
MySQL DB:-
categories = catname (char60 PRIMARY), catid (INT10, AI)
posts = id (bigint20 PRIMARY), catid (int10 PRIMARY), title (text), content (varchar255)
Example of categories populates: catname = Home / catid = 1 ...etc
Output.php ;
<?php
function display_post_form($post = '') {
$edit = is_array($post);
?>
<form action="<?php echo $edit ? 'edit.php' : 'add.php' ; ?>" method="post">
<table border="0">
<tr>
<td> Title:</td>
<td> <input type="text" name="title" value="<?php echo $edit ? $post['title'] : '' ; ?>" size="60" /> </td>
</tr><tr>
<td> Content:</td>
<td> <textarea id="editor1" name="content" value="<?php echo $edit ? $post['content'] : '' ; ?>"> </textarea> </td>
</tr><tr>
<td> Category:</td>
<td><select name="catid">
<?php
$cat_array = get_categories($catid, $catname);
foreach($cat_array as $thiscat) {
echo "<option value=\"".$thiscat['catid']."\" ";
if (($edit) && ($thiscat['catid'] == $post['catid'])) {
echo " selected";
}
echo ">".$thiscat['catname']."</option>";
}
?>
</select>
</td>
</tr><tr>
<td> Button:</td>
<td <?php if (!$edit) { echo "colspan=2"; } ?> align="center">
<?php
if ($edit)
echo "<input type=\"hidden\" name=\"_id\" value=\"". $post['id'] ."\" />";
?>
<input type="submit" value="<?php echo $edit ? 'Update' : 'Add' ; ?> Post" />
</form></td>
</td>
</tr>
</table>
</form>
<?php
}
?>
Functions.php ;
function get_categories($catid, $catname) {
$conn = db_connect();
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL " .mysqli_connect_error();
}
$sql = "SELECT catname, catid FROM categories";
$result = mysqli_query($conn, $sql) or die(" Could not query database");
while($row = mysqli_fetch_assoc($result)) {
printf("\n %s %s |\n",$row["catname"],$row["catid"]);
}
mysqli_close($conn);
}
I am able to call in the 'get_cattegories()' function which generates a flat data of categories and their respective id's. I then combined this with the Select Option Field in the Output.php file and it doesn't generate anything.
Can anyone give some useful tips or advice? Many thanks :)
You are not returning the array but printing a string to the output. Change printf to return:
function get_categories($catid, $catname) {
$conn = db_connect();
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL " .mysqli_connect_error();
}
$sql = "SELECT catname, catid FROM categories";
$result = mysqli_query($conn, $sql) or die(" Could not query database");
$categories = array();
while($row = mysqli_fetch_assoc($result)) {
$categories[] = $row;
}
mysqli_close($conn);
return $categories;
}
Also I agree for the comments to your question. The arguments are useless.
You also may refactor the code, actually... alot. Move the mysql_connect() to the other place, probably at the beginning of your script.
I suggest to use some frameworks. I think KohanaPHP will be a good start. You will learn about architecture and some design patterns. Keep the good work and improve your skills ;-)

SQL query in MySql_Fetch_Array

When I show this PHP on browser I couldn't get any value to table. My table is empty.
<?php
$sql = "select * from worksets where 'groupid'='$targetid'";
$query = mysql_query($sql);
$kadro=$_GET['kadro'];
if((mysql_num_rows($query) > 0)) {
while($result = mysql_fetch_array($query)) {
$groupid = $result[0];
$groupname = $result[2];
$sql2 = "select flag from havestatus where kadroid='$kadro' and yid='$groupid'";
$query2 = mysql_query($sql2);
if((mysql_num_rows($query2) == 0)) {
$sql3 = "insert into havestatus values('$kadro','$yid',0)";
} else {
$select='selected';
}
?>
<tr>
<td width='50%'><?php echo $groupname;?></td>
<td></td>
<td width='20%'><input type="checkbox" name="bev" checked="<?php echo $select; ?>"></td>
</tr>
<?php
}
}
?>
If I change code in simple way like;
It shows some values and unfunctional checkbox.
I need to get some values from database and fill checkboxs according to 0 or 1 from database
and I have to insert all check box values with one form submit button to database as different rows for every check box.
<?php
$sql = "select * from worksets where groupid='$targetid'";
$query = mysql_query($sql);
if((mysql_num_rows($query) > 0)) {
while($result = mysql_fetch_array($query)) {
$groupid = $result[0];
$groupname = $result[2];
?>
<tr>
<td width='50%'><?php echo $groupname;?></td>
<td></td>
<td width='20%'><input type="checkbox" name="bev"></td>
</tr>
<?php
}
}
?>
it is work after 'groupid'='$targetid'" to groupid='$targetid'"

Checkbox Form with Submit Button doesn't echo values from database php html sql

I'm new to php, html, and mysql. I have a database with a username, product, and price they want to sell the product for. The code is for a checkbox form with a submit button that works like a price filter, that when submitted it's supposed to echo the username, product, and price that matches the corresponding checkbox. . If a user selects a checkbox labeled, "0-25" OR "100 & above", and clicks the submit button it supposed to echo all users that have items in that specific price range. I've looked online an tried to manipulate somewhat close to what I have. Could someone please help me out or give me insight on how to do this? Any help is appreciated
Here is my checkbox form.
<form action="pricefilter.php" method="post">
<br><b>Filter By Price:</b><br><br>
<input type="checkbox" name="$0-$25[]" id="Price" value="0-25"/> $0-$25<br><br>
<input type="checkbox" name="$25-$50[]" id="Price" value="25-50"/> $25-$50<br><br>
<input type="checkbox" name="$50-$100[]" id="Price" value="50-100"/> $50-$100<br><br>
<input type="submit" name="submit" value="Submit" />
</form>
Here is the code to my php file.
<?php
mysql_connect ("localhost", "root","root") or die (mysql_error());
mysql_select_db ("xuswapuser");
$priceFilter = $_GET['priceFilter'];
$filteredResponse = array ();
foreach($priceFilter as $range)
{
if($range == 025)
{
$query = "select * from Books where Price <= 25";
$sql = mysql_query($query);
array_push($filteredResponse, $sql);
}
if($range == 2550)
{
$query = "select * from Books where Price >= 25 AND Price <=50";
$sql = mysql_query($query);
array_push($filteredResponse, $sql);
}
if($range == 5075)
{
$query = "select * from Books where Price >= 50 AND Price <=75";
$sql = mysql_query($query);
array_push($filteredResponse, $sql);
}
if($range == 75100)
{
$query = "select * from Books where Price >= 75 AND Price <=100";
$sql = mysql_query($query);
array_push($filteredResponse, $sql);
}
if($range == 100)
{
$query = "select * from Books where Price >= 100";
$sql = mysql_query($query);
array_push($filteredResponse, $sql);
}
}
?>
<html>
<head>
<title>
XUSWAP
</title>
<script type="text/javascript" src="sorttable.js"></script>
</head>
<body style="margin: 0; padding: 0;">
<div id="header" style="background-color:#339900;height:157px;width:100%;position:relative;"> <!--header area-->
<form id="headerForm" name="headerForm" method="Post" action="" align="right">
<input type="image" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSN3XIAe50cjq5Cf91GbAywPkChmI5HOAqYxgmRN8F5OhW7I_RT5Q" alt="Placeholder" align="left" width="150" height="150">
<br><br><br>
<input type="text" name="searchInput"id="search" style="width:500px;"/>
<input type="submit" name="searchButton" id="searchButton" value="Search" />
<input type="submit" name="logoutButton" id="logoutButton" value="Logout"/>
<br><br><br>
</form>
</div>
<div id="background" style="background-color:#FFD700;height:100%; width:100%;">
<div id = "pageContent"></div>
<div id="background" style="background-color:#FFD700;height:100%; width:100%;">
<blockquote>
<blockquote>
<blockquote>
<blockquote>
<blockquote>
<blockquote>
<blockquote>
<p>Books </p>
</blockquote>
</blockquote>
</blockquote>
</blockquote>
</blockquote>
</blockquote>
</blockquote>
<blockquote>
<table class="sortable" width="940" height="52" border="0">
<tr>
<td width="200" id="sortable">Username</td>
<td width="253"> Product</td>
<td width="220">Condition</td>
<td width="249">Price</td>
</tr>
<?php do { ?>
<tr>
<td><?php echo $range['id']; ?></td>
<td><?php echo $range['Product']; ?></td>
<td><?php echo $range['Condition']; ?></td>
<td><?php echo $range['Price']; ?></td>
</tr>
<?php } while ($range = mysql_fetch_assoc($sql)); ?>
</table>
Ouch. :)
What does IsChecked() function do? Is it defined, or you wanted isset() ?
Don't name your fields with the $ dollar sign.
Don't make them arrays, if they are not, you are using the group once, so it shouldn't have [] after it
To access posted name field, you need $_POST superglobal, you cannot access it directly by its name:
-
<input name="asd">
would be accessed if posted in PHP like:
$_POST['asd']
and the check if it's posted would be:
if(isset($_POST['asd']) { ...
By the convetion of using $row[] array, I assume you want to print a query results. In order to print results, you need to fetch them and iterate through them. In your way it would be:
while ($row = mysql_fetch_assoc($sql)) { ...
However mysql_* functions are deprecated, and before you get used to them, better switch to mysqli_* or PDO libraries.
this is just simple code for you to follow, you can loop through all possibilities by putting the checked values into an array and performing the query through a foreach()
<input type="checkbox" name="priceFilter[]" value="025">
<input type="checkbox" name="priceFilter[]" value="2550">
// etc.
<?php
$priceFilter = $_POST['pricFilter']; // this is now an array
if(isset($priceFilter[025]))
{
$query25 = "select * from Books where Price <= 25";
}
if(isset($priceFilter[2550]))
{
$query2550 = "select * from Books where Price >= 25 AND Price <= 50";
}
//etc.
// then run your query if it is set
if(isset($query25))
{
$sql = mysql_query($query25);
}
// then do w/e you need to do then run subsequent possibily
?>
this is time consuming but i am just trying to get the point across to you on how to handle checkboxes in php
UPDATE
if you want to do it with a foreach:
<?php
$priceFilter = $_GET['priceFilter'];
$filteredResponse = array ();
foreach($priceFilter as $range)
{
if($range == 025)
{
$query = "select * from Books where Price <= 25";
$sql = mysql_query($query);
array_push($filteredResponse, $sql);
}
if($range == 2550)
{
$query = "select * from Books where Price >= 25 AND Price <=50";
$sql = mysql_query($query);
array_push($filteredResponse, $sql);
}
// do this for all the conditions and you can save the results in an array of arrays
}
You now have an array of your MYSQL responses based on the selections from your checkbox form. Then just parse the information however you see fit.
i ALSO SUGGEST - before moving forward to use PDO instead of mysql_ as it is legacy code
take a gander at this for PDO use

Categories