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'];
}
}
Related
Need your help.
php, mysql
I have the following project.
I have two tables
**table 1**
user_id Plan
1 5
1 7
2 5
2 9
3 7
1 9
**table 2**
Plan Price
5 100
7 200
9 300
I must find the total cost of plans selected by one user
eg user_id = 2 must pay 400
I have already the following code, but this one adds the Price of all Plans in database in the above example total cost = 600
What am I doing wrong? :(
$totalcost = NULL;
$sql = "select SUM(Plan.Cost) as ANSWER FROM Plan";
$result = mysql_query($sql, $link) or die(mysql_error());
$totalcost = mysql_fetch_row($result);
$sql = "select * FROM Plan";
$result = mysql_query($sql, $link) or die(mysql_error());
$rows = mysql_num_rows($result);
$Plan = array();
if (is_resource($result)) {
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$Plan[] = $row;
}
}
You have to specify the user_id in your query, like:
$user_id = 2; // or get it from $_GET, $_POST...
$sql = "select SUM(Plan.Cost) as ANSWER
FROM Plan, Users
WHERE Users.Plan = Plan.Plan AND Users.user_id = $user_id";
You probably want to use LEFT JOIN in your query, so you can make something like this:
SELECT table1.user_id, table1.plan, SUM(table2.cost) FROM table1 LEFT JOIN table2 ON table1.plan=table2.plan WHERE table1.user_id = $user_id;
this way you can fetch results in 1 query and make database do all the work instead of looping through data in functions etc.
SQL left join tutorial
I made this php script and i am tryin to make it to return next and previus row, but there is one problem when i input my id the script return different thing for example :
This is my DB
ID String
1 Test 1
2 Test 2
3 Test 3
4 Test 4
So if i put ./index.php?id=1 this returns the result of id=2 and id=2 => id=3 and so on...
My question is how to fix it to return accurate result not +1. I tried with <= or => operators the result is correct, but then my links doesnt work.
Here is the script
<?php
if(isset($_GET['id']))
{
$id = (int)$_GET['id'];
}else
{
$id = 0;
}
$stmt1 = $db->prepare("SELECT * FROM records WHERE id > ? ORDER BY id ASC LIMIT 1");
$stmt1->bindValue(1,$id);
$stmt1->execute();
$row = $stmt1->fetch();
$stmt2 = $db->prepare("SELECT * FROM records WHERE id < ? ORDER BY id DESC LIMIT 1");
$stmt2->bindValue(1,$id);
$stmt2->execute();
$row = $stmt2->fetch();
echo $row['id'];
echo "<br/>";
echo $row['string'];
?>
I am not sure if the problem as silly as that, but I have no other explanation.
To have your page you need to make 3 selects:
to get current page data
to get prev id
to get next one
But I can see only 2 selects
So, you have to select data for the very page to show
if(isset($_GET['id']))
{
$sql = "SELECT * FROM records WHERE id = ?";
$stm = $db->prepare($sql);
$stm->execute(array($_GET['id']));
} else {
$sql = "SELECT * FROM records ORDER BY id ASC LIMIT 1";
$stm = $db->query($sql);
}
$row = $stm->fetch();
and now you can go for getting prev and next ids
$sql = "SELECT id FROM records WHERE id < ? LIMIT 1";
$stm = $db->prepare($sql);
$stm->execute(array($row['id']));
$prev = $stm->fetchColumn();
$sql = "SELECT id FROM records WHERE id > ? LIMIT 1";
$stm = $db->prepare($sql);
$stm->execute(array($row['id']));
$next = $stm->fetchColumn();
i am tryin to make it to return next and previus row
There is no such thing as "previous" or "next" row in a table. Without explicit ordering, tables must be considered as unordered set of rows. And you shouldn't rely on auto_increment field to be sequentially numbered. For example:
because there was interleaved insert on the table,
because the server is allowed to reuse auto_increment after row deletion.
You probably have to modify your table structure to add a sequence number:
CREATE TABLE tbl (id in primary key not null auto_increment,
sequence_number int unique,
value char(40));
While inserting your data you might rely on something like that:
INSERT INTO tbl (sequence_number, value)
VALUES (SELECT COUNT(*) FROM tbl, ?)
And the query for the "next" and "prev":
SELECT * FROM tbl WHERE sequence_number = ?-1 OR sequence_number = ?+1
ORDER BY sequence_number;
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";
My page displays an image, and I want to display the previous and next image that is relevant to the current one. At the moment I run the same query 3x and modify the "where" statement with =, >, <.
It works but I feel there must be a better way to do this.
The image id's are not 1,2,3,4,5. and could be 1,2,10,20,21 etc. But if it is much more efficient I am willing to change this.
mysql_select_db("database", $conPro);
$currentid = mysql_real_escape_string($_GET['currentid']);
$query ="SELECT * FROM database WHERE id ='".$currentid."' LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$current_id = $row['id'];
$current_header = $row['title'];
$current_description =$row['desc'];
$current_image = "http://".$row['img'];
$current_url = "http://".$row['id']."/".$db_title."/";
$current_thumb = "http://".$row['cloud'];
}
mysql_select_db("database", $conPro);
$query ="SELECT * FROM database WHERE id <'".$currentid."' ORDER BY id DESC LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$previous_id = $row['id'];
$previous_header = $row['title'];
$previous_description =$row['desc'];
$previous_image = "http://".$row['img'];
$previous_url = "http://".$row['id']."/".$db_title."/";
$previous_thumb = "http://".$row['cloud'];
}else{
$previous_none = "true"; //no rows found
}
mysql_select_db("database", $conPro);
$query ="SELECT * FROM database WHERE id >'".$currentid."' ORDER BY id ASC LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$next_id = $row['id'];
$next_header = $row['title'];
$next_description =$row['desc'];
$next_image = "http://".$row['img'];
$next_url = "http://".$row['id']."/".$db_title."/";
$next_thumb = "http://".$row['cloud'];
}else{
$next_none = "true"; //no rows found
}
mysql_close($conPro);
Thank you for your time
You don't have to do select_db each time. Once you 'select' a db, it stays selected until you select something else.
You can't really get away from doing two separate queries to get the next/previous images, but you can fake it by using a union query:
(SELECT 'next' AS position, ...
FROM yourtable
WHERE (id > $currentid)
ORDER BY id ASC
LIMIT 1)
UNION
(SELECT 'prev' AS position, ...
FROM yourtable
WHERE (id < $currentid)
ORDER BY id DESC
LIMIT 1)
This would return two rows, containing a pseudofield named 'position' which will allow you to easily identify which row is the 'next' record, and which is the 'previous' one. Note that the brackets are required so that the 'order by' clauses apply to the individual queries. Without, mysql will take the order by clause from the last query in the union sequence and apply it to the full union results.
You can get the "previous" one first WHERE id <'".$currentid."' ORDER BY id DESC, and then query for two "above" it: SELECT * FROM database WHERE id >= '".$currentid."' ORDER BY id ASC then it takes only two queries instead of three.
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()