I'm having trouble getting my sql to pull in photos based on the column "order" which contains numbers. The following works fine, however it seems to be pulling in photos based on the "num" column in "cms_uploads".
$photoSql = "SELECT * FROM cms_uploads WHERE ('tableName'='residential_master_rental_availabilities' AND 'recordNum' = '".$rent['num']."' AND 'fieldname' = 'image') LIMIT 1";
This query returns nothing:
$photoSql = "SELECT * FROM cms_uploads WHERE ('tableName'='residential_master_rental_availabilities' AND 'recordNum' = '".$rent['num']."' AND 'fieldname' = 'image') ORDER BY 'order' LIMIT 1";
order is a reserved word.
You need backticks rather than single quotes for the order by. You are ordering by a constant -- that is, doing nothing:
ORDER BY `order`
To help with writing code, only use single quotes for string constants and dates.
Related
I have the following two queries. The first query is fetching a key called srNumber from first table called tags and then the second query is using that srNumber to fetch details from a second table called nexttable.
$tagQuery = "SELECT * FROM tags WHERE status = 0 AND currentStage = '1' AND assignedTo = '1' ORDER BY
deliveryDate ASC";
$tagQueryExecute = mysqli_query($conn, $tagQuery);
while($rows = mysqli_fetch_array($tagQueryExecute)){
$srNumber = $rows['srNumber'];
$nextQuery = "SELECT * FROM nexttable WHERE srNumber='$srNumber'";
$nextQueryExecute = mysqli_query($conn, $nextQuery);
$detailsFromNextTable = mysqli_fetch_array($nextQueryExecute);
//Show these details
}
For a small result this is not a big issue. But if the first query got so many results, then second query has to run as many times as number of loop. Is there any other way to do this efficiently?
NB: Please ignore the SQL injection issues with these queries. I just simplified it to show the problem
As you appear to have only 1 row in the second table, you would be better off with a join, MySQL: Quick breakdown of the types of joins gives some more info on the types of joins.
SELECT *
FROM tags t
JOIN nexttable n on t.srNumber = n.srNumber
WHERE t.status = 0 AND t.currentStage = '1' AND t.assignedTo = '1'
ORDER BY t.deliveryDate ASC
This also removes the SQL injection as well.
I would also recommend removing the * and just list the columns you intend to use, this also helps if you have columns with the same names in the different tables as you can add an alias to the specific columns.
FYI - the original problem you have is similar to What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?
I'm using Joshcam's PHP Mysqli Database Class (github) and have been fighting over comparing dates for a long while now.
Bottom line is could anyone explain this error message:
PHP Fatal error: Problem preparing query (SELECT * FROM jobs WHERE business_id = 5 AND active = 1 AND date_visit > `2015-01-01 05:02:14` ORDER BY date_appt DESC) Unknown column '2015-01-01 05:02:14' in 'where clause'
My query goes:
$jobs = $db->rawQuery("SELECT * FROM jobs WHERE business_id = $business_id AND active = 1 AND date_visit > `".$search_from."` ORDER BY date_appt DESC");
Why would my date input be considered a column instead of a field value?
I've tried double quotes, single quotes, no quotes, and it's either turning the quotes to ' or put off by the space between Y-m-d and H:i:s.
You are using backticks for query variable rather single quote so try to remove backticks from value($search_from) else it will be treat as column
$jobs = $db->rawQuery("SELECT * FROM jobs WHERE business_id = '$business_id' AND active = 1 AND date_visit > '$search_from' ORDER BY date_appt DESC");
Enclose the names of database objects (databases, tables, fields, indexes, triggers a.s.o.) in backquotes (``). This is usually not needed but it is useful (read "required") when the name is a MySQL reserved word.
Enclose the string literals in apostrophes ('2015-01-01 05:02:14') or quotes ("2015-01-01 05:02:14"):
SELECT *
FROM `jobs`
WHERE `business_id` = 5
AND `active` = 1
AND `date_visit` > '2015-01-01 05:02:14'
ORDER BY `date_appt` DESC
None of the field names in the query above is a MySQL keyword, there is no need to enclose them in backquotes. I only did it for explanatory purposes.
Your PHP code should read:
$jobs = $db->rawQuery("SELECT * FROM jobs WHERE business_id = $business_id AND active = 1 AND date_visit > '".$search_from."' ORDER BY date_appt DESC");
The issue was mainly that this class doesn't allow for
WHERE the_date > $date1
AND the_date < $date2
I actually had to use between to solve it.
My final code:
$params = array($business_id,1,$search_from,$search_to,$limit_end);
$jobs = $db->rawQuery("SELECT * FROM jobs WHERE business_id = ? AND active = ? AND date_visit BETWEEN ? AND ? ORDER BY date_appt DESC, id DESC LIMIT ?",$params,false);
I am trying to do a query in PHP PDO where it will grab a simple result. So like in my query I need it to find the row where the column group is 'Admin' and show what ever is in the group column. I know that we already know what it should be [Should be admin] but just need to get the query to work. Its only grabbing 1 row from my table, so will I need forsearch?
If I change WHERE group = 'Admin' to WHERE id = '1' it works fine. But I need it so it can be where group = 'admin'
$sql2 = "SELECT * FROM groups WHERE group = 'Admin'";
$stm2 = $dbh->prepare($sql2);
$stm2->execute();
$users2 = $stm2->fetchAll();
foreach ($users2 as $row2) {
print ' '. $row2["group"] .' ';
}
Thanks
group is a reserved word in MySQL, that's why it's not working. In general it's a bad idea to use reserved words for your column and table names.
Try using backticks around group in your query to get around this, so:
$sql2 = "SELECT * FROM groups WHERE `group` = 'Admin'";
Also you should really use placeholders for values, because you're already using prepared statement it's a small change.
Edit: just to clarify my last remark about the placeholders. I mean something like this:
$sql2 = "SELECT * FROM groups WHERE `group` = ?";
$stm2->execute(array('Admin'));
try to use wildcard in your WHERE Clause:
$sql2 = "SELECT * FROM groups WHERE group LIKE '%Admin%'";
Since the value in your table is not really Admin but Administrator then using LIKE and wildcard would search the records which contains admin.
Have some IDs:
$ids = "'55-30269','50-30261','50-30254','50-30257','50-30268','50-30253'";
Have this query:
$sql = "SELECT * FROM `report` WHERE `id` IN ($ids)";
I want the rows to be in the same order like specified in $ids.
Instead of that I get order by which these rows were originally inserted in table.
Also, i'm not sure why do I need each of id to be placed in quotes '55-30269', but query is not getting executed other way. E.g. $ids = "55-30269,50-30261,50-30254,50-30257,50-30268,50-30253";
Because the data type of ID is string. String literals must be wrap with single quotes. If you want to order the result based on the specified ID, use FIELD() for custom reordering.
SELECT *
FROM report
WHERE ID IN ($ids)
ORDER BY FIELD(ID, $ids)
FIELD()
The reason why you are not getting exact result when passing ID without single quotes,
$ids = "55-30269,50-30261,50-30254,50-30257,50-30268,50-30253"
is because MySQL performs arithmetic on the values.
55-30269 = -30216
50-30261 = -30211
...
I am running an mysql query and I am trying to order the results by there auto incrementing index value. I am running my query with this code.
$query = mysql_query("SELECT * FROM chanels WHERE videolocation != '' ORDER BY index DESC ");
This worked before I added the ORDER BY function and now when I run a mysql_num_rows test it is returning 0 rows. If you have any ideas thank you I appreciate it.
Are you sure that the column is called index? That is not an ideal choice for a column name because it is a reserved word. Normally the auto-increment column should be called id or similar.
If you really have called your column index then you need to quote it using backticks in your SQL queries:
SELECT * FROM chanels
WHERE videolocation != ''
ORDER BY `index` DESC
Edit yoru code like this
$query = mysqli_query("SELECT * FROM chanels
WHERE videolocation != ''
ORDER BY 'index' desc");
may it helps you