Connect WHERE clause to link - php

I need to connect a WHERE clause to a link. Here is my code:
<body>
<?php
function toiletPaper($input) {
// Clean input
return $input;
}
$username="USERNAME";
$password="PASSWORD";
$database="DATABASE";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM searchacts";
$result=mysql_query($query);
// process form when posted
$query = "SELECT * FROM searchacts";
$options['PriceLow'] = array("desc" => "Price (Low to High)","query" => " ORDER BY price ASC");
$options['PriceHigh'] = array("desc" => "Price (High to Low)","query" => " ORDER BY price DESC");
$options['NameAZ'] = array("desc" => "Name (A-Z)","query" => " ORDER BY name ASC");
$options['NameZA'] = array("desc" => "Name (Z-A)","query" => " ORDER BY name DESC");
$query = "SELECT * FROM searchacts";
$filter['partybands'] = array("desc" => "Party Bands","query" => " WHERE category='Party Bands'");
// Important: function name is made up
$cleanValue = toiletPaper($_REQUEST['value']);
if (array_key_exists($cleanValue, $options)) {
$query .= $query.$options[$cleanValue];
}
$result = mysql_query($query);
$num = mysql_num_rows($result);
echo "<a href='".$_SERVER['PHP_SELF']."'>All</a>";
foreach ($options as $key => $value) {
echo "<a href='".$_SERVER['PHP_SELF']."?value=".$key."'>".$value['desc']."</a>";
}
?>
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post' name='form_filter' >
<select name="value">
<option value="all">All</option>
<option value="PriceLow">Price (Low to High)</option>
<option value="PriceHigh">Price (High to Low)</option>
<option value="NameAZ">Name (A-Z)</option>
<option value="NameZA">Name (Z-A)</option>
</select>
<br />
<input type='submit' value = 'Re-Order'>
</form>
<?php
$i=0;
while ($i < $num) {
$image=mysql_result($result,$i,"image");
$name=mysql_result($result,$i,"name");
$category=mysql_result($result,$i,"category");
$description=mysql_result($result,$i,"description");
$stamps=mysql_result($result,$i,"stamps");
$stickmen=mysql_result($result,$i,"stickmen");
$price=mysql_result($result,$i,"price");
$view=mysql_result($result,$i,"view");
$actpagelink=mysql_result($result,$i,"actpagelink");
?>
<a href="<?php echo $actpagelink; ?>" class="searchitem">
<div class="searchimage"><img src="<?php echo $image; ?>"/></div>
<div class="searchtext">
<div class="searchname"><?php echo $name; ?></div>
<div class="searchcategory"><?php echo $category; ?></div>
<div class="searchdescription"><?php echo $description; ?></div>
</div>
<div class="searchstamps"><img src="<?php echo $stamps; ?>" /></div>
<div class="searchstickmen"><img src="<?php echo $stickmen; ?>" /></div>
<div class="searchprice"><span class="pricefrom">from</span>£<?php echo $price; ?></div>
<div class="searchview"><img src="<?php echo $view; ?>" /></div>
</a>
<?php
$i++;
}
mysql_close();
?>
</body>
So I have my clause:
elseif($_POST['value'] == 'partybands') {
$query = "SELECT * FROM searchacts
WHERE category='Party Bands'";
}
Which I need to connect to a link eg. Party Bands
How can I do that as I will have quite a lot of where clauses to filter the data.
Thanks

Use url parameters and pass in variables, then use those variables to trigger what you want the where clause to say.

I am guessing that you are trying:
http://example.com/yourscript.php?value=partybands
But finding that that does not work...
This is because you are looking for the variable value in the $_POST array.
$_POST['value'] == 'partybands'
If you want to be able to grab the value from either POST or GET you can use $_REQUEST
$_REQUEST['value'] == 'partybands'
You'll also need to modify the topmost conditional isset().
But do take seriously the cautions that others have made here with regards to security and forward compatibility.
Do not trust user data. Must be sanitized. Best way to accomplish is probably through PDO.

