how to create a dynamic query using 'IN' in mysql - php

I want to pass a string that contains many usernames, seperated by a comma,and want to pass it to query
$name_list='kesong,nicholas,jane'; //this value would change
$select_occupy=mysql_query("SELECT * FROM user_data WHERE `username` IN('$name_list') ORDER BY `occupy_date` ");// i think this would just search for a username which is 'kesong,nicholas,jane', instead searching them seperately
echo mysql_num_rows($select_occupy); //would echo 0
I know it works only when you specify like IN('$name1','$name2','$name3'), but I need a dynamic one

As a suggestion, just hold your names into an array and do like below:
$names=array('name1','name2','name3');
$namesToCheck="";
foreach($names as $name){
$namesToCheck.="'$name',";
}
//to remove the last ,
$namesToCheck=substr($namesToCheck,0,-1);
Now, you can put $namesToCheck into your IN query.
EDIT:
In this answer, this is assumed that you will prevent any possible SQL injections as current answer is just an idea about your question. The minimum suggestion to perform preventing SQL injections would be using mysql_real_escape_string function, which escapes special characters in a string for use in an SQL statement. For example:
$namesToCheck.="'".mysql_real_escape_string($name)."',";
//OR DO THIS ON FINAL STRING
NOTE THAT This extension is deprecated as of PHP 5.5.0. You can take a look at the PHP's official document in the following link:
mysql_real_escape_string

You can do it like this :
$namesToCheck = "'" .implode( "','" ,explode( ',' ,$name_list ) ) ."'";
And then use the $namesToCheck in the IN clause of your query .
The above code would convert :
kesong,nicholas,jane
to :
'kesong','nicholas','jane'

Related

PHP mysqli_real_escape_string converts empty string to single space

My application is working fine. DB connection has been opened before call SQL commands in PHP.
The problem is that some parameters in an input form is blank, and after using real_escape_string the parameters have an empty string stored in database. The database columns are set to default to NULL.
Is this expected? I can't find anything relevant in PHP documentation.
Is it possible to simply make it store NULL?
Code is as below:
"INSERT INTO address SET firstname = '" . $mysqli->real_escape_string($data['firstname']) . "'";
It’s expected if you tell the server to use the empty string, which you are doing. You need to add some logic to your code to use null when a string is blank.
Also, you are wide open to SQL injection. You need to use prepared statements, rather than concatenating variables into your query. Escaping strings is not enough. See How can I prevent SQL injection in PHP?.
You probably should separate the data verification from the query creation. This can be done as follows:
$firstName = strlen($data['firstname'])? "'".$mysqli->real_escape_string($data['firstname'])."'": "NULL";
$sql = "INSERT INTO address SET firstname = " . $firstName;
This will check that $data['firstname'] has a value in it and if not, Null is used. This then is combined into your query that you then will run in some subsequent step.
This is by no means the only (or even the best) approach, but based on the code that you have provided, this should give you a start.

Not able to insert string which contains '

I wrote a script to insert record in my DB. The only issue I am getting is when I try to store data which contains ' character then the script does not work and it does not store anything in the DB. For example John's Birthday , Amy's Home etc . Any solution to this problem which allows special character like ' to store in the DB and retrieving them without any harm to security?
mysqli_query($con,"INSERT INTO Story (desc)
VALUES ('$mytext')");
PHP's mysqli_real_escape_string is made specifically for this purpose. You problem is that quotes are being interpreted by MySQL as part of the query instead of values. You need to escape characters like this so they won't affect your query - this is what SQL injection is.
$mytext = mysqli_real_escape_string($con, $mytext);
// continue with your query
Manual: http://php.net/manual/en/mysqli.real-escape-string.php
Filter the variable part of the query through mysqli_real_escape_string.

How to include php echo within mysql update?

So I am updating my mysql database using php. Below is the end of the UPDATE, and if I have a string instead of echo $row[embedcode]"); it works fine, and this echo sets data on the page just fine retrieving the right value, but within this UPDATE it doesn't work.
...WHERE `embedcode` = echo $row[embedcode]");
I have tried using ". ." around it and adding its own php tag around it but I'm not sure what needs to be done.
Just use this:
...WHERE `embedcode` = " . $row[embedcode]);
There is no need for echo.
As a side note, you should probably parameterize or at least sanitize any strings that go into a MySQL query to prevent SQL injection and other bad things.
" ... WHERE `embedcode=` '" .$row[embedcode]. "';");
WHEREembedcode= . $row[embedcode]); will set the value.
There is not need for echo inside the sql statement. echo is used for displaying something from php to the webbrowser.
You don't use echo, perhaps it should be:
...WHERE `embedcode=` . $row[embedcode]");
Not that if $row[embedcode] is a string you have to put quotes around it.
Let say for example...
("UPDATE `tblProfile` SET `profilename` = 'abc' WHERE `embedcode` = '".$row['embedcode']."'");
to prevent SQL injection, you can pass that value as a parameter if you are using PDO or MySQLi.
For example,
$stmt = $dbConnection->prepare('...WHERE `embedcode` = :embedcode');
$stmt->execute(array(':embedcode' => $row[embedcode]));
See this for details.

Sanitize search query with php

