PHP sqlsrv_query dynamic order by clause - php

(Note that this is for MSSQL, not MYSQL)
Does anyone know why this doesn't work?
$query = "SELECT * FROM table WHERE SeriesID = ? ORDER BY ? ?";
$result = $conn->getData($query, array($seriesID,$sortBy,$sortOrder));
I don't see any errors, but no results are returned.
When I don't have the ORDER BY portion, it works. It's the second and third question marks that kill it.
$conn->getData() is calling sqlsrv_query() function...
There is a similar question here which I answered with a workaround, but I'd like to find out why this doesn't work as I think it should.

Related

SQL query doesnt find exact name from database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
SELECT * FROM hge_funcionarios
JOIN hospitais
ON hge_funcionarios.hospital_id = hospitais.id_hospitais
JOIN funcoes
ON hge_funcionarios.funcao_id = funcoes.id_funcoes
WHERE nome LIKE '%$search%'
ORDER BY hospital_id DESC
When I try the exact name from the database doesnt show up any results.
If i search "Larissa" or "LARISSA", I get no results even in my database having "LARISSA CAMPOS".
If I try "lar" or anything like this I can find it, but when it gets too close to the name on database like "LARISS" I can't find it any more.
I tried collate and charset but no success.
EDIT: Its not a Query error with ambiguous column name in SQL because column names are distinct.
I'm writing this answer since it's not possible to show it in the comments. Feel free to disregard it.
The problem you are facing seems to be related to the injection of parameter values into your SQL query. The easy (dangerous) way is to simply concatenate strings, as in:
$stmt = $conn->prepare(
"select * from my_table where name = '" . $param1 . "'");
Even though it works for simple cases, your case is more complicated, and confusing. Most of the time you'll use Prepared Statements as in:
$stmt = $conn->prepare("select * from my_table where name = ?");
$stmt->bind_param("sss", $param1);
This way, the parameter will be injected the right way. In your case you'll need to prepend and append % to your parameter, since it'll be used for a LIKE operator.
WHERE nome LIKE '%$search%'
May be $ is the Reason.Try Like : WHERE nome LIKE '%search%'

Use multiple conditions in SQL WHERE clause using OR

I've got the following SQL statement in my PHP code:
$strSQL = "SELECT * FROM coaches WHERE pastors='1' OR all_categories='1' ORDER BY l_name";
but the WHERE portion after the OR is ignored. Is my code correct? Is there a better way to code it?
Thanks for the suggestions. Even though people said it should work, for some reason it wasn't. The easiest solution was to simply set every true/false to 1 for those individuals who want to be in all categories instead of trying to fight against the OR which looks correct but won't work.
I am trying to get it to select database entries if there is a 1 in a particular category, in this case "pastors", or if there is a 1 in the "all_categories" category.
From the looks of it, your code does just that.
You're just forgetting ASC or DESC at the end of it.
It should look more like this:
$strSQL = "SELECT * FROM coaches WHERE pastors='1' OR all_categories='1' ORDER BY l_name ASC";