I recommend using an associative array and in_array to validate.
Also make sure you sanitize the input before you use it.
EDIT2:
<body>
<?php
function toiletPaper($input) {
// Clean input
return $input;
}
$username="USERNAME";
$password="PASSWORD";
$database="DATABASE";
mysqli_connect("localhost",$username,$password);
#mysqli_select_db($database) or die( "Unable to select database");
// process form when posted
$query = "SELECT * FROM searchacts";
$options['partybands'] = array("desc" => "Party Bands","query" => " WHERE category='Party Bands'");
$options['PriceLow'] = array("desc" => "Price (Low to High)","query" => " ORDER BY price ASC");
$options['PriceHigh'] = array("desc" => "Price (High to Low)","query" => " ORDER BY price DESC");
$options['NameAZ'] = array("desc" => "Name (A-Z)","query" => " ORDER BY name ASC");
$options['NameZA'] = array("desc" => "Name (Z-A)","query" => " ORDER BY name DESC");
// Important: function name is made up
$cleanValue = toiletPaper($_REQUEST['value']);
if (array_key_exists($cleanValue, $options)) {
$query .= $query.$options[$cleanValue];
}
$result = mysqli_query($query);
$num = mysqli_num_rows($result);
echo "<a href='".$_SERVER['PHP_SELF']."'>All</a>";
foreach ($options as $key => $value) {
echo "<a href='".$_SERVER['PHP_SELF']."?value=".$key."'>".$value['desc']."</a>";
}
?>
<br />
<?php
$i=0;
while ($i < $num) {
$image = mysqli_result($result,$i,"image");
$name = mysqli_result($result,$i,"name");
$category = mysqli_result($result,$i,"category");
$description = mysqli_result($result,$i,"description");
$stamps = mysqli_result($result,$i,"stamps");
$stickmen = mysqli_result($result,$i,"stickmen");
$price = mysqli_result($result,$i,"price");
$view = mysqli_result($result,$i,"view");
$actpagelink = mysqli_result($result,$i,"actpagelink");
?>
<a href="<?php echo $actpagelink; ?>" class="searchitem">
<div class="searchimage"><img src="<?php echo $image; ?>"/></div>
<div class="searchtext">
<div class="searchname"><?php echo $name; ?></div>
<div class="searchcategory"><?php echo $category; ?></div>
<div class="searchdescription"><?php echo $description; ?></div>
</div>
<div class="searchstamps"><img src="<?php echo $stamps; ?>" /></div>
<div class="searchstickmen"><img src="<?php echo $stickmen; ?>" /></div>
<div class="searchprice"><span class="pricefrom">from</span>£<?php echo $price; ?></div>
<div class="searchview"><img src="<?php echo $view; ?>" /></div>
</a>
<?php
$i++;
}
mysql_close();
?>

Related

How do I show just the first image from mysql database in php

