Mysql syntax for a search engines with names [duplicate] - php

This question already has answers here:
How to select two columns as one?
(2 answers)
Closed 8 years ago.
I want to make a "search engine" with people in php. I have two columns. The first is with first_name and the secon is with last name i use this sql syntax:
SELECT *
FROM users
WHERE first_name OR last_name LIKE '$search_term%'
I wand the sql to search for first name and for last name the same time with out having one column with first_name and last_name together. Please Help !!!!

it should be
SELECT *
FROM users
WHERE first_name LIKE '$search_term%' AND
last_name LIKE '$search_term%'
But the query above performs full table scan because it doesn't use index. For better performance, search about FULL TEXT SEARCH.
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?

Related

MySQL SELECT * FROM table WHERE name LIKE (?) OR owner LIKE (?); [duplicate]

This question already has answers here:
PHP PDO prepared statement -- MySQL LIKE query
(3 answers)
Closed 6 years ago.
As you can see in the title, I have a table that I want to take use of in a website I have.
This is how the MySQL statement looks like now: SELECT * FROM bth_nav WHERE name LIKE (?) OR owner LIKE (?);
On my website I want to either search for name or owner. Right now I can only search for name but not owner. This is why I'm asking for help, I've tried to rewrite the statement but however I do it i can only search for one of them.
Thanks in advance.
The answer will be a little more complicated then you would expect.
I see question marks in your query, this way I can assume you're using prepared statements (which is good!).
Your old statement was using 1 value (for the name), and now you want to use 2.
You have some options for this to work.
The easiest one would be that you bind the value twice, but that's not the nicest way.
A better way would be to name your parameters, like this:
SELECT * FROM bth_nav WHERE name LIKE (:nameOwner) OR owner LIKE (:nameOwner);
Hence that I use the same name for both parameters here. Now you can bind the value to the named parameter with bindValue, and you need do this only once.

SELECT query with apostrophe [duplicate]

This question already has answers here:
How to insert a value that contains an apostrophe (single quote)?
(13 answers)
Closed 7 years ago.
In my database, I have a column named storeName with a value called Joe's Kitchen.
When user enters Joe's Kitchen, I would store it in a variable named storeName and do a select query on it like this: "SELECT * FROM shops WHERE storename='".$storeName."'". Problem now is that the value contains apostrophe, how should I go about this ?
I have tried the method below but it is not working
$storeName = mysqli_real_escape_string($db->getConnection(),$_POST["storeName"]);
Escape the apostrophe in query by writing two apostrophes
Example
SELECT * FROM shops WHERE storename='Joe''s Kitchen' //added 2 apostrophes
this is not a recommended method since it has serious security issues, try to use pdo or parameterized queries
In your SQL query, you can replace the single quote ' by `. Then the name can contain single quotes...
You can do this way also
SELECT * FROM shops WHERE
storename="Joe\'s Kitchen"

Query works in phpmyadmin but not in PHP [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 8 years ago.
Ok so i have this kind of query
SELECT * FROM table WHERE column LIKE 'Blahblahblah Blah - Blah (Blah-Blah)'
(Yep, column values are 20-30 characters long)
And it works in phpmyadmin and returns ~ 100 results.
But whn i try it in PHP framework CI (CodeIgniter)
It is not returning any values.
My code looks like:
$sql = "SELECT * FROM table WHERE column LIKE '$val' ORDER BY column ASC";
$sql = $this->db->query($sql);
return $sql->result();
So how do i get this to work?
Before you try to make it work, you really, really need to change the way you're constructing the query. You should use a prepared statement where you introduce variables, and then bind them to values.
The way you've written it is horribly vulnerable to SQL injection attacks. (Suppose $val contained '; DROP DATABASE blah; .... What would the whole SQL statement now look like?) If you try to solve the problem in its current form, you'll end up with something that works but will be very dangerous. Make it safe first with a prepared statement.
Details in this linked question.

Getting a Mysql Results without knowing a column name [duplicate]

