MySQL 1 Table, 1 Select, Multiple Wheres - php

I am trying to add a "Related Products" section below my product. I can only get this to work if
I use two separate SELECTS. I am trying to combine them but can't get it to work.
Same Table in MySQL -
<?php
//select items from db
$items = mysql_query
("SELECT * FROM table WHERE (myinvno='dg300')
OR (action='alive' AND cate='dogs'
ORDER BY productNo ASC LIMIT 0, 4)");
or die(mysql_error());
while($item = mysql_fetch_array($items))
{
?>
This part is for the Related Products section:
OR (action='alive' AND cate='dogs'
ORDER BY productNo ASC LIMIT 0, 4)");
Thank you ~

The correct syntax would look like:
$items = mysql_query("
SELECT *
FROM table
WHERE (myinvno = 'dg300') OR
(action = 'alive' AND cate = 'dogs')
ORDER BY productNo ASC
LIMIT 0, 4"
);
You were missing a closing parent after 'dogs'.
EDIT:
Hmmm . . . I wonder if this is what you want:
SELECT *
FROM table
WHERE (myinvno = 'dg300')
UNION ALL
(SELECT *
FROM table
WHERE (myinvno <> 'dg300') AND
(action = 'alive' AND cate = 'dogs')
ORDER BY productNo ASC
LIMIT 0, 4
);
This gets all rows that match the first condition plus four more that match the second.

Related

I need to reverse the order of my ORDER BY results

I need to get 3 rows with the lowest value in a certain column, and then reverse the order of these 3 rows. So if the 3 rows with the lowest value are A, B and C, I need to sort them as C, B and A. Could I do that in a single SQL statement?
$sql = "SELECT * FROM ratings_table ORDER BY rating DESC LIMIT 3";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0)
{
while ($row = mysqli_fetch_assoc($result))
{
echo "<td>".$row['rating']."</td>";
}
}
With this code I will get the right results but in the wrong order.
You'll want to use a subquery, like this:
SELECT *
FROM
(
SELECT *
FROM ratings_table
ORDER BY rating ASC LIMIT 3
) a
ORDER BY rating DESC
This will take the lowest three results , then flop the order.
Only a sub-query will work. First you select the 3 lowest values and then sort them.
Something like:
SELECT * FROM (
SELECT <COLUMN_VALUE>
FROM <YOUR_TABLE>
ORDER BY <COLUMN_VALUE> LIMIT 3
) T
ORDER BY <COLUMN_VALUE> DESC
$sql = "SELECT * FROM ratings_table ORDER BY rating DESC LIMIT 3";
$result = mysqli_query($conn, $sql)->fetch_all();
krsort($result)
foreach ($result as $row)
{
echo "<td>".$row['rating']."</td>";
}

SELECT query failing when I added a WHERE statement in it

I had a SELECT query like this at first..
($con,"SELECT * FROM users ORDER BY id ASC LIMIT 1");
But, I realized that I needed the newest user out of the groups 2, 3, 4, or 5 (excluding group 1). So in the end I only want one user showing that is the newest.
What is wrong with my SELECT query now that it would not show up anything?
//Newest Member
$member = mysqli_query($con,"SELECT * FROM users WHERE `group`=2, 3, 4,5 ORDER BY id ASC LIMIT 1");
$numrows_member = mysqli_num_rows($member);
if($numrows_member > 0){
while($row_member = mysqli_fetch_assoc($member)){
$memberid = $row_member['id'];
$member_username = $row_member['username'];
echo $member_username;
}
} else {
echo "No Members Found...";
}
You are looking for the IN operator. The syntax would be like this:
SELECT *
FROM users
WHERE `group` IN (2, 3, 4, 5)
ORDER BY id ASC
LIMIT 1;
There is a reference here.
Note: Based on your comment, if you are looking for the latest user you may want to order in DESC order instead, so that the largest id is put first. Even better (in my opinion), if you store the account_created_date you could order by that. Again, in descending order.
If you want to exclude a specific group, use != instead of trying to find one of the remaining groups:
SELECT * FROM users WHERE `group` != 1 ORDER BY id ASC LIMIT 1

Creating a subquery with mysqli in PHP to fetch array last 10 results in ascending order

I thought this would be simple but I'm having a tough time figuring out why this won't populate the the data array.
This simple query works fine:
$queryPrice = "SELECT price FROM price_chart ORDER BY id ASC LIMIT 50";
$resultPrice = mysqli_query($conn, $queryPrice);
$data = array();
while ($row = mysqli_fetch_array($resultPrice)) {
$data[] = $row[0];
}
But instead I want it to choose the last 10 results in Ascending order. I found on other SO questions to use a subquery but every example I try gives no output and no error ??
Tried the below, DOESN'T WORK:
$queryPrice = "SELECT * FROM (SELECT price FROM price_chart ORDER BY id DESC LIMIT 10) ORDER BY id ASC";
$resultPrice = mysqli_query($conn, $queryPrice);
$data = array();
while ($row = mysqli_fetch_array($resultPrice)) {
$data[] = $row[0];
}
I also tried specifying the table name again and using the IN, also doesn't work:
$queryPrice = "SELECT price FROM price_chart IN (SELECT price FROM price_chart ORDER BY id DESC LIMIT 10) ORDER BY id";
$resultPrice = mysqli_query($conn, $queryPrice);
$data = array();
while ($row = mysqli_fetch_array($resultPrice)) {
$data[] = $row[0];
}
In both examples my array is blank instead of returning the last 10 results and there are no errors, so I must be doing the subquery wrong and it is returning 0 rows.
The subquery doesn't select the id column, so you can't order by it in the outer query. Also, MySQL requires that you assign an alias when you use a subquery in a FROM or JOIN clause.
$queryPrice = "SELECT *
FROM (SELECT id, price
FROM price_chart
ORDER BY id DESC LIMIT 10
) x ORDER BY id ASC";
$resultPrice = mysqli_query($conn, $queryPrice) or die (mysqli_error($conn));
$data = array();
while ($row = mysqli_fetch_assoc($resultPrice)) {
$data[] = $row['price'];
}
You would have been notified of these errors if you called mysqli_error() when the query fails.
Your second query is the closest. However you need a table alias. (You would have seen this if you were kicking out errors in your sql. Note you will need to add any field that you wish to order by in your subquery. In this case it is id.
Try this:
SELECT * FROM (SELECT price, id
FROM price_chart ORDER BY id DESC LIMIT 10) as prices
ORDER BY id ASC
You must have errors, because your SQL queries are in fact incorrect.
First, how to tell you have errors:
$resultPrice = mysqli_query (whatever);
if ( !$resultprice ) echo mysqli_error($conn);
Second: subqueries in MySQL need aliases. So you need this:
SELECT * FROM (
SELECT id, price
FROM price_chart
ORDER BY id DESC LIMIT 10
) AS a
ORDER BY id ASC";
See the ) AS a? That's the table alias.

MYSQL - Get Next and Previous Record by ID - HTML for hyperlinks

So I'm trying to add a little bit of convenience to a CRUD by adding next and previous links to navigate between records in my database.
Here are my queries:
$id=$_GET['id'];
$id = $currentid;
$prevquery= "SELECT * FROM inventory WHERE id < $currentid ORDER BY id DESC LIMIT 1";
$prevresult = mysql_query($prevquery);
$nextquery= "SELECT * FROM inventory WHERE id > $currentid ORDER BY id ASC LIMIT 1";
$nextresult = mysql_query($nextquery);
?>
Here is my HTML:
Previous
Next
Now I tested these queries in PHPMyAdmin and they produced the result I wanted, but I can't get my hyperlinks to actually be supplied with the correct IDs... they're just blank after the =. What am I doing wrong?
mysql_query() returns a result set (resource). To get the actual rows from the result set, you need to use a function like mysql_fetch_row().
Your code for the "next" link would look something like:
PHP
$nextquery= "SELECT * FROM inventory WHERE id > $currentid ORDER BY id ASC LIMIT 1";
$nextresult = mysql_query($nextquery);
if(mysql_num_rows($nextresult) > 0)
{
$nextrow = mysql_fetch_row($nextresult);
$nextid = $nextrow['id'];
}
HTML
Next
and the previous link would be done similarly.
Obligatory note: For new code, you should seriously consider using PDO.
Advanced note:
You could combine your queries into a single query like:
SELECT
(
SELECT id
FROM inventory WHERE id < $currentid ORDER BY id DESC LIMIT 1
) AS previd,
(
SELECT id
FROM inventory WHERE id > $currentid ORDER BY id ASC LIMIT 1
) AS nextid
And then adjust the logic accordingly.
Okay, It took a little bit but I figured it out...
PHP
$prevquery= "SELECT * FROM inventory WHERE id < $currentid ORDER BY id DESC LIMIT 1";
$prevresult = mysql_query($prevquery) or die(mysql_error());
while($prevrow = mysql_fetch_array($prevresult))
{
$previd = $prevrow['id'];
}
$nextquery= "SELECT * FROM inventory WHERE id > $currentid ORDER BY id ASC LIMIT 1";
$nextresult = mysql_query($nextquery) or die(mysql_error());
while($nextrow = mysql_fetch_array($nextresult))
{
$nextid = $nextrow['id'];
}
HTML
Previous
Next
Thanks for the help, I think it put me on the right course. I'll look into that PDO stuff for the future. I'm just now starting to get a hang of the old MYSQL/PHP syntax and now all the sudden there's a new format... tough to keep up with it all!
The resultant code has a culprit at the very beginning and end of the table. Your code will "die" as you ordered. Instead you might check the query results ($prevresult, $nextresult) and decide NOT to show a link for previous or next item.
SELECT
IFNULL(
(SELECT id FROM inventory WHERE id < $currentid ORDER BY id DESC LIMIT 1 ) , (SELECT id FROM inventory ORDER BY id DESC LIMIT 1 )
) AS previd ,
IFNULL(
(SELECT id FROM inventory WHERE id > $currentid ORDER BY id ASC LIMIT 1 ),
(SELECT id FROM inventory ORDER BY id ASC LIMIT 1 )
) AS nextid

Get total rows count of table

I want to get all rows count in my sql.
Table's first 2 columns look like that
My function looks like that
$limit=2;
$sql = "SELECT id,COUNT(*),dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$stmt->bind_result($id, $total, $datetime, $title, $content);
$stmt->store_result();
$count = $stmt->num_rows;
if ($count > 0) {
while ($stmt->fetch()) {
Inside loop, I'm getting exact value of $total, but MySQL selects only 1 row - row with id number 1. (and $count is 1 too)
Tried this sql
SELECT id,dt,title,content FROM news ORDER BY dt DESC LIMIT 2
All goes well.
Why in first case it selects only 1 row? How can I fix this issue?
for ex my table has 5 rows. I want to get 2 of them with all fields, and get all rows count (5 in this case) by one query.
Remove COUNT(*). You will only ever get 1 row if you leave it in there.
Try adding GROUP BY dt if you want to use COUNT(*) (not sure why you're using it though).
EDIT
Fine, if you insist on doing it in a single call, here:
$sql = "SELECT id,(SELECT COUNT(id) FROM news) as total,dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
This is likely cause by the variable $limit being set to 1, or not being set and mysql defaulting to 1. Try changing your first line to
$sql = "SELECT id,COUNT(*),dt,title,content FROM news ORDER BY dt DESC";
EDIT
Change to:
$sql = "SELECT SQL_CALC_FOUND_ROWS,id,dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
And then use a second query with
SELECT FOUND_ROWS( )
to get the number of rows that match the query
This totally wreaks of a HW problem... why else besides a professor's retarded method to add complexity to a simple problem would you not want to run two queries?
anyways.... here:
SELECT id, (SELECT COUNT(*) FROM news) AS row_count, dt, title, content FROM news ORDER BY dt DESC LIMIT

Categories