I have the following code. How do I show the first image in the database with index of 0 for the large image display at end of the code? Right now it is showing the last image in the database.
<div id="imgWheel" class="treatmentContainer">
<?php
$query = "SELECT * FROM images WHERE user = 0 ORDER BY id;";
$result = $mysqli->query($query);
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$product = $row["product"];
$room = $row["room"];
$style = $row["style"];
$tags = $row["tags"];
$src = $row["url"];
$dataid = $row["id"];
$imgClass = "";
if (in_array($src, $favourites)) {
$imgClass = " favourite";
}
echo "<div class='treatment$imgClass' data-url='$src' data-product='$product' data-room='$room' data-style='$style' data-tags='$tags' data-number='$dataid' id='pic_$dataid' >";
echo "<img src='$src' crossorigin='anonymous'/>";
echo "</div>";
}
?>
</div> <!-- close imgWheel -->
<!-------- Large Image Display------- -->
<div id="display">
<img id="mainImage" src="<?php echo $src ?>" />
</div>
Your result set is alreadyx ordered by id, so you need only a variable, to be filled once with the first imageurl
<div id="imgWheel" class="treatmentContainer">
<?php
$bigpictureurl = "";
$query = "SELECT * FROM images WHERE user = 0 ORDER BY id;";
$result = $mysqli->query($query);
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$product = $row["product"];
$room = $row["room"];
$style = $row["style"];
$tags = $row["tags"];
$src = $row["url"];
$dataid = $row["id"];
if (empty($bigpictureurl)) {
$bigpictureurl = $src ;
}
$imgClass = "";
if (in_array($src, $favourites)) {
$imgClass = " favourite";
}
echo "<div class='treatment$imgClass' data-url='$src' data-product='$product' data-room='$room' data-style='$style' data-tags='$tags' data-number='$dataid' id='pic_$dataid' >";
echo "<img src='$src' crossorigin='anonymous'/>";
echo "</div>";
}
?>
</div> <!-- close imgWheel -->
<!-------- Large Image Display------- -->
<div id="display">
<img id="mainImage" src="<?php echo $bigpictureurl ?>" />
</div>
You just need to update your SQL query, just add LIMIT 1. This will limit the result just to 1 record and as you have ORDER id ASC, it will show the first record of the given user (as per you it is 0).
$query = "SELECT * FROM images WHERE user = 0 ORDER BY id ASC LIMIT 1;";
A quick and dirty solution is to save your first image in some separate variables, for example like this:
$isFirst = true;
$firstImageSrc = "";
$result = ....;
while (...) {
// set your $product, $room etc here
if ($isFirst) {
$isFirst = false;
$firstImageSrc = $src;
}
}
echo ...
?>
</div> <!-- close imgWheel -->
<!-------- Large Image Display------- -->
<div id="display">
<img id="mainImage" src="<?php echo $firstImageSrc ?>" />
</div>
A much more elegant solution would be to create an array with all your images, so that you can separate your php from your html. I will refactor your code below, and fix your first image problem as well:
<?php
$images = [];
$idx = 0;
$query = "SELECT * FROM images WHERE user = 0 ORDER BY id;";
$result = $mysqli->query($query);
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$images[$idx]["product"] = $row["product"];
$images[$idx]["room"] = $row["room"];
$images[$idx]["style"] = $row["style"];
$images[$idx]["tags"] = $row["tags"];
$images[$idx]["src"] = $row["url"];
$images[$idx]["dataid"] = $row["id"];
$images[$idx]["imgClass"] = "";
if (in_array($src, $favourites)) {
$images[$idx]["imgClass"] = " favourite";
}
$idx++;
}
?>
<div id="imgWheel" class="treatmentContainer">
<?php foreach ($images as $image) { ?>
<div class='treatment<?=$image["imgClass"]?>' data-url='<?=$image["src"]?>' data-product='<?=$image["product"]?>' data-room='<?=$image["room"]?>' data-style='<?=$image["style"]?>' data-tags='<?=$image["tags"]?>' data-number='<?=$image["dataid"]?>' id='pic_<?=$image["dataid"]?>' >
<img src='<?=$image["src"]?>' crossorigin='anonymous'/>
</div>
<?php } ?>
</div> <!-- close imgWheel -->
<!-------- Large Image Display------- -->
<div id="display">
<img id="mainImage" src="<?=$images[0]["src"]?>" />
</div>
Since you have all of that in your WHILE statement, I assume you want to echo all those records. And then at the end show the 1st pic. So for the "Large Image Display," give this a try:
<div id="display">
$query = "SELECT * FROM images WHERE user = 0;";
$result = $mysqli->query($query);
$row = $result->fetch_array(MYSQLI_ASSOC)
$src = $row["url"];
<img id="mainImage" src="<?php echo $src ?>" />
</div>
If you'd like less code, then save the value of $src inside your WHILE loop when user=0 into some other variable like $src2. And then your code simply becomes:
<img id="mainImage" src="<?php echo $src2 ?>" />

How to avoid blank first result when searching from databse