When a user searches on my site, I grab the get request and do a mysql query against it. My original code looked something like this: $q = $_GET['q'];.
Right now urldecode is adding slashes for me, but I decided to aslo try filter_var with the santize string filter.
Here is my sql when I use $q = urldecode($_GET['q']);:
SELECT * FROM item WHERE title LIKE '%you\'re%' OR description LIKE '%you\'re%' ORDER BY date DESC
and here is my sql when I use: q = filter_var(urldecode($_GET['q']), FILTER_SANITIZE_STRING);
SELECT * FROM item WHERE title LIKE '%you\'re%' OR description LIKE '%you\'re%' ORDER BY date DESC
The sql is exactly the same, but I get different results and I'm not sure why? Just using urldecode returns the correct results from the database, but filter_var returns nothing (even though the sql is the same).
I guess my question is, is what's the best way to sanitize and search query string?
Urldecode is the wrong function to use - PHP will automatically decode any variables in $_GET so you don't need to, and the PHP Manual says doing so is dangerous.
Often people talk about sanitizing input, but I prefer to think about sanitizing output.
For example, sanitizing input would be:
$q = urldecode($_GET['q']);
$sql = "SELECT * FROM item WHERE title LIKE '%{$q}%'"
// later
echo "These items match '$q'";
And sanitizing output:
$sql = "SELECT * FROM item WHERE title LIKE '%".mysql_real_escape_string($_GET['q'])."%'"
// later
echo "These items match '".htmlspecialchars($_GET['q']).'";
Notice how in the latter example I've used different functions - one for converting the data into a mysql safe format, the other for converting the data into an HTML safe format. You can't know which function you want to run until you know what you're doing with the data.
Others have mentioned parameterised queries. Yes, these are about as secure as you can get and avoid accidental errors, but are not easy to switch to overnight.
Don't try to sanitize your data.
Use parametrized queries.
See http://bobby-tables.com/php.html for examples.
I would do:
$q = mysql_real_escape_string( stripslashes( $_GET['q'] ) );
The best variant is to use php Sanitize filters http://php.net/manual/en/filter.filters.sanitize.php,

How should I write PHP $_POST vars in a mysql_query function?

In accessing my database, I have the user fill out a form, and in the target page, the posted values are used in the resulting MySQL query.
$query = mysql_query("SELECT pass FROM database WHERE user='$_POST[user]'");
However, for some reason or another, MySQL doesn't like my using a $_POST variable in the command, and it only works if I define (for example) $user = $_POST['user'];, and then put $user directly in the SQL command.
On the other hand, I can use $_POST values in INSERT statements where specific column names are not required:
$query = mysql_query("INSERT INTO database VALUES ('foo', 'bar', '$_POST[user]'");
If I try an INSERT statement where attributes are defined (e.g. user='foo'), then the same problem appears.
What am I doing wrong in my SQL query that causes the command to error out when run, but works with the specific method of formatting an INSERT command?
Hopefully, it's not "tough luck, looks like you have to assign all of your posted values". Heh.
First of, watch out for SQL Injections!
Now, to answer your question try doing this instead:
$query = mysql_query("SELECT `pass` FROM `database` WHERE `user` LIKE '" . mysql_escape_string($_POST['user']) . "';");
You were doing a couple of things wrong:
using the = operator instead of LIKE operator
not enclosing the value in the SQL query with '
not enclosing the user index in the $_POST array with '
PS: You should use mysql_real_escape_string() instead of mysql_escape_string()!
You're simply inserting a variable into a string, so it shouldn't matter which command you're putting it into.
There are a few issues to point out.
One, you might want to use the {} format for array variables. You don't use quotes around the arrray key names in this format.
$query = mysql_query("SELECT pass FROM database WHERE user='{$_POST[user]}'")
Two, you'd never want to make a query like that because you are open to sql injection holes. Consider, what if $_POST['user'] was "cow';drop table database;--"?
You must either run mysql_real_escape_string on the POST input before putting it into your query, or check out using PHP PDO with prepared statements.
One way to do format your string which provides a bit of structure is to use sprintf.
$query=mysql_query(sprintf("SELECT pass FROM database WHERE user='%s'",mysql_real_escape_string($_POST['user'])));
Use PDO - it provides much better API to communicate with DB.
If you're using mysql_*() functions always remember to filter (mysql_real_escape_string()) any data that comes from untrusted source (like user)
Pay more attention to how your code looks like. Just compare the following listings:
$query = mysql_query("INSERT INTO database VALUES ('foo', 'bar', " . mysql_real_escape_string($_POST['user']) . ", " . mysql_real_escape_string($_POST['user']) . ", " . mysql_real_escape_string($_POST['user']) . ", " . mysql_real_escape_string($_POST['user']) . ")");
$query = sprinf('INSERT INTO database VALUES ("foo", "bar", "%s", "%s", "%s")',
mysql_real_escape(...), ...);
Do I have to explain which one is better to read, modify or understand?
Why not check and see what mysql_error() has to say about it? If your query is invalid, mysql_error() will return a nice blob of text telling you exactly what went wrong.
As for MySQL not liking the POST var if you insert it directly for some runs, but not others, then you should make sure you're using consistent data and setups for each test. If some test are done using a GET, then your POST vars will be empty. If you're using different user names for each test, then see if what's consistent between the ones that fail.
And as mentioned above, read up about SQL injection and how your query is just begging to be subverted by a malicious user.
Try
$query = mysql_query("SELECT pass FROM database WHERE user=" . mysql_real_escape_string($_POST['user']));
and
$query = mysql_query("INSERT INTO database VALUES ('foo', 'bar', " . mysql_real_escape_string($_POST['user']) . ")");
Its always a good idea to sanitize anything received through $_GET or $_POST

Categories