My problem is that I need to SELECT fields from a MYSQL table depending on a previous MYSQL SELECT. Before I did this through an if and else if statement when it could only be one of two things but now I've added a third and so this no longer works. This is the effect I want:
$call = "SELECT * FROM blog_posts WHERE id = $_GET[id] LIMIT 1";
$latest = mysql_query($call);
$result = mysql_fetch_array($latest);
$post_cat = $result['category'];
$sql="SELECT title, post_thumb, id FROM blog_posts WHERE category = $post_cat AND id <> $_GET[id] ORDER BY id DESC LIMIT 6";
Thanks in advance.
$sql="SELECT `title`, `post_thumb`, `id` FROM `blog_posts` WHERE category = '".$post_cat."' AND `id` = '".$_GET[id]."' ORDER BY `id` DESC LIMIT 6";
Put tables/columns in backticks and surround PHP variables in concatenated quotes. At the moment, your query asks MySQL to find a value in the category column which is $post_cat. Not the PHP variable $post_cat, the explicit string $_post_cat.
Related
I wanted to fetch data from MySQL with PHP when a user inputs something. I have this code.
$query = "SELECT * FROM mealplans WHERE plantitle LIKE '%$inputText%' AND `STATUS` = 1 OR plantitle LIKE '%$inputText%' AND userid = '$userid' GROUP BY plantitle, userid";
$result = mysqli_query($con, $query);
It works fine however, it fetches the oldest or first data from the group. How do I select the newest data?
I've search and found possible solutions by using FROM, JOIN, IN, etc. However, I do not know how to use them since I only know the basics. Hopefully someone could explain one solution for me.
There is a simple solution that you can do.
You can order your data to DESC order. I'm sure that you have an id(primary key) in your table.You just have to order all your datas' to DESC order of ids .So that your last inserted data set will be the one to be fetched since it's on the top.
change your query to: (add your primary key(in the following query i have added it as id) in the ORDER BY syntax)
$query = "SELECT * FROM mealplans WHERE plantitle LIKE '%$inputText%' AND `STATUS` = 1 OR plantitle LIKE '%$inputText%' AND userid = '$userid' GROUP BY plantitle, userid ORDER BY `ID` DESC"
Just add a condition in your query which only retrieves the row having the greatest id.
Find out the id first and then you can use the same query for that id:
SELECT MAX(id) FROM mealplans WHERE plantitle LIKE '%$inputText%' AND `STATUS` = 1 OR plantitle LIKE '%$inputText%' AND userid = '$userid' GROUP BY plantitle, userid
After getting the id and storing it in a variable (say $temp):
SELECT * from mealplans where `id` = $temp
Frame: MySQL server on localhost using XAMPP server.
I'm trying to insert all these fields in a particular table "tbl_labelled_images":
id_in_raw_image_table
image
label
gender
Out of them, image comes from another table named as "tbl_raw_image" and id_in_raw_image_table is the id of that image in table "tbl_raw_image".
Then label and gender are the inputs by the user taken on run time using radio buttons. But the problem is I cannot insert all these four attributes in a single query. Query just does not insert anything in the table if all of them are in the same query. I have tried following queries but none of them actually helped:
$label=mysqli_real_escape_string($conn, $_POST["radio"]);
$gender=mysqli_real_escape_string($conn,$_POST["radio-gender"]);
$query_insert="INSERT INTO labelled_images.tbl_labelled_image
(`label`,`gender`,`image`, `id_in_raw_image_table`) '$label','$gender',
SELECT image, id FROM raw_images.tbl_raw_image
WHERE raw_images.tbl_raw_image.id = $id_raw";
$insert_exec = mysqli_query($conn, $query_insert);
And
$sql = "SELECT * FROM tbl_raw_image WHERE id IN
(SELECT id FROM (SELECT id FROM tbl_raw_image ORDER BY RAND() LIMIT 1) t)";
$sth = $conn1->query($sql);
$result=mysqli_fetch_array($sth);
$id=$result['id'];
$image=$result['image'];
$label=mysqli_real_escape_string($conn, $_POST["radio"]);
$gender=mysqli_real_escape_string($conn,$_POST["radio-gender"]);
$query2="INSERT INTO tbl_labelled_image(image, label, id_in_raw_image_table) VALUES('$image','$label','$id'); ";
$rs = mysqli_query($conn2, $query2);
But none of them worked for me. As a work around I'm currently using a complex two step insertion as follows:
$sql = "SELECT * FROM tbl_raw_image WHERE id IN
(SELECT id FROM (SELECT id FROM tbl_raw_image ORDER BY RAND() LIMIT 1) t)";
$sth = $conn1->query($sql);
$result=mysqli_fetch_array($sth);
$id=$result['id'];
$image=$result['image'];
$label=mysqli_real_escape_string($conn, $_POST["radio"]);
$gender=mysqli_real_escape_string($conn,$_POST["radio-gender"]);
$query_insert="INSERT INTO labelled_images.tbl_labelled_image
(`image`, `id_in_raw_image_table`)
SELECT image, id FROM raw_images.tbl_raw_image
WHERE raw_images.tbl_raw_image.id = $id_raw;";
$insert_exec = mysqli_query($conn, $query_insert);
$labelled_id=mysqli_insert_id($conn);
$query_label = "UPDATE labelled_images.tbl_labelled_image SET
`label` = '$label', `gender` = '$gender' WHERE `id`=$labelled_id";
$label_insert_exec = mysqli_query($conn, $query_label);
$query_update_Is_labelled="UPDATE raw_images.tbl_raw_image SET `Is_labelled`= 1 WHERE id= $id_raw; ";
$update=mysqli_query($conn,$query_update_Is_labelled);
It works but it is far from ideal. So my question is that is there any way to perform this insert in one step? Or more generally what should be done when different fields of record to be inserted are from different sources?
You can try to use a static value in your MySQL select query SELECT '$label' as label,'$gender' as gender
complete query:
$query_insert="INSERT INTO labelled_images.tbl_labelled_image
(`label`,`gender`,`image`, `id_in_raw_image_table`)
SELECT '$label' as label,'$gender' as gender, image, id FROM raw_images.tbl_raw_image
WHERE raw_images.tbl_raw_image.id = $id_raw
";
Edited: remove the VALUES() before the SELECT
how would i go about ordering by a value that is not in the table where i am selecting from, in this instance the value $count1 is not in the table search.
count has the same identifying id as that of the thing it is being reffered to in the other table, this is where count1 is grabbed
$q = $db->prepare("SELECT COUNT(rating) FROM ratings WHERE id='$id' AND rating = 'd'");
$q->execute();
$count1 = $q->fetchColumn();
$query = "SELECT * FROM search WHERE title LIKE '$each' ORDER BY '$count1'"
$query = $db->prepare($query);
$query->execute();
that is from ratings, how would i go about ordering the entries like that, so that they are based off the number of count1 and are decided, i might have to implement something like
$query = "SELECT * FROM search WHERE title LIKE '$each' AND id = '$id' ORDER BY '$count1'"
$query = $db->prepare($query);
$query->execute();
Possible Duplicate: Mysql order by specific ID values
Same thing here, you'll just output your $count1as a comma separated string and add it in the SQL query as ORDER BY FIELD(COUNT,___comma_sep_string___)
ratings is a table, not a database. You can join tables or use subqueries to get the desired result, without having to make multiple queries.
You haven't described how the FOREIGN_KEY is set up in the ratings table, but assuming you have something ratings.search_id, this should work:
SELECT search.*, (SELECT COUNT(rating)
FROM ratings
WHERE ratings.search_id = search.id
AND rating = 'd'
) AS rating_count
FROM search
WHERE title LIKE '$each'
ORDER BY rating_count
for($i = 0;$i<10;$i++)
{
$query1 ="SELECT `id` FROM radcheck ORDER BY `id` DESC LIMIT 1;";
$lololo= mysql_query($query1) or die(mysql_error());
//echo $lololo;
$query = "INSERT INTO radcheck (username,attribute,op,value) VALUES ('teleuser".$lololo."','Cleartext-Password',':=','$arr1[$i]')";
mysql_query($query) or die(mysql_error());
}
I am trying to retrieve my latest id value to append with my username. And the value retrieve always be 'Resource id #4'.
Is there anyway to solve it ?
Thank you.
Mysql doesn't support TOP that is for SQL Server.
Instead of using TOP you can use mysql LIMIT so your query would be:
SELECT `id` FROM radcheck ORDER BY `id` DESC LIMIT 1;
You do not have to use single quotes around column names. if you need to escape it use backticks. And TOP is not mysql syntax. You have to use limit
SELECT `id` FROM radcheck ORDER BY `id` DESC limit 1
Do not longer use the depricated mysql_* API. Use mysqli_* or PDO
Remove the 's around field names -
"SELECT TOP 1 id FROM radcheck ORDER BY id DESC";
But as Daan told it will not work for mysql, then ORDER & LIMIT will do the trick.
"SELECT id FROM radcheck ORDER BY id DESC LIMIT 1";
i hope you never mind trying this pattern
Select id from radcheck WHERE id=1 ORDER BY 'id' DESC ;
I'm trying to find a solution to select a list of rows coming after a certain Id from an ordered list.
For example, first I select 1000 rows. Then, on a subsequent request, i want to fetch another 1000 rows coming from after the last id of the first request. I know i can do it with limit, but suppose there has been 100 rows added between the first and second request, there will be 100 rows that will be from the first request.
Both queries will be ordered by the date of the entries.
Here's an example of the query I thought of:
$query = "SELECT * FROM table WHERE id AFTER $id ORDER BY date DESC";
$query = "SELECT * FROM `table` WHERE `id` > '$id' ORDER BY `date` DESC LIMIT 1000";
Two ways to do this:
WHERE
"SELECT * FROM `table` WHERE `id` > '$id' ORDER BY `date` DESC LIMIT $length"
LIMIT
"SELECT * FROM `table` LIMIT $start, $length"
$query = "SELECT * FROM table WHERE id > $id ORDER BY date LIMIT 1000";
You're asking about logic, not code so here it is.
The first request selects the first 1000.
$query = "SELECT * FROM the_table ORDER BY `date` DESC LIMIT 0,1000";
NB date is a reserved word so needs escaping if you've called a column "date" which you shouldn't.
$rs=$db->selectMany($query); // replace this with however you select the rows. $rs is results set
Do stuff with PHP and save the maximum id. They may not be in order.
$maxid=0;
foreach ($rs as $r){
// whatever you need to do with your results
$maxid=max($maxid, $r->id);
}
Your subsequent select uses the last id
$query = "SELECT * FROM the_table WHERE id > $maxid ORDER BY date DESC LIMIT 0,1000";
BUT you need to take note that you're ordering by date and using id to find a breakpoint which sounds like it would cause data to be missed.
Perhaps you mean to use WHERE`date`> $maxdate? If so you can figure that out from the code given.