I have search webpage, but when the search is run, there is a blank first result.
<?php include "headnav.php";
$count = 0;
$sql = "SELECT * FROM lost_property";
if (!empty($_POST)) {
$name = mysqli_real_escape_string($dbconnect, htmlspecialchars($_POST['name']));
$item = mysqli_real_escape_string($dbconnect, htmlspecialchars($_POST['item']));
$area = mysqli_real_escape_string($dbconnect, htmlspecialchars($_POST['area']));
$sql = "
SELECT *
FROM lost_property
JOIN item
ON lost_property.itemID = item.itemID
JOIN area
ON lost_property.areaID = area.areaID
WHERE name LIKE '%$name%'
AND item LIKE '%$item%'
AND area LIKE '%$area%'
ORDER
BY lost_property.name ASC
";
$search_query = mysqli_query($dbconnect, $sql);
$count = mysqli_num_rows($search_query);
}
$result = $dbconnect->query($sql);
?>
<body>
<div class="form">
<h1>Search for lost property here:</h1>
<form action="" method="POST">
Name:
<input type="text" placeholder="Name" name="name">
Item type:
<select name="item" class="dropdown">
<option value="" disabled selected>Item</option>
<?php
$item_sql = "SELECT DISTINCT item FROM `lost_property`
JOIN item ON (lost_property.itemID = item.itemID)
ORDER BY item ASC
";
$item_query = mysqli_query($dbconnect, $item_sql);
$item_rs = mysqli_fetch_assoc($item_query);
do {
?>
<option value="<?php echo $item_rs['item']; ?>"><?php echo $item_rs['item']; ?></option>
<?php
} while ($item_rs = mysqli_fetch_assoc($item_query));
?>
</select>
Area (where it was found):
<select name="area" class="dropdown">
<option value="" disabled selected>Area</option>
<?php
$area_sql = "SELECT DISTINCT area FROM `lost_property`
JOIN area ON (lost_property.areaID = area.areaID)
ORDER BY area ASC
";
$area_query = mysqli_query($dbconnect, $area_sql);
$area_rs = mysqli_fetch_assoc($area_query);
do {
?>
<option value="<?php echo $area_rs['area']; ?>"><?php echo $area_rs['area']; ?></option>
<?php
} while ($area_rs = mysqli_fetch_assoc($area_query));
?>
</select>
<input type="submit" value="Search" name="btn">
</form>
</div>
<div class="gallery">
<h2>Search results:</h2>
<?php
//check for results. If there are none display error
if ($count < 1) {
?>
<div class="error">
<h1>No results were found.</h1>
</div>
<?php
} //end if
else {
do {
?>
<!-- display image and information from database and show in gallery -->
<div class="results">
<h3><?php echo $search_rs['name']; ?></h3>
<h3><?php echo $search_rs['item']; ?></h3>
<p><?php echo $search_rs['area']; ?></p>
</div>
<?php
} // end of do
while ($search_rs = mysqli_fetch_assoc($search_query));
} //end else
//if there are any display
?>
</div>
</table>
</body>
</html>
It's hard to see without any CSS, but no matter what is searched, there is always one result, but the h3 and p fields don't have any content. If there wasn't the no results error message it would pop up there too. What is causing this first result?
Use while (){}, if you use do instead it will run once first (credit to Magnus Eriksson).
It ends up like
else {
while ($search_rs = mysqli_fetch_assoc($search_query)) {
?>
<!-- display image and information from database and show in gallery -->
<div class="results">
<h3><?php echo $search_rs['name']; ?></h3>
<h3><?php echo $search_rs['item']; ?></h3>
<p><?php echo $search_rs['area']; ?></p>
</div>
<?php
} // end of do
} //end else
//if there are any display
?>
instead of
else {
do {
?>
<!-- display image and information from database and show in gallery -->
<div class="results">
<h3><?php echo $search_rs['name']; ?></h3>
<h3><?php echo $search_rs['item']; ?></h3>
<p><?php echo $search_rs['area']; ?></p>
</div>
<?php
} // end of do
while ($search_rs = mysqli_fetch_assoc($search_query));
} //end else
//if there are any display
?>

How can I get this to display in 1 loop

