where clause not displaying data - php

i am trying to display data based on wether data in a field is new. instead of showing only the data that is new it is showing all data. can someone point out my error. many thanks
<?php
include("../../js/JSON.php");
$json = new Services_JSON();
// Connect to MySQL database
mysql_connect('localhost', 'root', '');
mysql_select_db(sample);
$page = 1; // The current page
$sortname = 'id'; // Sort column
$sortorder = 'asc'; // Sort order
$qtype = ''; // Search column
$query = ''; // Search string
$new = 1;
// Get posted data
if (isset($_POST['page'])) {
$page = mysql_real_escape_string($_POST['page']);
}
if (isset($_POST['sortname'])) {
$sortname = mysql_real_escape_string($_POST['sortname']);
}
if (isset($_POST['sortorder'])) {
$sortorder = mysql_real_escape_string($_POST['sortorder']);
}
if (isset($_POST['qtype'])) {
$qtype = mysql_real_escape_string($_POST['qtype']);
}
if (isset($_POST['query'])) {
$query = mysql_real_escape_string($_POST['query']);
}
if (isset($_POST['rp'])) {
$rp = mysql_real_escape_string($_POST['rp']);
}
// Setup sort and search SQL using posted data
$sortSql = "order by $sortname $sortorder";
$searchSql = ($qtype != '' && $query != '') ? "where ".$qtype." LIKE '%".$query."%' AND new = 1" : '';
// Get total count of records
$sql = "select count(*)
from act
$searchSql";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$total = $row[0];
// Setup paging SQL
$pageStart = ($page -1)*$rp;
$limitSql = "limit $pageStart, $rp";
// Return JSON data
$data = array();
$data['page'] = $page;
$data['total'] = $total;
$data['rows'] = array();
$sql = "select *
from act
$searchSql
$sortSql
$limitSql";
$results = mysql_query($sql);
while ($row = mysql_fetch_assoc($results)) {
$data['rows'][] = array(
'id' => $row['id'],
'cell' => array($row['id'], $row['slot'], $row['service'], $row['activity'], $row['department'], $row['company'], $row['address'], $row['user'], $row['item'], $row['filebox'], date('d/m/Y',strtotime($row['date'])), $row['quantity'], $row['type'], $row['new'])
);
}
echo $json->encode($data);
?>

You should debug SQL by looking at the SQL query, not at the PHP code that produces the SQL query. If you echo $sql and look at it, you'll probably see any syntax errors much more easily.
You can also copy & paste that SQL and try to execute it in the MySQL command tool, and see what happens, whether it gives the result you want, you can profile it or use EXPLAIN, etc.
You're using mysql_real_escape_string() for integers, column names, and SQL keywords (ASC, DESC). That escape function is for escaping only string literals or date literals. It's useless for escaping unquoted integers, column names, SQL keywords, or any other SQL syntax.
For integers, use (int) to typecast inputs to an integer.
For column names or SQL keywords, use a whitelist map -- see example in my presentation http://www.slideshare.net/billkarwin/sql-injection-myths-and-fallacies
You're not testing for error statuses returned by any of your functions. Most functions in ext/mysql return false if some error occurs. You should check for that after every call to a mysql function, and report errors if they occur.
You're selecting a database using a constant name sample instead of a quoted string "sample". This might be intentional on your part, I'm just noting it.
Also, this is not related to your errors, but you should really upgrade to PHP 5. PHP 4 has been end-of-lifed for over two years now.

after looking at the code again and all the suggestions i think i should be using an AND clause and not WHERE. for example the code
$searchSql = ($qtype != '' && $query != '') ? "where ".$qtype." LIKE '%".$query."%' AND new = 1" : '';
this is the WHERE clause? which basically translates to:
$sql = "select *
from act
$searchSql
$sortSql
$limitSql"; <- original code
$sql = "select *
from act
WHERE company LIKE '%demo%' AND new = 1
$sortSql
$limitSql";<-updated code
am i on the right track?

Related

SQL query not working but works in PHPMyAdmin

I have a web application and I'm trying to modify one of the queries. The query fetches information (from a table named voyage_list) and returns various fields.
I want to modify the query so that it is based on certain filters the user applies (which will be placed in the URL).
I can't get the query to work in the web application, but if I copy the query and execute it directly within PHPMyAdmin, it works fine.
$vesselFilter = $_GET['vesselFilter'];
$vesselArray = explode(',', $vesselFilter);
$arrayCount = count($vesselArray);
$sqlExtend = ' status = 1 AND';
foreach ($vesselArray as $value) {
$i = $i + 1;
$sqlExtend .= " vesselID = '$value'";
if ($i < $arrayCount){
$sqlExtend .= " OR";
}
}
$newQuery = "SELECT * FROM voyage_list WHERE" . $sqlExtend;
echo $newQuery;
$query = $db->query($newQuery)->fetchAll();
I appreciate the above is pretty messy, but it's just so I can try and figure out how to get the query to work.
Any help would be greatly appreciated!
Thanks
That query probably doesn't return what you think it does. AND takes precedence over OR, so it will return the first vessel in the list if the status is 1, and also any other vessel in the list, regardless of status.
You'd do better to create a query with an IN clause like this:
SELECT * FROM voyage_list WHERE status = 1 AND vesselID IN(8,9,10)
Here's some code to do just that:
$vesselFilter = $_GET['vesselFilter'];
// Validate data. Since we're expecting a string containing only integers and commas, reject anything else
// This throws out bad data and also protects against SQL injection.
if (preg_match('/[^0-9,]/', $vesselFilter)) {
echo "Bad data in input";
exit;
}
// filter out any empty entries.
$vesselArray = array_filter(explode(',', $vesselFilter));
// Now create the WHERE clause using IN
$sqlExtend = 'status = 1 AND vesselID IN ('.join(',', $vesselArray).')';
$newQuery = "SELECT * FROM voyage_list WHERE " . $sqlExtend;
echo $newQuery;
$query = $db->query($newQuery)->fetchAll();
var_dump($query);

