I have a php form that submits to MySQL, and a 2nd php form that uses the value stored via the first.
The highest value in the database for booth_member is currently 3. In the example below, = $booth_member should be equal to 4, but instead always returns 2.
$membersql = $mysqli->query("SELECT booth_member FROM users WHERE booth_number = '{$user['booth_number']}' ORDER BY booth_member DESC LIMIT 1");
$booth_member = $membersql + 1;
echo $booth_member;
If I try and echo $membersql, it simply returns 'array.'
mysqli::query returns a ressource object, that's why it's not working. Some code to fix it:
$membersql = $mysqli->query("SELECT booth_member FROM users WHERE booth_number = '{$user['booth_number']}' ORDER BY booth_member DESC LIMIT 1");
if($membersql->num_rows < 1)
{ /* error handling goes here */ }
else
{
$res_array = $membersql->fetch_assoc(); // save result as array
$booth_member = $res_array["booth_member"] + 1;
echo $booth_member;
}
Be sure to escape $user['booth_number'] before to prevent sql injection.
For more info, check the mysqli::query documentation :)
You require a bunch of try/catch code around this for a production system, but to test:
$result = $mysqli->query("SELECT booth_member FROM users WHERE booth_number = '{$user['booth_number']}' ORDER BY booth_member DESC LIMIT 1");
$booth_member = $result->fetch_object('booth_member');
++$booth_member;
echo $booth_member;
That's because it's an array. I believe you are trying to do:
$booth_member = $membersql['booth_member'] + 1;
Related
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();
I use this query to get username data table so if i write url index.php?user=username get user data base on username if index.php and data table redirect to admin table this my query
it's work if i write url index.php?user=username data display base on username but if write index.php data not display ..
what wrong with this query thanks
if(isset($_GET['user'])) {
$result = mysql_query("select * from content_table where username = '" . $_GET['user'] . "' limit 2 ;");
if(!empty($GET['user'])){
$result = mysql_query("select * from content_table order by content_id desc limit 1;");
}
I'll leave the SQL injection issue aside for now. First of all, you are missing a closing curly brace. The second problem is that you are not doing the second part correctly. You have:
if(isset($_GET['user'])) {
// query based on username
if(!empty($GET['user'])){
// query just first row
}
The second check is doing the same as the first one - there's no need for it. Your logic should be:
if(!empty($_GET['user'])) {
// query based on username
}
else {
// query just first row
}
Note that you will also need to deal with empty results somewhere.
Now, as for your SQL injection vulnerability, imagine for a second that the username passed in is myname'; drop table content_table -- - your code would simply put this in and execute it - dropping the table. Think about it.
Oh, and please do yourself a favour and stop using mysql_ functions - switch to PDO or at least mysqli_.
Try this
if(empty($GET['user'])){
$result = mysql_query("select * from content_table order by content_id desc limit 1;");
}
if(isset($_GET['user'])) {
$result = mysql_query("select * from content_table where username = '" . $_GET['user'] . "' limit 2 ;");
You have your empty test backwards. So when the parameter is empty, you never perform either query.
Do this:
if (empty($_GET['user'])) {
$result = mysql_query("select * from content_table order by content_id desc limit 1;");
} else {
$result = mysql_query("select * from content_table where username = '" . $_GET['user'] . "' limit 2 ;");
}
empty() performs an isset test first, so you don't need to do both.
Suppose I have code like that
$teachersql = mysql_query("SELECT * FROM `teacher` WHERE status = '2' ORDER BY name") or die(mysql_error());
while($teachers = mysql_fetch_array($teachersql))
{
echo "results";
}
But I have 100 results. I want only first 10 result in output. How? Please anybody help me now.
$teachersql = mysql_query("SELECT * FROM teacher
WHERE status = '2'
ORDER BY name
LIMIT 10")
The mandatory warning:
mysql_* is deprecated, use mysqli_* or PDO.
If you need 10 result in result set then you can make your code as below using limit.
$teachersql = mysql_query("SELECT * FROM `teacher` WHERE status = '2' ORDER BY name limit 10") or die(mysql_error());
or
if you want to fetch all rows and display only 10 result using while loop then you can use counter as below.
$cnt=0;
while($teachers = mysql_fetch_array($teachersql))
{
$cnt++;
echo "results";
if($cnt==10)
break;
}
Try:
SELECT * FROM teacher WHERE status = '2' ORDER BY name limit 10
So, im trying to do a poll, when i run mysql gives me this error, and i dont know what it means.
Warning: max() [function.max]: Array must contain at least one element in .... in line 18.
Could anyone please guide me of whats that?
This is my code:
$query = mysql_query("SELECT * FROM `poll` ORDER BY `id` ASC LIMIT 1");
$rows = mysql_num_rows($query);
if($rows > 0){
$poll = mysql_fetch_array($query);
$title = $poll['name'];
} else {
$title = 'No Poll Yet';
}
$query = mysql_query("SELECT COUNT(`id`) as hits FROM `responses` GROUP BY `qid`");
$me = array();
while($row = mysql_fetch_array($query)){
$me[] = $row['hits'];
}
$max = max($me); ////// THIS IS LINE 18
$query = mysql_query("SELECT `questions`.`pid` FROM `responses`, `questions` WHERE `responses`.`qid`=`questions`.`id` AND `responses`.`ip`='".$_SERVER['REMOTE_ADDR']."' AND pid='".$poll['id']."'");
line 18 is noted after "//////"
Any help ? :s
simply what the error-message says: $me is an empty array (caused by your sql-query returning nothing - why this happens is hard to say without seeing your tablestructure and contents of the table)
Just change in line number 18
if(!empty($me)) $max = max($me);
Full Code After Changes:
$query = mysql_query("SELECT * FROM `poll` ORDER BY `id` ASC LIMIT 1");
$rows = mysql_num_rows($query);
if($rows > 0){
$poll = mysql_fetch_array($query);
$title = $poll['name'];
} else {
$title = 'No Poll Yet';
}
$query = mysql_query("SELECT COUNT(`id`) as hits FROM `responses` GROUP BY `qid`");
$me = array();
while($row = mysql_fetch_array($query)){
$me[] = $row['hits'];
}
if(!empty($me)) $max = max($me); ////// THIS IS LINE 18
$query = mysql_query("SELECT `questions`.`pid` FROM `responses`, `questions` WHERE `responses`.`qid`=`questions`.`id` AND `responses`.`ip`='".$_SERVER['REMOTE_ADDR']."' AND pid='".$poll['id']."'");
You must be passing an empty array to the max() function. Just check the array is not empty before calling the max() or min() function. You can check by count($arr) > 0, Here are a few key points from the documentation.
max() in php, returns the parameter value considered "highest" according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and 'abc') the first provided to the function will be returned.
If an empty array is passed, then FALSE will be returned and an E_WARNING error will be emitted.
The values of different types will be compared using the standard comparison rules. For instance, a non-numeric string will be compared to an integer as though it were 0, but multiple non-numeric string values will be compared alphanumerically. The actual value returned will be of the original type with no conversion applied. If the first and only parameter is an array, max() returns the highest value in that array. If at least two parameters are provided, max() returns the biggest of these values.
I have this code:
$local_id = $_GET['id'];
$sql = dbquery("SELECT * FROM `videos` WHERE `id` = ".$local_id." LIMIT 0, 1");
while($row = mysql_fetch_array($sql)){
$video_id = $row["youtube_id"];
// the rest
}
how can i check if $local_id does not exist in the db and display an error?
mysql_num_rows
if(mysql_num_rows($sql) == 0) {
//Show error
}
$sql = dbquery("select count(*) from videos where id = ".$local_id." LIMIT 0, 1");
$row = mysql_fetch_row($sql);
if($row[0] == 0)
echo 'error';
You can use the following query:
"SELECT COUNT(*) FROM `videos` WHERE `id` = ".mysql_real_escape_string($local_id)
This query will return one number: how many records have matched your query. If this is zero, you surely know that there are no records with this ID.
This is more optimal than other solutions posted in case you only want to check for the existence of the ID, and don't need the data (if you use SELECT * ..., all the data will be unnecessarily sent from MySQL to you). Otherwise mysql_num_rows() is the best choice, as #Ryan Doherty correctly posted.
Be sure to ALWAYS escape data that came from the outside (this time GET) before you put it into a query (mysql_real_escape_string() for MySQL).
If you fail to do so, you are a possible victim for SQL Injection.
You could have a $count variable and increment it in the while loop. After the loop, check the count, if it is 0, then echo an error message.