In the backend of my website, I have added more categories as follows
<strong>Tour category : </strong><br />
<select name="category_id">
<?php
foreach($category_lists as $list){
if($list['id'] == $arr_collect['category_id']){
$sel = ' selected="selected" ';
}else{
$sel = null;
}
echo '<option value="'.$list['id'].'"'.$sel.'>'.$list['name'].'</option>';
}
?>
</select>
<br clear="all" />
<strong>Tour category 2: </strong><br />
<select name="category_id2">
<option value="">Select Another</option>
<?php
foreach($category_lists as $list){
if($list['id'] == $arr_collect['category_id2']){
$sel = ' selected="selected" ';
}else{
$sel = null;
}
echo '<option value="'.$list['id'].'"'.$sel.'>'.$list['name'].'</option>';
}
?>
</select>
<br clear="all" />
<strong>Tour category 3: </strong><br />
<select name="category_id3">
<option value="">Select Another</option>
<?php
foreach($category_lists as $list){
if($list['id'] == $arr_collect['category_id3']){
$sel = ' selected="selected" ';
}else{
$sel = null;
}
echo '<option value="'.$list['id'].'"'.$sel.'>'.$list['name'].'</option>';
}
?>
</select>
In the front end, I have this
<?php
$sql_ci = "SELECT * FROM location WHERE parent_id <> 0 ORDER BY parent_id, sort ";
$result_ci = mysql_query($sql_ci);
$cities = $Manager->fetchAssoc($result_ci); //peek_array($cities);
if(!empty($cities)){
foreach($cities as $city){
$i = 1; // for active category
$sql_count = "SELECT * FROM tour t, tour_category c
where t.location_id = {$city['id']} and t.type = 'P'
group by t.category_id AND t.category_id2"; //echo $sql_count.'<br />';
$result_count = mysql_query($sql_count);
$count = $Manager->fetchAssoc($result_count);
?>
<ul class="tours-accord tour-private" id="tourcity<?php echo $city['id'];?>">
<?php
$sql_ca = "SELECT * FROM tour_category ORDER BY sort";
$result_ca = mysql_query($sql_ca);
$categories = $Manager->fetchAssoc($result_ca);
if(!empty($categories)){
foreach($categories as $cat){
$sql_tour = "SELECT t.* FROM tour t
WHERE
t.touronline = 'yes'
AND t.category_id = {$cat['id']}
AND t.location_id = {$city['id']}
and t.type = 'P'
ORDER BY t.tourcode";
$result_tour = mysql_query($sql_tour);
$tours = $Manager->fetchAssoc($result_tour);
if(!empty($tours)){
?>
<li style="border-bottom:1px solid gray;">
<?php echo $city['name']; ?> - <?php echo $cat['name']; //echo ' '.$i.' ';?>
<ul>
<?php foreach($tours as $tour){
if(!empty($tour['intro_image'])){
$img = $tour['intro_image'];
}else{
$img = 'default.jpg';
}
?>
<a href="tour-details.php?code=<?php echo $tour['tourcode'];?>" class="tourname">
<li class="<?php if($i == count($count)){echo 'active';} ?>">
<img src="uploaded-items/tour-introimage/<?php echo $img; ?>" width="150" height="100" />
<span class="tourname"><?php echo $tour['tourname'].'(Code: '.$tour['tourcode'].')'; ?></span>
<p><?php echo $tour['intro']; ?></p>
<div class="home-tour-info">
<img src="images/btn-more-info-green-dark.jpg" alt="More info" class="moreinfo"/>
<div class="home-tour-price"><?php echo $tour['promotion_label']; ?></div>
</div>
</li></a>
<?php } ?>
</ul>
</li>
<?php $i++;}}} //each category ?>
The way I made it work was post the last bit 3 times and changed category_id to category_id2, category_id3. But this displayed duplicate categories.
How can I make all this just in 1 loop instead of 3?
Your backend loop is like wise as follows, as a optimising code,
<?
$numcount = 3;
for($i=0;$i<$numcount;$i++) { ?>
<strong>Tour category <?=$i+1?>: </strong><br />
<select name="category_id<?=$i+1?>">
<?php
foreach($category_lists as $list){
if($list['id'] == $arr_collect['category_id'.($i+1)]){
$sel = ' selected="selected" ';
}else{
$sel = null;
}
echo '<option value="'.$list['id'].'"'.$sel.'>'.$list['name'].'</option>';
}
?>
</select>
<br clear="all" />
<? } ?>

Show song with typed letter

I'm making a search form with suggestions from database. All is going good but the problem is when I type "t" it shows the song with t likewise shows the song with s letter as well here is my code:
<?php
include('config.php');
if($_POST) {
$q = $_POST['searchword'];
$sql_res=mysql_query("select * from vass_songs");
while($row=mysql_fetch_array($sql_res)) {
$id=$row['id'];
$title=$row['title'];
$img=$row['img'];
$album_id=$row['album_id'];
$re_title='<b>'.$q.'</b>';
?>
<div class="suggestion_box" align="left">
<a href="/song/<?php echo $id; ?>">
<img src="/static/albums/<?php echo $id; ? >_small.jpg");">
</div><?php echo $title; ?><br/>
<span style="font-size:9px; color:#999999"><?php echo $country; ?></span>
</a>
</div>
<?php
}
} else {
}
?>
try this:
<?php
include('config.php');
if(isset($_POST['searchword'])) {
$q = $_POST['searchword'];
$sql_res=mysql_query("
SELECT *
FROM vass_songs
WHERE title LIKE '%$q%'
");
while($row=mysql_fetch_array($sql_res)) {
$id = $row['id'];
$title = $row['title'];
$img = $row['img'];
$album_id = $row['album_id'];
$re_title = "<b>{$q}</b>";
?>
<div class="suggestion_box" align="left">
<a href="/song/<?php echo $id; ?>">
<img src="/static/albums/<?php echo $id; ?>_small.jpg");">
<div><?php echo $title; ?></div><br/>
<span style="font-size:9px; color:#999999">
<?php echo $country; ?>
</span>
</a>
</div>
<?php
}
} else {
}
?>

How do I show all the results from an SQL statement?

I wanted to display all of my shirts but I always get the same error
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /homepages/36/d362778419/htdocs/home/specials.php on line 34
Here is the code I have currently in place
<?php
require "connect2.php";
$sql = mysql_query("SELECT * FROM shirts WHERE all='1'");
$runrows = mysql_fetch_array($sql);
$title = $runrows['title'];
$picture = $runrows['picture'];
$newp = $runrows['newp'];
$date = strftime("%b %d, %Y %l:%M %p" ,strtotime($runrows['date']));
$oldp=$runrows['oldp'];
$viewl=$runrows['viewl'];
$shirtl = $runrows['shirtl'];
echo "";
?>
<div class="specialsListBoxContents centeredContent back" style="width:25%;"><div class="product-col" > <div class="img">
<a href="detail.php?id=<?php echo $id; ?>"><img src="<?php echo $picture; ?>" alt="<?php echo $title; ?>" title=" <?php echo $title; ?> " width="190"
height="160" /></a> </div> <div class="prod-info"> <div class="wrapper">
<div class="price"> <strong><span class="normalprice"><?php echo $oldp; ?
></span><br /><span class="productSpecialPrice"><?php echo $newp; ?></span></strong> </div>
<div class="button"><a href="detail.php?id=<?php echo $id; ?>"><img src="images/button_add_to_cart.gif" alt="Add to Cart" title=" Add to Cart " width="54"
height="49" /></a></div> </div> </div> </div></div>
<?php
?>
mysql_*() functions return boolean FALSE if they fail, which means your query call did not succeed. Add this code to find out the reason why:
$sql = mysql_query("SELECT * FROM shirts WHERE all='1'");
if ($sql === FALSE) {
die(mysql_error());
}
Here's some sample code:
<?php
$sql = mysql_query("SELECT * FROM shirts WHERE `all`='1'");
if (!$sql ) {
echo "Could not successfully run query from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($sql) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
while ($row = mysql_fetch_assoc($sql))
{
?>
<a href="detail.php?id=<?php echo $row['id']; ?>"><img src="<?php echo $row['picture']; ?>" alt="<?php echo echo $row['title']; ?>" title=" <?php echo $row['title']; ?> " width="190" height="160" />
<?php
}
?>
And here is more info. Notice the exiting php mode inside the while.

Categories