Mysqli query using $_get where a value is missing [duplicate] - php

This question already has answers here:
Search Form with One or More (Multiple) Parameters
(2 answers)
Closed 6 years ago.
I have a drop-down box where a user can select a location. Then, there is a text box where they can input a maximum rental price (there will be a few more options but to keep things simple just these in the example). Then this will go to a results.php page and using the $_GET array extract the values and query the database
This works fine if both fields are complete, but if they only wanted to search by location and leave the rent field blank it doesn't work and displays results.php?loc=york&rent= in the URL, which then as I have used the AND function displays no results?
I'm very new to PHP and would very much appreciate anyone who can point me in the right direction or what the correct term to search in google for?
<?php
$location = $_GET['loc'];
$rent=$_GET['rent'];
$result = $mysqli->query("SELECT * FROM dbc_posts WHERE '$location'=city &&'$rent'>rent_price ORDER BY ID ASC");
?>

try this
<?php
// you can check for sql injection
$location = $_GET['loc'];
$rent=$_GET['rent'];
// check if $_GET['rent'] is provided and has a value
if( isset( $_GET['rent'] ) && $_GET['rent'] ) {
$result = $mysqli->query("SELECT * FROM dbc_posts WHERE city='$location' AND rent_price < '$rent' ORDER BY ID ASC" );
// do remaining stuff
} else {
// rent is not provided
$result = $mysqli->query("SELECT * FROM dbc_posts WHERE city='$location' ORDER BY ID ASC");
// do other stuff
}
?>

You can either create 2 queries, or just one with some variables.
$rent = $_GET['rent'];
$rent_options = "";
if(isset($rent)) //add condition
{
$rent_options .= "&& \'rent\'>rent_price";
}
$mysqli->query("SELECT * FROM dbc_posts WHERE '$location'=city".$rent_options." ORDER BY ID ASC");
This way, assuming they chose a rent option, it will be added to the query. If not, it will simply be blank space and be ignored.

If the $rent is empty the you have to check it first before querying to database.
if(!empty($rent))
{
$result = $mysqli->query("SELECT * FROM dbc_posts WHERE city='$location' and rent_price<'$rent' ORDER BY ID ASC");
} else {
$result = $mysqli->query("SELECT * FROM dbc_posts WHERE city='$location' ORDER BY ID ASC");
}

Related

PHP mysql data not retrieving from last id

I'm developing one API in php to display data on android app from my database using JSON.
In my app I want to display 20 records first, after display again 20 records once user scroll to top.
I'm requesting the last id of the record from app to show next 20 records from last id.
Here is my code
<?php
$last_movie = 0;
$genre = $_REQUEST['genre'];
$last_movie = $_REQUEST['lastid'];
require_once("connect.php");
$myArray = array();
if($last_movie == 0)
{
$result = $conn->query("SELECT * FROM my_movies WHERE genre = '$genre' ORDER BY year DESC LIMIT 20");
}
else
{
$result = $conn->query("SELECT * FROM my_movies WHERE genre = '$genre' ORDER BY year LIMIT ".$last_movie.",20");
}
if ($result) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
$result->close();
$conn->close();
?>
I'm getting values in some genres, but sometimes it show empty JSON.
I tried with this url
http://freemodedapk.com/bobmovies/by_genre.php?genre=Action
its working , whenever I try from last id
http://freemodedapk.com/bobmovies/by_genre.php?genre=Action&lastid=4714
It returns empty JSON. I have values in database.
But some genres working fine
http://freemodedapk.com/bobmovies/by_genre.php?genre=Drama
http://freemodedapk.com/bobmovies/by_genre.php?genre=Drama&lastid=865
I have total 4858 records in the database with all genres.
Anybody can help me to fix empty JSON problems in some of genres ?
Your main issue is in the wrong LIMIT usage: when you utilize 2 parameters for LIMIT keyword, the first one is for OFFSET value (not for IDs), the second one is to limit your result.
In short words: you should use LIMIT 0,20 to get the first 20 results, LIMIT 20,20 to show next 20 results and so on.
Also, your code is insecure - you have SQL injection. Try to not post direct urls on your sites with the source code which includes injection because some bad guys may drop your database or do some other harmful things.
Sample code is listed below (minor changes may be required):
<?php
require_once('connect.php');
$response = [];
$items_per_page = 20;
$page = (int) (($_REQUEST['page'] - 1) * $items_per_page);
$genre = $conn->escape_string($genre); # replace escape_string with proper method if necessary
$result = $conn->query("SELECT * FROM my_movies WHERE genre = '$genre' ORDER BY year DESC LIMIT $page,$items_per_page");
if ($result)
{
$response = $conn->fetch_all($result, MYSQLI_ASSOC); # replace fetch_all with proper method if necessary
}
echo json_encode($response);
$result->close();
$conn->close();
if you want to get last ID to ASC then use to
SELECT * FROM my_movies WHERE genre = '$genre' id<".$last_movie." ORDER BY year LIMIT 0,20
or if you want to get for pagination then your OFFSET value wrong,
you should be use LIMIT 0,20 to get the first 20 results, LIMIT 20,20 to next 20 , LIMIT 40,20
please check your SQL injection
look like Code
require_once('connect.php');
$result = [];
$limit = 20;
$pageNumber = (int) (($_REQUEST['pageNumber'] - 1) * $limit);
$genre = $conn->escape_string($genre);
$getDta = $conn->query("SELECT id,title,stream,trailer,directors,actors,quality,year,genre,length,translation,rating,description,poster FROM my_movies WHERE genre = '".$genre."' ORDER BY year DESC LIMIT $pageNumber,$limit");
if ($result)
$result =$conn->fetch_all($result, MYSQLI_ASSOC);
echo json_encode($result);
$result->close();
$conn->close();

