PDO fails when using "WHERE" in a query - php

I am using PHP, Silex, and a PostgreSQL database. I have a piece of code that executes exactly as expected:
$statement = $app['pdo']->query("SELECT * FROM my_table LIMIT 50");
$string = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($string);
return $json;
When I change one thing by adding a "WHERE" parameter, it fails:
$statement = $app['pdo']->query("SELECT * FROM my_table LIMIT 50 WHERE id > 3000");
$string = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($string);
return $json;
I checked that "id" is not capitalized in the schema and it is formatted as an integer. Id values in the table range from 1 to 5000, and it is populated with random entries, many of which should satisfy the query.
What is going wrong?

WHERE comes first
SELECT * FROM my_table WHERE id > 3000 LIMIT 50

Limit goes after the where clause
$statement = $app['pdo']->query("SELECT * FROM my_tableWHERE id > 3000 LIMIT 50");

Related

What if I don't fetch an SQL query?

So I was wondering what if at the end of a simple SQL query in PHP like this:
$sentence = $connection->prepare("
SELECT * FROM posts_comments WHERE comment_on = $id ORDER BY date DESC LIMIT 2
");
$sentence->execute();
return $sentence->fetchAll();
I didn't put the fetchAll() function, so it would be like this:
$sentence = $connection->prepare("
SELECT * FROM posts_comments WHERE comment_on = $id ORDER BY date DESC LIMIT 2
");
$sentence->execute();
Will there be any difference in the result or it would be the same?

How to count returned rows [duplicate]

I am using count function to get the number of rows buffered in a resultset.
But it always returns count as one even if resultset is empty.
Please see the code below:
$dbhandle = new SQLite3("sqlitedb_111.db");
$selQuery1 = "SELECT id,dbname,tabname,fieldname FROM scan_results ORDER BY id ASC LIMIT 0,10";
$resQuery1 = $dbhandle->query($selQuery1);
print count($resQuery1);
What am I doing wrong and how can I fix this?
As per your comment if you just want to return the count of records you could wrap your query in a SELECT COUNT(*) and change $dbhandle->query to $dbhandle->querySingle. This will work with or without LIMIT.
$dbhandle = new SQLite3("sqlitedb_111.db");
$selQuery1 = "SELECT COUNT(*) FROM (SELECT id,dbname,tabname,fieldname FROM scan_results ORDER BY id ASC LIMIT 0,10)";
$resQuery1 = $dbhandle->querySingle($selQuery1);
print count($resQuery1);
Result is an array. find the size of the array.
$dbhandle = new SQLite3("sqlitedb_111.db");
$selQuery1 = "SELECT id,dbname,tabname,fieldname FROM scan_results ORDER BY id ASC LIMIT 0,10";
$resQuery1 = $dbhandle->query($selQuery1);
$noofrows=sizeof($resQuery1);
echo $noofrows;
SQLite is an embedded database, i.e., there is no client/server communication overhead.
Therefore, it can return the results dynamically; there is only a single row buffered at any time.
To get the number of result rows, you either have to step through the results, or execute something like SELECT COUNT(*) FROM (original query).
Call numRows() on the result set.
From http://php.net/manual/en/function.sqlite-num-rows.php
<?php
$db = new SQLiteDatabase('mysqlitedb');
$result = $db->query("SELECT * FROM mytable WHERE name='John Doe'");
$rows = $result->numRows();
echo "Number of rows: $rows";
?>

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.

Count number of rows buffered in sqlite result set

I am using count function to get the number of rows buffered in a resultset.
But it always returns count as one even if resultset is empty.
Please see the code below:
$dbhandle = new SQLite3("sqlitedb_111.db");
$selQuery1 = "SELECT id,dbname,tabname,fieldname FROM scan_results ORDER BY id ASC LIMIT 0,10";
$resQuery1 = $dbhandle->query($selQuery1);
print count($resQuery1);
What am I doing wrong and how can I fix this?
As per your comment if you just want to return the count of records you could wrap your query in a SELECT COUNT(*) and change $dbhandle->query to $dbhandle->querySingle. This will work with or without LIMIT.
$dbhandle = new SQLite3("sqlitedb_111.db");
$selQuery1 = "SELECT COUNT(*) FROM (SELECT id,dbname,tabname,fieldname FROM scan_results ORDER BY id ASC LIMIT 0,10)";
$resQuery1 = $dbhandle->querySingle($selQuery1);
print count($resQuery1);
Result is an array. find the size of the array.
$dbhandle = new SQLite3("sqlitedb_111.db");
$selQuery1 = "SELECT id,dbname,tabname,fieldname FROM scan_results ORDER BY id ASC LIMIT 0,10";
$resQuery1 = $dbhandle->query($selQuery1);
$noofrows=sizeof($resQuery1);
echo $noofrows;
SQLite is an embedded database, i.e., there is no client/server communication overhead.
Therefore, it can return the results dynamically; there is only a single row buffered at any time.
To get the number of result rows, you either have to step through the results, or execute something like SELECT COUNT(*) FROM (original query).
Call numRows() on the result set.
From http://php.net/manual/en/function.sqlite-num-rows.php
<?php
$db = new SQLiteDatabase('mysqlitedb');
$result = $db->query("SELECT * FROM mytable WHERE name='John Doe'");
$rows = $result->numRows();
echo "Number of rows: $rows";
?>

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