Issues using between, min and max - php

I have created a catalog with a block of years search function for characters and the years I've assigned to them. So anything from 1940-1949 would be in the 1940's block of time, and so on. I'm using a href to group these timeframes.
<?php
$sql = "SELECT * FROM catalog";
$displayby = $_GET['displayby'];
$displayvalue = $_GET['displayvalue'];
if($displayby && $displayvalue){
$sql = "SELECT * FROM catalog WHERE $displayby LIKE '$displayvalue'";
}
if($displayby == 'year'){
$min = $_GET['min'];
$max = $_GET['max'];
$sql = "SELECT * FROM catalog WHERE year BETWEEN '$min' AND '$max'";
}
//$result = mysqli_query($con,$sql);
$result = mysqli_query($con,"SELECT * FROM catalog WHERE year BETWEEN '$min' AND '$max'");
while($row = mysqli_fetch_array($result)){
$name = $row['name'];
$filename = $row['filename'];
$cid = $row['cid'];
echo "\n<div class=\"holder\">";
echo "<img src=\"thumbs/$filename\">";
echo "$name<br />\n";
echo "</div>";
}
?>
With this href to only bring up certain characters within those years:
40's Villans<br/>
However they are showing up in the years prior - it might be 1945 as a set date for the character but they only appear in 1930's link.
What am i doing wrong?
Edit : here is the table

BETWEEN ... AND .... can be used for integers and strings. so:
BETWEEN 1 AND 3
Will be true for 1, 2 and 3. But:
BETWEEN 'a' AND 'c'
Will be true for 'a', 'b' and 'c'.
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between
You've put quotes around your numbers, turning them into strings. So the comparison is done on the characters, not the numbers.
Removing the quotes should make it work.
$result = mysqli_query($con,"SELECT * FROM catalog WHERE year BETWEEN $min AND $max");
But as said by others, there are a lot of other problems with the code. This mistake is a symptom of someone who doesn't really know what they're doing. Why not start at the beginning, and grab a good book. Read it. Do the examples. Experiment. It can take years to become a fluent programmer. (This is meant as an ecouragement, not critizm.)

instead of using between you can also use the following statement for getting the desired data as following
$sql = "SELECT * FROM catalog WHERE year >= '$min' AND year <='$max'";
and in phpmyadmin you can run the query to make sure that you are getting the correct data ,and after that you can check your code where you are displaying it
i hope it help's you..

Related

Search Query not works Properly : Php Like Query

<?php
include"configration.php";
?>
<?php
$query = $_GET['query'];
$min_length = 1;
//echo $query;exit();
if (strlen($query) >= $min_length) { // if query length is more or equal minimum length then
//echo "success";exit();
$query = htmlspecialchars($query);
$query = mysqli_real_escape_string($conn, $query);
$sql = "SELECT * FROM table2
WHERE title LIKE '%".$query."%' order by date DESC";
$raw_results = mysqli_query($conn, $sql) or die(mysql_error());
if (mysqli_num_rows($raw_results) > 0) { // if one or more rows are returned do following
while ($res = mysqli_fetch_array($raw_results)) { ?>
<?php echo $res['title'] ?> // Place where result comes ..
<?php }
}
}
?>
This is code works fine but search in this way
For Example Title is: you are vary nice boy but lazy
When I search by:
You are vary ............. result shows ..
vary nice boy ............. result shows ..
vary lazy, or boy lazy or vary lazy .. result not shows ..
Plz some one help me in this and how to show searched query in title ..
<title> Searched Query ...</title>
LIKE '%boy lazy%' will show the Of the cases where anything can be before boy lazy and anything can be after boy lazy, but boy lazy will be together.
In your case, one approach can be, you can explode your $query, and then use multiple LIKE queries to create sql query. Example:
<?php
//$conn = mysqli_connect("localhost","your user","your pass","db");
$query = $_GET['query'];
$min_length = 1;
//echo $query;exit();
if (strlen($query) >= $min_length) { // if query length is more or equal minimum length then
//echo "success";exit();
$query = htmlspecialchars($query);
$query = mysqli_real_escape_string($conn, $query);
$searchKeys = explode(' ',$query);
$sql = "SELECT * from table2 where title ";
foreach ($searchKeys as $key) {
$sql.= "LIKE '%".$key."%' AND title ";
}
$sql = substr($sql, 0, -10);
//$sql.="ORDER BY date DESC;";
$raw_results = mysqli_query($conn, $sql) or die(mysql_error());
if (mysqli_num_rows($raw_results) > 0) { // if one or more rows are returned do following
while ($res = mysqli_fetch_assoc($raw_results)) {
echo $res['title']."\n";
}
}
}
When you search title LIKE "%vary lazy%", you will get records that contain the string "vary lazy" preceeded and followed by any other or no character sequences. If you want to match strings that contain the words - I should better say, the character sequences - "vary" and "lazy" in that specific order you should use:
title LIKE "%vary%lazy%"
However, this will also match "varylazy", "varying lazytown characters".
Assuming you generally intend to use queries as you mentioned, i.e. each word is separated by a space character and you want to see if those words appear in a text in specifically that order, you could write something like this:
$query = $_GET["query"];
$query = '%'.str_replace(' ', '%', $query).'%';
//... MySQL stuff
Please be aware that the code above is very specific to your needs. I wouldn't use it as a general purpose approach for processing query strings, e.g. having multiple spaces between words would result in multiple consequent % in your SQL query - I'm not even sure if that is allowed. However, under the constraints described, this code should work just fine.

