PHP/MYSQL subquery causing undefined index error - php

I am trying to do a subquery using PDO:
$stmt = $pdo->prepare("SELECT sum(ros_ranking) FROM (SELECT ros_ranking FROM players WHERE teamid = 1 and positionid = 1 ORDER BY ros_ranking ASC LIMIT 1) AS totalrankings");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$num_rows= $stmt->rowCount();
echo "tqr= ".$row['totalrankings'];
I keep getting Notice: Undefined index: totalrankings in ...
ros_ranking is definitely a field with numbers in it in my Players table and a teamid of 1 and positionid of 1 definitely exist.
Does anyone see what I'm doing wrong here? FYI, if I do just the subquery as the main query, it works. So something must be wrong with SELECT sum(ros_ranking) FROM or AS totalrankings but they seem pretty straightforward.

Wrong alias use/position
you need a column name alias for totalrankings (not a table name alias as you have done)
$stmt = $pdo->prepare("SELECT sum(t.ros_ranking) totalrankings
FROM (SELECT ros_ranking
FROM players
WHERE teamid = 1
AND positionid = 1
ORDER BY ros_ranking ASC LIMIT 1) t");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$num_rows= $stmt->rowCount();
echo "tqr= ".$row['totalrankings'];

total_rankings is an alias for the subquery, it's not an alias for the column. You need to put AS totalrankings after the SUM() expression.
$stmt = $pdo->prepare("
SELECT sum(ros_ranking) AS totalrankings
FROM (
SELECT ros_ranking
FROM players
WHERE teamid = 1 and positionid = 1
ORDER BY ros_ranking ASC
LIMIT 1) AS subquery");
But LIMIT 1 in the subquery means you're not going to get a sum of anything. The subquery just returns 1 row, and the sum of one thing is just that value.

Though you can fix it, by giving the selected column the right alias, there is no need to fetch an array if your query returns only one column. Use fetchColumn() instead:
$stmt = $pdo->prepare("SELECT ...");
$stmt->execute();
$totalrankings = $stmt->fetchColumn();
$num_rows= $stmt->rowCount();
echo "tqr= ".$totalrankings;

Related

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.

Error when using "ORDER BY count" in query

I'm using the following query to display some information:
$result = mysqli_query ($con,"SELECT * FROM files,members,member_group WHERE files.member_id = members.member_id AND members.member_id = member_group.member_id AND group_id='$id' ORDER BY count DESC ");
My issue is it works fine when I leave out ORDER BY count DESC but when it is there I get the following error:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in /proj/co600/project/repo/public_html/select_field3.php on line 227
Count is a column in my database which records the number of times a publication is downloaded.
count is an aggregate function, so you need to surround it with backticks.
To get a clear cut picture of your error.. You need to change your code like..
$result = mysqli_query ($con,"SELECT * FROM files,members,member_group WHERE files.member_id = members.member_id AND members.member_id = member_group.member_id AND group_id='$id' ORDER BY count DESC ");
if(!$result)
{
die(mysqli_error($con));
}
You are having MySQL reserved keyword as column name in table.
Use Below query:
$result = mysqli_query ($con,"SELECT * FROM files,members,member_group WHERE files.member_id = members.member_id AND members.member_id = member_group.member_id AND group_id='$id' ORDER BY `count` DESC ");

MySQLi , declare variable and using math to count a median

I am trying to do some math in this SQL query. I'm not used to this syntax. Trying to count a median for line 3 in the query.
-?- = Can I put a variable here?
-??- = Can I make this line a variable some how?
This is the code I have done:
if(!isset($_SESSION["username"])):
$sql_art_sum = "SELECT (SELECT count(*) FROM post WHERE user_id = ?), **-?-**
(SELECT count(*) FROM comment),
(SELECT count(*)/ **-??-** FROM comment)";
if($stmt = $mysqli->prepare($sql_art_sum)) {
$stmt->bind_param('i', $_SESSION['id']);
$stmt->execute();
$stmt->bind_result($art_sum, $comment_sum, $comment_median);
$stmt->fetch();
$stmt->close();
}
When creating new variables in mysql you need to use 'AS' so for example:
SELECT x, y,
(SELECT SUM(x) - sum(y)
FROM tablename
WHERE b <= c
) as z
FROM tablename
Hope this is the answer you are searching for

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

SQL_CALC_FOUND_ROWS not working

so I execute query:
SELECT SQL_CALC_FOUND_ROWS * FROM table l LIMIT 10, 20;
which returns 20 rows from table, and there are a total 553 rows in the table
Then i immediately execute SELECT FOUND_ROWS();
But this instead only returns the number 1, despite the fact that there are 553 rows in my table (it's supposed to return 553, am I correct?)
what did I do wrong?
I suspect you have a syntax error, as names in SQL are not supposed to contain spaces. Try adding square brackets around [table 1], if that is the name of your table.
Remove your limit, I think there it is not showing 20 rows; it is showing only 10 rows.
$sql = "SELECT SQL_CAL_FOUND_ROWS * FROM users "; //don;t write table then table name
$result = mysql_query($sql);
//Use these according to your requirements:
$sql = "SELECT SQL_CAL_FOUND_ROWS * FROM users ";
$result = mysql_query($sql);
$sql = "SELECT FOUND_ROWS() AS `found_rows`";
$rows = mysql_query($sql);
$rows = mysql_fetch_assoc($rows);
$total_rows = $rows['found_rows'];

Categories