SQL query doesnt find exact name from database [closed] - php

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%'

Related

sql statement in PHP doesn't update the 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 1 year ago.
Improve this question
When I put a number myself the database gets updated to Success but when I try to access the same number from $_POST It complete the transaction but doesn't affect the rows even thought it's using the same number.
Example of a query that works perfectly and updates the database
$sql = "UPDATE `transactions` SET `status` ='Success' WHERE `transactions`.`txn_id` = 65765756";
Example of a query that doesn't work
$sql = "UPDATE `transactions` SET `status` ='Success' WHERE `transactions`.`txn_id` = ".$_POST['m_payment_id'];
First, check what's in the value, and make sure it is the same as what you are manually entering.
var_dump($_POST['m_payment_id'])
Second, the code without any other checks is a SQL injection vulnerability.
You could convert the value into an integer to protect against this, e.g. intval($_POST['m_payment_id'])
Ideally though, you would be using bindings.

PHP - Trouble with SQL query [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 6 years ago.
Improve this question
I have this query:
SELECT * FROM items WHERE itemcategory= 123 AND itemname LIKE '%abc%';
I want to pass parameters to itemcategory and itemname; I tried something like this:
SELECT * FROM items WHERE itemcategory=".'$categoryid'." AND itemname LIKE" ."'%$itemname%'"." AND shopid=5003;
It didn't work. Can anyone help?
What you are doing is nearly right, but you can de complicate the string concatenation, if you remember that $var is automatically expanded in a double quoted string
So this is easier to read and notice spacing issues, which is all I think that was wrong with your statement
$q = "SELECT *
FROM items
WHERE itemcategory = '$categoryid'
AND itemname LIKE '%$itemname%'
AND shopid=5003";
Assuming you have valid data in these variables this should work
The only danger with doing this rather than using prepared parameterised queries is that you risk SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared statement and parameterized statements

Select values from mysql table with php [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 7 years ago.
Improve this question
Please explain to me why it is not working.
$sql = "SELECT nombre,precio,presentacion FROM '$keywords'";
I used the next code and it worked but it's not what I need
$sql = "SELECT nombre,precio,presentacion FROM productos";
You're using the incorrect quotes (Identifier Qualifiers) for your table, being single quotes.
$sql = "SELECT nombre,precio,presentacion FROM '$keywords'";
needs to read as
$sql = "SELECT nombre,precio,presentacion FROM `$keywords`";
While unknown as to which MySQL API you are using to connect with, using error checking on the query, would have thrown a syntax error.
Now, if your table name doesn't contain spaces or hyphens or a reserved word or anything else to give MySQL to complain about, you can just remove the quotes.
$sql = "SELECT nombre,precio,presentacion FROM $keywords";
For more information on Identifier Qualifiers, visit:
https://dev.mysql.com/doc/refman/5.0/en/identifier-qualifiers.html
Error checking link references:
http://php.net/manual/en/function.mysql-error.php - MySQL_*
http://php.net/manual/en/mysqli.error.php - MySQLi_*
http://php.net/manual/en/pdo.error-handling.php - PDO
Footnotes:
If you're assigning "productos" to the $keywords variable (which seems to be the case), such as:
$keywords = "productos";
then you can omit the quotes/ticks around that variable in your query.
Remove the ticks from your table name. Hopefully $keywords is not a user supplied value or you will need to sanitize it
$sql = "SELECT nombre,precio,presentacion FROM $keywords";

How to search in all columns of a table [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I would like to know how I can search a substring in all columns of a table when I do not know the names of the columns? Is there a foreach-loop-functionallity I do not know?
If I understand you correctly then this may work, brute forces a search through all the results.
Here is a PDO-based example:
$stmt = $dbh->prepare("SELECT * FROM table");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
foreach($row as $column){
if(strpos($column, "find me") !== false)
echo $match."found in:".$column."<br />";;
}
}
I am also lazy. I am also a ColdFusion programmer, not php. However programming logic is the same no matter what the language. I would do this:
Step 1 - Run this query and output the results somewhere
select *
from mytable
where 1 = 2
The outputted results will include the field names. Copy and paste then into your source code as a comment. Delete the ones that you are not going to query. Convert the remaining ones to a list variable. In ColdFusion, that list would look something like this:
listOfFields = "field2,field3,field8,etc";
Fields 1,4,5,6, and 7 were intentionally excluded. We are then going to loop through the list in our query. In ColdFusion, this would be the syntax
<cfquery>
select somefields
from sometables
where 1 = 2
<cfloop list="#listOfFields#" index = "thisField">
or #thisField# = something
</cfloop>
This meets the laziness criteria because you only have to get the field names once. Whether it's better or worse than getting the columns from the system tables and looping through them depends. Doing it this way will make your own app run faster because you don't have to query the system tables every time. However, if a new column is added to your table, you'll have to modify your source code to include it in your search.
If you do decide to query the system tables, make sure you only select char and varchar fields.
Adapt the sample query given at https://stackoverflow.com/a/1054988/1967396
SELECT *
FROM Northwind.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'Customers'
to get the names of the columns. Then loop over those names to search the table one column at a time for the specific strings. This takes advantage of the efficiency of SQL search and prevents you making a copy of the entire database just to search it (slowly) with nested foreach loops (as in #Silver89's answer).

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.

Categories