Between min and max value mysqli

I have to create a PHP web page with two text fields in which the user can enter minimum and maximum item prices from a SQL database. So I have items with prices. For example, if a user wants to see items between the prices 4 and 15, he can submit it and then it will show only the items in that price range. How can I do this? How to echo this?
Thank you!
I have this so far:
$min=$_POST["minimum"];
$max=&$_POST["maximum"];
$result = mysqli_query($con,"SELECT * FROM items WHERE selling price BETWEEN {$min}+1 AND {$max}");
Apart from a major SQL Injection issue, your script is looking fine. Just some small typs and syntax errors. Compare this one to yours:
$min=(int)$_POST["minimum"];
$max=(int)$_POST["maximum"];
$result = mysqli_query($con,"SELECT * FROM items WHERE selling_price BETWEEN {$min}+1 AND {$max}");
So, what did I change?
At least cast posted values to int to remove the chance of anyone injecting malicious SQL code into your query. You should use proper escaping in the future
You dont need to add the & character before in line two. You dont need to assign the value by reference. just assign the plain old way
column and table names can not conain spaces in MySQL. Are you sure that is the correct name of the column? Maybe there was an underscore?
One of the many safer and simpler ways of doing that would be
$dsn = "mysql:dbname=test;host=127.0.0.1";
$dbh = new PDO($dsn, 'username', 'password');
if(isset($_POST["minimum"]) && isset($_POST["maximum"]))
{
$min=floatval($_POST["minimum"]); //+1 is not needed
$max=floatval($_POST["maximum"]);
$sth = $dbh->prepare("SELECT * FROM items WHERE selling_price BETWEEN ? AND ?");
$sth->execute(array($min,$max));
while($row = $sth->fetch(PDO::FETCH_OBJ))
{
print_r($row);
}
}
That should do the trick for you:
if(isset($_POST['minimum'])){
$min = $_POST['minimum'];
}else{
$min = '';
}
if(isset($_POST['maximum'])){
$max = $_POST['maximum'];
}else{
$max = '';
}
$sql = "SELECT * FROM item WHERE selling_brice > '$min' AND selling_price < '$max'";
$query = mysqli_query($con, $sql);
$count = mysqli_num_rows($query);
if($query == true && $count > 0 ){
while ($row = mysqli_fetch_assoc($query)){
$price .= $row['selling_price'];
$price .= '<br />'
}
echo $price;
}else{
echo "NO results to Display";
}
Ofcourse this is not the best programing mysql injections, your query uses * etc....but this should work.

Whats wrong with this SQL query?

I haven't been writing PHP/SQL in a few years and needed to do this for a project. And now I have run into a problem.
I wanting to grab some data from a MySQL databas, between specific dates. It works just fine if write it like this:
$result = mysql_query("SELECT * FROM acw WHERE team = '".$team."' and added between '2012-11-05' and '2012-11-10' ");
But I want to get the dates from the URL, and have written this:
$periods = $_GET["per"];
if ( $periods == 1 ) {
$period = "and added between '2012-11-05' and '2012-11-10'";
}
elseif ( $periods == 2 ) {
$period = "and added between '2012-11-11' and '2012-11-17'";
}
elseif ( $periods == 3 ) {
$period = "and added between '2012-11-05' and '2012-11-10'";
}
echo $period;
If I echo $period I got the correct output in the HTML but when trying to insert it to my MySQL questions i got nothing, what does I do wrong?
$result = mysql_query("SELECT * FROM acw WHERE team = '".$team."' '".$period."' ");
So something is wrong with this, and can't solve it by my self :(
Your string in $period is a full chunk of SQL, not a quoted string literal. So remove the single quotes surrounding it.
$result = mysql_query("SELECT * FROM acw WHERE team = '". $team ."' " . $period);
//---------------No quotes here----------------------------------------^^^^^^^^^^
Note: We assume that $team, if originating from user input, has already been properly escaped against SQL injection via mysql_real_escape_string()
It is recommended to always debug your SQL statement by echo'ing out the string. It would have been a little more obvious to see a string like:
SELECT * FROM acw WHERE team = 'The Team' 'and added between '2012-11-05' and '2012-11-10''
A final word of advice - unless this is already done in code not posted here, verify that $_GET['per'] is set before attempting to use it:
// Set $periods to the $_GET value or defualt to 1 if it isn't set (or whatever value)
$periods = isset($_GET["per"]) ? $_GET['per'] : 1;