cannot select a row in mysql

EDIT1 : used double quotes and single quotes but I am getting same error.
EDIT2 : same query is returning me result in mysql shell
I am selecting a row from a table.
if(!isset($_GET['title']) || !isset($_GET['user'])){
echo "hi"; //something come here
}
else{
$title = $_GET['title'];
$title = mysqli_real_escape_string($conn,$title);
$user = $_GET['user'];
$user = mysqli_real_escape_string($conn,$user);
echo $title ;
echo $user ;
// tried giving value directly to test but no luck
$query = "SELECT * FROM site WHERE client=\"Chaitanya\" && title=\"werdfghb\" ";
$result5 = mysqli_query($conn,$query) or die(mysqli_error());
$count = mysqli_num_rows($result5);
echo $count ;
while($result9 = mysqli_fetch_array($result5)){
$kk=$result9['url'];
echo $kk ;
}
$page = $kk;
include ( 'counter.php');
addinfo($page);
}
In my database there is a row with columns title and client and the values I entered are in that row but when I echo count(no of rows) it is showing zero.
Is there anything wrong with code ?
The error you are getting is due to the line
$page = $kk;
in this code $kk is not declared previously. The defined $kk is in the while loop scope.
declare the variable like this in the outer scope from the while loop
...
$kk = null;
while($result9 = mysqli_fetch_array($result5)) {
$kk = $result9['url'];
echo $kk ;
}
$page = $kk;
...
Error on Fetching Data
You have to crack you SQl into smaller pieces and test the code like this.
run the query SELECT * FROM site without any where and get the count
run the query SELECT * FROM site WHERE client='Chaitanya' and get the count
SELECT * FROM site WHERE title='werdfghb' and check the count
Then run the whole query
And see the results. This way u can find out in where the issue is in your SQL code. I prefer you use the mysql client to execute this queries
As I pointed out in my comment, $kk is undefined in the $page = $kk;, since it is declared in the while loop.
Do something like:
$kk = ''; //can also do $kk=NULL; if you want.
while($result9 = mysqli_fetch_array($result5)) {
$kk=$result9['url'];
echo $kk ;
}
$page = $kk;
try this one
$client = "Chaitanya";
$title = "werdfghb";
$query="SELECT * FROM site WHERE client='".$client."' and title='".$title."' ";
you can also use this
$query="SELECT * FROM site WHERE client={$client} and title={$title} ";

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.

Generating a sql query in php using for loop

CODE :
$nerd_result = mysql_query("select * from nerd_profile where nerd_reg_no = '$reg_no'");
$nerd_data = mysql_fetch_array($nerd_result);
$tags = array();
$tags = explode(",",$nerd_data['nerd_interests']);
for($i = 0; $i < sizeof($tags)-1; $i++)
{
if($i != sizeof($tags)-2)
{
$sub_query = $sub_query."`tags` like %".$tags[$i]."% or ";
}
else
{
$sub_query = $sub_query."`tags` like %".$tags[$i]."% ";
}
}
$proper_query = "select * from `qas_posts` where ".$sub_query." and `post_date` like '%$today%'";
$result = mysql_query($proper_query);
while($each_qas = mysql_fetch_array($result))
Description :
I am adding the like clause along with php variable in a string and concatenating it with the further variables with like clause to come. In the end when I echo I get the perfect query that I want but
mysql_fetch_array()
does not accept that generated query rather if I hard code it , it works perfect what am I doing wrong ?? can I do that ??
When doing string comparisons in mysql you need to make sure you have quotes around your comparison value.
$sub_query = $sub_query."`tags` like '%".$tags[$i]."%' or ";
and
$sub_query = $sub_query."`tags` like '%".$tags[$i]."%' ";

Running PHP search script with empty parameters returns entire MySQL table

When I run the following MySQL query via PHP and all of the elements of $_GET() are empty strings, all the records in the volunteers table are returned (for obvious reasons).
$first = $_GET['FirstName'];
$last = $_GET['LastName'];
$middle = $_GET['MI'];
$query = "SELECT * FROM volunteers WHERE 0=0";
if ($first){
$query .= " AND first like '$first%'";
}
if ($middle){
$query .= " AND mi like '$middle%'";
}
if ($last){
$query .= " AND last like '$last%'";
}
$result = mysql_query($query);
What is the most elegant way of allowing empty parameters to be sent to this script with the result being that an empty $result is returned?
my solution:
$input = Array(
'FirstName' => 'first',
'LastName' => 'last',
'MI' => 'mi'
);
$where = Array();
foreach($input as $key => $column) {
$value = trim(mysql_escape_string($_GET[$key]));
if($value) $where[] = "`$column` like '$value%'";
}
if(count($where)) {
$query = "SELECT * FROM volunteers WHERE ".join(" AND ", $where);
$result = mysql_query($query);
}
There's no point in running a (potentially) expensive query if there's nothing for that query to do. So instead of trying to come up with an alternate query to prevent no-terms being searched, just don't run the search at all if there's no terms:
$where = '';
... add clauses ...
if ($where !== '') {
$sql = "SELECT ... WHERE $where";
... do query ...
} else {
die("You didn't enter any search terms");
}
With your current code, if everything is empty, you will get the WHERE 0=0 SQL which is TRUE for all rows in the table.
All you have to do is remove the if statements...

Categories