How Sort data from database in php when using while in php

I want to sort date, time from the database from new to old ( high to low ) and I use this code but didn't work!
can you help me?
and I want MySqli Solution and it uses while because I don't know how many numbers of information I will receive from the database!
$sql = "SELECT * FROM orders WHERE seller='$id' ORDER BY dtime ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$ordernumber = $row['ordernumber'];
echo "<ul> <li> $ordernumber</li></ul>";
}
}
If you want to get more details for ordering then click Here.
In your code, you should write like this below,
$sql = "SELECT * FROM orders WHERE seller='$id' ORDER BY dtime DESC";
And please do some search for ordering for your doubt.
Thanks..!!

Hiding the particular value in php

I am getting a string value in php. It shows all the related lists from the db, but my question here is about the sidebar. I want to display the related list item from the same table, but it is getting the whole list, even the row which is already displayed on the main body.
So, could you please help me out, to hide the row already shown.
$queryy = "SELECT * FROM cate_websites WHERE s = 'approved' ORDER BY rand()";
$result = mysqli_query($con1,$queryy);
$allrows = mysqli_num_rows($result);
if ($allrows > 0){
while ($row_result =mysqli_fetch_assoc($result)) {
$eid = $row_result['cid'];
$etitle =$row_result['title'];
$eimage = $row_result['img1'];
$edesc = substr($row_result['meta'],0,100);
$epermalink=$row_result['permalink'];
if($epermalink == $_GET['articles']) {
echo" here it should not display the get value but it show all the rest of the values";
}
}
}
I think that you wish to skip the particular link from the list. Correct me if I am wrong.
The query should be like this.
$queryy = "SELECT * FROM cate_websites
WHERE s = 'approved' and permalink!='".$_GET['articles']."'
ORDER BY rand()";
Comment if you feel this is not the answer expected.(Also pls add filters and all as this will be pretty injection prone if used like this)

Let the user select the amount of records to get from table

I have a website that Facebook users use to get likes on their statuses. The website uses MySQL database to give likes to the users, the default number of limitation of the likes to be sent is 70. What I need is a PHP code that will let the user choose the amount of likes by themselves using the "select" HTML code.
I have already made the form and select codes (demo: jsfiddle.net/U4Ye8) Please see the demo.
The form action is "p.php"
The questions are:
-What code do I need to have in the index.php?
-What code do I need to have in the p.php?
If you need any other info about my question, please comment below.
$output = '';
//get users and try liking
$result = mysql_query("
SELECT
*
FROM
Likers ORDER BY ID DESC LIMIT 70
");
if($result){
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$m = $row['access_token'];
$facebook->setAccessToken ($m);
$id = trim($_POST ['id']);
try {
$facebook->api("/".$id."/likes", 'POST');
$msg1 = "<font color='get'>Success!</font>";
}
catch (FacebookApiException $e) {
$output .= "<p>'". $row['name'] . "' failed to like.</p>";
$msg2 = "<font color='red'>Failed to Like!</font>";
}
}
}
Looks like you just need to set the limit to what was selected:
<select name="numOfLikes"> // <---- I gave your select a name
<option value="##'>##</option>
</select>
SELECT * FROM Likers ORDER BY ID DESC LIMIT $_POST['numOfLikes']
Note** This is a sample script to see the changes easily. All $_POST and $_GET requests must be escaped for protection from sql injection. Prevent SQL Injection

How to assign the results of a row to different variables using PDO in PHP & MySQL

I have a table
id url count
1 www. 6
2 www. 9
3 www. 11
4
and so on
I want to display the count next to a link in my webpage and therefore I am using the statements below to assign "count" to a variable for a specific id.
$stmt1 = $db->query("SELECT * FROM clickcounter WHERE id = 1");
while ($row = $stmt1->fetch(PDO::FETCH_ASSOC)){
$count1=$row['count'];
}
$stmt2 = $db->query("SELECT * FROM clickcounter WHERE id = 2");
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC)){
$count2=$row['count'];
}
$stmt3 = $db->query("SELECT * FROM clickcounter WHERE id = 3");
while ($row = $stmt3->fetch(PDO::FETCH_ASSOC)){
$count3=$row['count'];
}
and so on
I have plenty of id in my table.
Is there a better way to do this or do I have to write these statements over and over again.
Basically I want to assign the values of "count" to a variable so that I can use them in my webpage at different locations.
Ok, you can make a block with url list and add pager with button "next list" or so.
For example:
$page = (isset($_GET['page']) && is_numeric($_GET['page'])) ? $_GET['page'] : 0;
$per_page = 10;
$url_list = "";
$stmt = $db->query("SELECT * FROM clickcounter LIMIT ".($page * $per_page).", 10");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$url_list .= $row['url']." : ".$row['count']."<br />\n";
}
// view url list
print $url_list;
You can save it in external file and use javascript (like jQuery) for display it in you page and change pages with "onclick" function :)

Categories