How to php pagination of results obtained from this database

I am a beginner in php.
I visualize in my html page the results obtained with this php code, and now I want to paginate the results and limit your search to 6 items per page. How can I get this? My php code is as follows:
<?php
$k = $_GET['k'];
$terms = explode(" ", $k);
$query = "SELECT * FROM table_name WHERE ";
$i = 0;
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "keywords LIKE '%$each%' ";
else
$query .= "OR keywords LIKE '%$each%' ";
}
// connect
mysql_connect("hostname","databaseUser","databasePassword");
mysql_select_db("databaseName");
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
echo "<p><strong>Totale: {$numrows} risultati trovati</strong></p></br>";
if ($numrows > 0){
while ($row = mysql_fetch_assoc($query)){
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
$date = $row['date'];
$caption = $row['caption'];
echo "<h4><a href='$link'>$title</a></h4>";
echo "<em>$description</em></br></br>";
echo "$caption</br>";
echo "$link</br></br>";
echo "<em>$date</em></br></br>";
}
}
else
echo "NO result found for \"<p><strong>$k</strong></p>\"";
// disconnect
mysql_close();
?>
Pagination is a problem that most of us have tried to solve over the years.
You can build your own library to do this but you'll almost definitely be re-inventing the wheel and might not spot/handle some of the special cases.
If you're using a framework I'd suggest using the built in paginator, if not you could look at using something like http://pear.php.net/package/Pager which is a PEAR package.
You need to add a page variable into your code. The easiest way to to this is via $_GET, just like you grabbed keywords, so your url should look something like this:
foo.php?k=keywords%20here&p=1
Where p is the current page number.
Then you just need to add a limit to your search results so that you only grab 6, and the correct 6 at that. Something like this:
$query .= ' LIMIT '.(6*($pageNum - 1)).' 6';
This statement tells SQL to start at the first entry for the given page, and grab 6 results. We subtract 1 from the page number so that page 1 starts at entry 0 instead of entry 6.
The result of this code:
page | statement | Rows Grabbed
---------------------------------
1 | LIMIT 0 6 | 1-6
2 | LIMIT 6 6 | 7-12
3 | LIMIT 12 6 | 13-18
---------------------------------
and so on...
You might need to check that $_GET['p'] is an integer before you put it in $pageNum, so that you don't run into runtime issues trying to multiply a string by 6.
If you ever want to change the results per page, simply replace the 6's in that statement with the desired number of results per page, e.g.
$query .= ' LIMIT '.($numResults*($pageNum - 1)).' '.$numResults;
That way you can set your desired number of results with another variable, say $_GET['n'] or something similar, and have even better control.
EDIT:
You should probably add error checking:
$pageNum = (is_numeric($_GET['p']) ? intval($_GET['p']) : 1);
which says if GET[p] is numeric, set pageNum to the integer value of GET[p]. Otherwise, set pageNum to 1.
Also, You have a few errors in the way that you put variables into strings. There are two ways to join a variable into a string, you can either use double quotes and curly braces, like so:
$string = "this string has {$variable} in it";
Or you can concatenate with periods, using either single or double quotes likes so:
$string = 'this string has ' . $variable . " in it";
You have this problem in your foreach loop when you append the query, and also further down where you output your results.

MySQL + PHP: How to do search and show summary rather than entire result

was wondering how to do a search result using PHP + MySQL but not show all the data in the result but only a SUMMARY (lets say limited to 200 characters). And the summary would exactly contain the keyword portion. So -100 characters+keyword+100 characters might be how it would be shown.
Thanks!
Assuming you are fine with taking the first instance of the keyword to use in your summary, you could break up the results of your query in PHP in a way similar to this:
$sql = "SELECT data_field FROM your_table WHERE data_field LIKE '%".$keyword."%'";
$res = mysql_query($sql);
while($row = mysql_fetch_array($res)) {
$data = $row['data_field'];
$first_pos = strpos($data,$keyword);
if ($first_pos !== false) {
$output = substr($data,max(0,$first_pos - 100),200 + strlen($keyword));
echo $output;
}
}
Obviously you could do whatever suited your needs with $output once you had it.

Categories