This question already has answers here:
Get table column names in MySQL?
(19 answers)
Closed 9 years ago.
As I am still learning PHP and MySQL, I would like to know if it is possible to query a table without knowing it's name. Knowing the table I am querying and the column I would like to retrieve, I can write something like
$book_title=$row['book_title'];
Then I can use the resulting variable later in the script. In each case, each book category table will have a column of interest with a different name. I have several tables on which I am running queries. I am able to query any table by using a variable that always evaluates to the correct table name, because all the input from users corresponds to the tables in the database, so the $_POST super global will always carry a correct table name. The problem is for me to have a
$variable=$row['column'];
in cases where I do not know a column name before hand even though I know the table name.
My queries are simple, and look like
query="select * FROM $book_categories WHERE id=$id";
$row = mysqli_fetch_array ($result);
$variable=$row['?'];
The question mark say, I do not know what column to expect, as it's name could be anything from the tables in the database!
Since I have several tables, the query will zero on a table, but the column names in each table varies so I would like to be able to use one query that can give me an entry from such a column.
I hope my question is clear and that I am not asking for the impossible. If it's ambiguous, I care to elucidate (hope so).
I'm not sure what you mean, but it is possible to reference specifc columns by typing index (starting with 0) something like this: $row[0], $row[1] where 0 indicates the first column, and 1 indicates the second column from the returned recordset.
Example:
If you have a select-statement like this:
SELECT title, author FROM books
You could reference these two columns with $row[0], $row[1]
If you try to get the value of $row[2] you will get an unassigned value because there are only two columns (0 and 1) from the recordset.
If you have a select-statement like this:
SELECT * FROM book_categories
and the recordset returns three columns, then you could access these with $row[0], $row[1] and $row[2]. $row[3] does not exist because there are only three columns (0,1 and 2)
Since you are learning maybe we could take some time to explain why this is possible but many people (including myself) would say this is bad -- or at least dangerous
Why you can
Your SQL query is basically a text string you send to the DB server, which decode that string trying to interpret it as SQL in order to execute the query.
Since all you send to the DB server is text string, you could build that string however you want. Such as using string interpolation as you did:
select * FROM $book_categories WHERE id=$id
That way, you could replace any part of your query by the content of a variable. You could even go further:
$query FROM $book_categories WHERE id=$id
Where $query could by SELECT * or DELETE.
And, why not initializing all those variables from a form:
$book_categories = $_POST['book_categories'];
$id = $_POST['id'];
$query = $_POST['query'];
Great, no? Well, no...
Why you shouldn't
The problem here is "could you trust those variables to only contain acceptable values?". That is, what would append if $book_categories somehow resolve to one table you didn't want to (say myTableContainigSecretData)? And what if $id resolve to some specially crafted value like 1; DELETE * FROM myImportantTable;?
In these conditions, your query:
select * FROM $book_categories WHERE id=$id
Will become as received by the DB server:
select * FROM myTableContainigSecretData WHERE id=1; DELETE * FROM myImportantTable;
Probably not what you want.
What I've tried to demonstrate here is called SQL injection. This is a very common bug in web application.
How to prevent that?
The best way to prevent SQL injection is to use prepared statement to replace some placeholders in your query by values properly shielded against SQL injection. There was an example posted a few minutes ago as a response to an other question: https://stackoverflow.com/a/18035404/2363712
The "problem" regarding your initial question is that will replace values not table or columns identifiers.
If you really want to replace table/columns identifiers (or other non-value part of your query) by variables contents, you will have to check yourself the content of each of these variables in order to prevent SQL injection. This is quite feasible. But that's some work...

How to Perform SQL Injection making a SELECT statement UPDATE or INSERT rows? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
MySQL Injection - Use SELECT query to UPDATE/DELETE
So I have found in my site bug that allows to perform sql injection
http://mysite.com/script.php?id=1 union select 1,2,3 will output all fields that has Id property equal to one plus one additional row with 1,2,3. I know that I have to validate user input to close my bug.
However my question is quite another. Is it possible to perform update query or insert query? I am able to comment query using --, however I cannot use multiple statements that are delimited by ;. So is it possible to perform update query in my case. I can show PHP code and SQL query if needed.
$sql = "SELECT id, title, text from table where cId=$val";
$result = mysql_query($sql);
$array = mysql_fetch_array($result);
//echo rows in table
Judging from MySQL Injection - Use SELECT query to UPDATE/DELETE
all that is protecting you is a limitation of mysql_query. I would not rely on this, and in particular not that it remains this way over time. You should never rely on a feature to be disabled by default. Maybe the next version already allows statements such as.
SELECT id, title, text from table where cId=1; DROP table table
Nope it is not possible. Most probably you ar running mysql_query, that would not allow multiple queries to be run in one pass. And hence if your query starts with SELECT (as it does), it would not allow any UPDATE injection
Edit: Use mysql_real_escape_string on your input even then
By default this should not be possible. Although there are options for mysql_query to run multiple statements in one string since MySQL 5.0 which you have to set with mysql_set_server_option.
Please consider changing your statement command like this to use mysql_real_escape_string:
$q = mysql_fetch_array(mysql_query("SELECT id, title, text from table where cId = " . mysql_real_escape_string($val)));
At the very best you change your code to use PDO since all mysql_* functions are officially deprecated.

Categories