MySQL returning wrong record - php

I am running a query on my page and it is returning the wrong results.
Here is my code:
$timestamp = time();
$query = "SELECT * FROM videos WHERE expire >= $timestamp AND home = 1 AND active = 1 ORDER BY id DESC LIMIT 1";
$result = mysql_query($query) or die(mysql_error());
if(mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
foreach ($row as $key => $value) {
$$key = $value;
}
}
The problem is, it is returning the SECOND record, and not the most recent ID. But, strange part is, if I run this in the Query window of MySQL, it returns the correct record.
This is the data on the record it should return:
id: 53, videoid: abc123, expire:1335596400, home: 1, active:1
Anyone have any ideas on this?

1335596400 is 28 april, so cleary is not the result from time();
It seems that you are runnign the query with another timestamp in MySQL (or without timestamp at all)

use
$query = "SELECT * FROM videos WHERE expire >= $timestamp AND home = 1 AND active = 1 ORDER BY id DESC LIMIT 0,1";
instead
$query = "SELECT * FROM videos WHERE expire >= $timestamp AND home = 1 AND active = 1 ORDER BY id DESC LIMIT 1";

Related

How to LOOP a SELECT query until it finds a data on database (PHP to MySQL)

I wanted to select a row in the database, but if row is not in the database, it should loop until it finds the
This line
$prev_date = date('M d, Y', strtotime($macrodate .' -1 day')); transforms the currentdate to one down (lets say Jun 15, it will transform to Jun 14). And use that date to check if the date is in the database, it not, it will loop and go to Jun 13. Until it could find the date.
How do I do this? What loop should I use?
$query = "SELECT * FROM users_macros WHERE userid = '$userid' AND `date` = '$macrodate'";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) == 0) {
while(1) {
$prev_date = date('M d, Y', strtotime($macrodate .' -1 day'));
$query2 = "SELECT * FROM users_macros WHERE userid = '$userid' AND `date` = '$prev_date'";
$result2 = mysqli_query($con, $query2);
if (mysqli_num_rows($result2) != 0) {
$row2 = mysqli_fetch_assoc($result2);
$targetcarbs = $row2['carbs'];
$targetproteins = $row2['proteins'];
$targetfats = $row2['fats'];
$con->query("INSERT INTO users_macros VALUES('','$userid','$targetproteins','$targetfats','$targetcarbs','$macrodate')");
break;
}
}
}
Don't use a loop. Just use a query that returns the row with the highest date lower than $macrodate. And you can combine that with the INSERT query.
And add a NOT EXISTS criteria to make it select nothing if the given date is already in the table.
Also, use a prepared statement to prevent SQL injection.
$stmt = mysqli_prepare($con, "
INSERT INTO users_macros
SELECT '', userid, proteins, fats, carbs, ? FROM users_macros
FROM users_macros
WHERE userid = ? AND date < ?
AND NOT EXISTS (
SELECT 1 FROM users_macros
WHERE userid = ? AND date = ?
)
ORDER BY date DESC
LIMIT 1");
mysqli_stmt_bind_param($stmt, "sss", $macrodate, $userid, $macrodate, $userid, $macrodate);
mysqli_stmt_execute($stmt);

getting all mysql results that is less than given id

i am working on a timeline for my website but i am having some problem when i ran the query to select all id that is less than given identifier its still return the identifier result upon every query
example if identifier is id=4 i want to select everything less than 4 and not from 4 > 3 > 2 > 1 i want it to be 3 > 2 > 1
here is my php. i know its not secure or what not but i have written it in prepared statement and get the same thign so i need some here.
if(isSet($_POST['lastmsg']))
{
$feed_id = mysqli_real_escape_string($con, $_POST['lastmsg']);
$get1 = mysqli_query($con, 'SELECT receiver FROM connection where sender="'.$_SESSION['userid'].'"');
$id_feed = array();
while($id_result1 = mysqli_fetch_array($get1)){
$id_feed[] = $id_result1['receiver'];
$ids1 = join(',', $id_feed);
$get_feed1 = mysqli_query ($con, "select * from feed where users in '".$ids1."' or users='".$_SESSION['userid']."' and 'feed_id' < '".$feed_id."' ORDER BY feed_id DESC LIMIT 2");
}
while($res1 = mysqli_fetch_array($get_feed1)){
echo $load = $res1['feed_id'];
}
}

Sort query by time and list next entries

I'm trying to sort this query by time.
I have a gaming match system. And I want to get a list of next 5 matches from my local time zone.
<?php
include_once "include/dbcompo.php";
$q=mysqli_query($con, "SELECT * FROM kamper ORDER BY tid LIMIT 5");
while($row = mysqli_fetch_array($q))
{
$clan1 = $row['clan1'];
$clan2 = $row['clan2'];
$server = $row['server'];
$tid = $row['tid'];
echo $clan1." ".$clan2." ".$server." ".$tid;
echo "<br />";
}
?>
Add a WHERE clause in your query: WHERE tid > NOW().
With NOW() you take the time of the server, maybe you should replace it with new DateTime(null)->getTimestamp()
Something like that:
<?php
mysqli_query($con, 'SELECT * FROM kamper WHERE tid > NOW() ORDER BY tid LIMIT 5');
// or
mysqli_query($con, 'SELECT * FROM kamper WHERE tid > '.new DateTime(null)->getTimestamp().' ORDER BY tid LIMIT 5');
?>
Two options:
1st option: Make the time field a numeric field and sort in PHP:
$queryResult = mysqli_query($con, $query);
while($row = mysqli_fetch_array($queryResult) {
$oldArray[$row['time'] = $row;
}
$array = ksort($oldArray);
foreach($array as $time=>$row) {
// do something
}
2nd option: Make a subquery
SELECT * FROM (
SELECT * FROM kamper WHERE timezone = 'UTC' ORDER BY tid
) LIMIT 5

Echoing out a date from a query

I would like $minutes below to be the oldest datecommented from the query (expressed in minutes). When I echo $minutes out, I get a blank result. What am I doing wrong?
$queryuidcount = "SELECT loginid, datecommented
FROM comment
WHERE (HOUR(NOW()) - HOUR(datecommented)) <= 1
AND loginid = '$uid'
ORDER BY datecommented ASC
LIMIT 1'";
$row2 = mysql_fetch_array($queryuidcount);
$minutes = $row2["datecommented"];
You need to execute mysql_query() on your query before you call mysql_fetch_array() on the result. Try this:
$result = mysql_query('SELECT loginid, datecommented FROM comment WHERE (HOUR(NOW()) - HOUR(datecommented)) <= 1 AND loginid = '$uid' ORDER BY datecommented ASC LIMIT 1');
$row = mysql_fetch_array($result);
$minutes = $row['datecommented'];
If your query returns multiple rows, you'll need to iterate through them with a while loop:
while($row = mysql_fetch_array($result)) {
//Fetch values from $row
}
Also, consider using PDO instead of the mysql function family.
I think you are doing it in the wrong way. Here you can find some examples.
mysql_fetch_array is not for DB connection or sql query.
http://php.net/manual/en/function.mysql-fetch-array.php

How do I get previous and next rows even though some rows have been deleted?

I have the following PHP functions that determine the next and previous rows in a database. However, there are lots of occasions when rows can be deleted and therefore my functions will not work as all they do is decrement the auto_increment field.
For example, current row 5. My function gives: 4 (previous) and 6 (next). What if 6 and 7 is deleted. My best idea is to keep querying until I get a row, but this seems inefficient, is there a better way?
Thanks all
//function to get next tweet
function getNextTweet($key, $direction){
$sql = "SELECT tweet_id FROM tweets WHERE tweet_key = '$key' LIMIT 1";
$result = mysql_query($sql) or die("DB Error : ". mysql_error());
$result = mysql_fetch_assoc($result);
if($direction=='next'){
$tweet_id = $result['tweet_id'] + 1;
}else{
$tweet_id = $result['tweet_id'] - 1;
}
$sql = "SELECT * FROM tweets WHERE tweet_id = '$tweet_id' LIMIT 1";
$result = mysql_query($sql) or die("DB Error : ". mysql_error());
return mysql_fetch_assoc($result);
}
Assuming you don't have a bajillion records...
Previous:
SELECT *
FROM table
WHERE (id < currentID)
ORDER BY id DESC
LIMIT 1
Next
SELECT *
FROM table
WHERE (id > currentID)
ORDER BY id ASC
LIMIT 1
If you run a modern version of MySQL, you can simplify your function into
function getNextTweet($key, $direction)
{
$cmp = ($direction == 'next') ? '>' : '<';
$order = ($direction == 'next') ? 'ASC' : 'DESC';
$sql = "SELECT *
FROM tweets
WHERE tweet_id $cmp (SELECT tweet_id FROM tweets WHERE tweet_key = '$key' LIMIT 1)
ORDER BY tweet_id $order
LIMIT 1";
$result = mysql_query($sql) or die("DB Error : ". mysql_error());
return mysql_fetch_assoc($result);
}
As long as "tweet_id" is indexed, the query will be very fast, even for millions of records.
One last thing, make sure that $key is properly validated! Otherwise, anyone can inject SQL in your query, that's a huge security flaw. If $key is anything but a hash key, it should at least go through mysql_real_escape_string()

Categories