Is there any simplification for this? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Is there any simplification for this?
$query = $this->link->prepare('SELECT * FROM test WHERE id = :id LIMIT 1')
$query->bindParam(':id', $id);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
unlink($row['avatar']);
$query = $this->link->prepare('DELETE FROM test WHERE id = :id LIMIT 1');
$query->bindParam(':id', $id);
$query->execute();
I don't like to advise people to skip using query parameters. You should get into the habit of doing it.
It's actually not hard, and it makes it simpler to write queries because you never have to think about whether you got the right kind of escaping and quoting. I find it makes my code look more clear.
I've always been puzzled how people learn that they need to use bindParam() for everything with PDO. It's simpler in most cases to pass an array of parameters to execute(). The only case when I typically use bindParam() is if I need to pass a NULL value.
Also you don't need to use named parameters, you can use positional parameters (but don't mix these parameter types in a given query).
fetchColumn() is simpler if you only need one column. Speaking of which, avoid SELECT * when you don't need all the columns.
If you are querying for a specific id, assuming that's the primary key, then you don't need LIMIT 1. There can be at most one row for a specific value in any unique key.
I assume you've enabled the exception-based error reporting. If not, you should check the result from each call to prepare() and execute() because they return false on error.
$query = $this->link->prepare('SELECT avatar FROM test WHERE id = ?')
$query->execute([$id]);
$avatar = $query->fetchColumn();
unlink($avatar);
$query = $this->link->prepare('DELETE FROM test WHERE id = ?');
$query->execute([$id]);
PS: The short syntax for arrays, like [$id], requires PHP 5.4
Thank you for the good question. To my utter disappointment, such questions are extremely rare on this site.
Is there any simplification for this?
Sure.
This is called "programming".
Although for the average PHP user programming stands for just putting several predefined blocks together, like LEGO bricks, in reality programming stands more for invention, for creating something new. And no less for optimizing too, for taking less moves for the same action.
A programmer could always create a function to encapsulate repeated tasks. Eventually he may wish to put such functions together into a class, but that's not the point.
As you can see, most of your operators just repeated ones. Every time you see a repetition you know for sure there can be a function or at least a loop.
Here is your code using my attempt in programming, aimed (beside extra safety) to the very code shortening:
$name = $this->link->getOne('SELECT avatar FROM test WHERE id = ?i', $id)
unlink($name);
$this->link->query('DELETE FROM test WHERE id = ?i', $id);
As you can see, this code is Extra DRY (stands for Don't Repeat Yourself) - all the repeated code is just taken away into internals.
Well, as you can see, my class is built upon mysqli. but of course something similar can be done even using ugly PDO, using wrapper sort of one I posted recently:
$name = $this->link->query('SELECT avatar FROM test WHERE id = ?', [$id], "one");
unlink($name);
$this->link->query('DELETE FROM test WHERE id = ?', [$id]);
By the way, taking programming little further you may shorten this code even more:
unlink($avatar_dir.$id.".png");
$query = $this->link->query('DELETE FROM test WHERE id = ?i', $id);
as avatar image obviously don't need no dedicated name and just id can serve perfectly, saving you extra field in database and extra query. All avatars can be converted to single format at the time of upload, to reduce the headache even more.

MySQL ORDER BY statement returning boolean?

I have absolutely no idea why this is happening, but my simple MySQL statement using an ORDER BY ... DESC command gives a really weird error when I try to perform the query.
The error is
mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in E:/.../home.php on line 23
And my code is:
$data = mysql_query("SELECT * FROM `blogposts` LIMIT 0, 30 ORDER BY id DESC");
while($results = mysql_fetch_assoc($data))//error here
I can't find out why. Any help is appreciated.
Oh, by the way, I know that everyone who looks at this question is going to rip into me for still using mysql.* libraries and there will be a highly upvoted comment about the evils of it and the fact that I am vulnerable to SQL injection. To answer before it's asked, as it were, this is not going online, it's purely a home project running on localhost. So don't even bother lecturing me.
ORDER BY clause must come before the LIMIT clause
SELECT * FROM `blogposts` ORDER BY id DESC LIMIT 0, 30

Parameterized Queries PHP/MySQL [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I create a PDO parameterized query with a LIKE statement in PHP?
PHP PDO prepared statement — mysql LIKE query
I'm trying to make a search engine for my website, and right now I'm just trying to make sure the connection is all and well. Here is my code thus far:
EDITED CODE (Still doesn't work, but here's where I'm at with the suggestions thus far):
$db = new PDO("mysql:host=".DB_SERVER.";dbname=".DB_NAME, DB_USER, DB_PASS);
$stmt = $db->prepare("SELECT * FROM table_1 WHERE name LIKE ? ORDER BY bid DESC");
$stmt->bindParam(1, "%{$_GET['s']}%", PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll();
I tried to see if the different methods of execute would do anything, but regardless of which way above I write it, I get the same result, nothing. I want the % wildcard in there so it does it'll search anywhere in name. On that note, am I using it correctly? The thing that confuses me most is when I type in the exact same query into PHPMyAdmin, the query runs through fine, so my guess is that I'm screwing up the PDO somewhere.
EDIT: PHPMyAdmin Query:
SELECT *
FROM table_1
WHERE name LIKE '%Test%'
ORDER BY bid DESC
LIMIT 0 , 30
This returns 1 result, as it is expected to. What is different about my code and this query? :/
I don't really understand what your question is, but I'm guessing you don't know how to add the %? If so, try this:
$stmt = $db->prepare("SELECT * FROM table_1 WHERE name LIKE ? ORDER BY bid DESC");
$stmt->bindValue(1, "%{$_GET['s']}%", PDO::PARAM_STR);
$stmnt->execute();
// fetch and win! :-)
A little explanation:
PDO will quote and escape the parameter ? appropriately. This means, that if you are binding hello, PDO will substitute ? with 'hello' (note the quotes). Therefore, in order to have the % inside the quotes, you will have to add them to what is binded, in this case $_GET['s'].

Categories