php files on the fly - php

In PHP, If i have this assign:
$link = 'Home';
And in another php section i need to grab the value of $link and insert it in a MYSQL query in plain text, like this:
$sql = "SELECT txt FROM Home WHERE id = 1";
Note that $link has been written in the format of it's value in the query.
Basically i need to see the inside of the $link var and write it down on the query.
Why i need this -> because i'm creating php files on the fly after the click of a submit button.
And inside of the newly created file is a tinymce text editor that needs to read it's text contents from a table that was also created on the fly along with this file.

What you want to do is this:
$sql = "SELECT txt FROM $link WHERE id = 1";
^ ^ ^
The double-quotes (") specify that the string has to be interpreted (with single quotes this won't work). Inside the string you can then write the name of the variable ($link) and it will be "supplanted" by its value.
I would'nt recommend doing this because it is vulnerable to SQL-injection and it is a very very bad practice that show that you do things in an uncommon way. Better avoid it!
EDIT: even worse...
When you say in a comment creates a mysql table with the name of the file that's an even worse thing to do. First, not all characters in a filename should go into a table name. Second, you can get litearlly anything as a filename, even things that are not actual filenames.
It is possible to forge a HTTP request so that the filename is an arbitrary string of your liking, for example:
a (); SELECT * FROM accounts; --
When you put this string into your query:
CREATE TABLE $filename (id int PRIMARY KEY, whatever varchar(20) NOT NULL);
You get this resulting SQL query:
CREATE TABLE a (); SELECT * FROM accounts; -- (id int PRIMARY KEY, whatever varchar(20) NOT NULL);
As you can see, this will create a table a without any columns and then select all usernames and passwords, if the table accounts exists. The rest of the query is commented out with --.
This is a very simple SQL injection attack and you don't want to do this! Don't put userinput straight up into your SQL queries!!
EDIT: taking the value from $_POST
If your field has the name link then you can access it with
$_POST['link']
You can put this into your string this way:
$sql = "SELECT txt FROM {$_POST['link']} WHERE id = 1";

Do you want something like this:
$sql = "SELECT txt FROM ".$link." WHERE id = 1";

Related

Performing MySQLi searches that contain URL encoded strings

I am having trouble retrieving data from a database, when the field contains a URL encoded string.
What I mean is, my MySQLi database contains a field called "artist_name", where some of the values contain URL encoded strings, such as:
"Sonny+O'Brien"
"Lil'+Joe"
"Batman+&+Robin"
etc.
When I search on these fields in PhpMyAdmin, it finds them straight away, using a select statement:
SELECT * FROM `artists` WHERE `artist_name` LIKE 'Sonny+O'Brien';
However, when I try the same thing programmatically, from within my PHP script, it returns no results:
$artist_name = "Sonny+O'Brien";
$sql = "SELECT * FROM artists WHERE artist_name LIKE '".$artist_name."'";
if ( $result = $mysqli->query( $sql ) ) {
$obj = $result->fetch_object();
}
No results.
I have tried using an addslashes() on the artist's name, and I have double-checked all the value's and I am providing them exactly as they appear in the database.
Any ideas why the URL escaped strings are not recognised in my SELECT queries?
edit:
(screenshot from PhpMyAdmin, showing that my data is stored as described, and that my SELECT query works from within PhpMyAdmin, just not from my PHP script).

Use pg_query_params array placeholders for searching multiple columns

I pass two different values into the file, one which the user entered and the other which is selected from a predefined set of values in a drop down menu, which is the one i'm having trouble with.
When using a single placeholder for the query it works,for example:
$result = pg_query_params($con, "SELECT * FROM chemsub WHERE name like $1", array("%".$_REQUEST['term']."%"));
I want to alter the query so the user can change which column they are searching i can't seem to get it to work, here is what i have
$result = pg_query_params($con, "SELECT * FROM chemsub WHERE $1 like $2", array($_REQUEST['dropdown'],"%".$_REQUEST['term']."%"));
I know the correct value is being passed into the file with the correct spelling matching a column name in the database but for some reason it returns no rows.
Any help would be much appreciated.
You can't have params in place of identifiers. If you want to have a dynamic column being queried again you can either prepare the query text in php or have the sql look like ($1 = 'foo' AND foo LIKE $2) OR ($1 = 'bar' ANd bar LIKE $2.`

Query with quotes not working

I am sending a Query string like:-
String query = "select * from table where id = 12345 or id like '___1435'";
in php code:-
$phone = $_REQUEST['data1'];
$result = mysql_query($phone);
return $result;
through android but it is not working.
But a query like:-
String query = "select * from table where id = 12345 or id = 21435";
is working.
I also tried:-
$phone = mysql_real_escape_string($_REQUEST['data1']);
$result = mysql_query($phone);
return $result;
What could be the problem.
Most probably it is related to the quotes I am using in String.
How can I overcome this ?
Thank You!
A LIKE query needs percentage signs to signify a wild card, which I assume you are trying:
id like '%___1435%'
If you don't want this wildcard behaviour then you could just remove the like
id = '___1435'
I think the problem is that you're attempting to perform a string comparison on an integer field. Try casting your ID field as a CHAR first, like this:
select * from table where id = 12345 or CAST(id as CHAR) like '___1435'
Edit: It's going to be a guessing game unless you can a) post some error logs or b) post your MySQL query log (to see the actual query executing), which you can enable by turning on the General Query Log for your installation. Since it looks like you're accepting your query string via POST, if the string has been encoded in any way (ie url encoding), it'll affect your query if not properly decoded first.
A better and more secure approach would be to create a specific web service that accepts the ID to query, which you can pass into a prepared statement server side. It's better practice anyway so your system isn't vulnerable to wide open queries from a client.

MySQL error: Incorrect Table Name

I'm pretty new to web development so there's a good chance I'm doing something pretty dumb here.
I'm using AJAX to send data to a PHP file which will use the data to run SQL commands to update a table. I'm dealing with editing articles, so my PHP file needs to know three things: The original name of the article (for reference), the new name and the new content. I also tell it what page the user is looking at so it knows which table to edit.
$('#save_articles').click(function () {
var current_page = $('#current_location').html();
var array_details = {};
array_details['__current_page__'] = current_page;
$('#article_items .article_title').each(function(){
var article_name = $(this).html(); //The text in this div is the element name
var new_article_name = $(this).next('.article_content');
new_article_name = $(new_article_name).children('.article_content_title').html();
var new_article_content = $(this).next('.article_content');
new_article_content = $(new_article_content).children('.article_content_content').html();
array_new_deets = {new_name:new_article_name, content:new_article_content};
array_details[article_name] = array_new_deets;
});
send_ajax("includes/admin/admin_save_articles.php", array_details);
});
In the PHP file, I first retrieve the current page and store it in $sql_table and then remove the current page variable from $_POST. Then I run this.
foreach($_POST as $key => $value){
$original_name = $key;
$new_name = $value['new_name'];
$new_cont = $value['content'];
$query = "UPDATE
`$sql_table`
SET
`element_name`= '$new_name',
`element_content` = '$new_cont',
WHERE
`element_name` = '$original_name'";
$query = mysql_query($query);
if(!$query){
die(mysql_error());
}
}
I always receive an error saying that 'sitep_Home' is an incorrect table name. Not only is it a real table in my db, but I've actually changed its name to make sure it isn't an issue with keywords or something.
If I instead run the query without the variable $sql_table (specifying that the table is called 'sitep_Home'), the query accepts the table. It then doesn't actually update the table, and I suspect it's because of the WHERE argument that also uses a variable.
Can anyone see what I'm doing wrong here?
try to use $sql_table as '$sql_table' if you are sure that this contain a right table name.
Like you are using other column's value
Check if this can help!!
Dump/log your query before executing it - the problem should be quite visible after that (I suspect some additional characters in the table name).
Couple of things:
you should never trust your users and accept everything they'll send you in $_POST, use whitelist for the fields you'd like to update instead
your code is vulnerable to SQL injection, I recommend to use some framework / standalone library or PDO at least, avoid mysql_query which will be deprecated in the future. Check this to get some explanation http://www.phptherightway.com/#databases
Table names are case sensitive in MySQL. Please check if there is mistake in the case.
You have to surround name of mysql table in query in this `` qoutes. When you dinamically create mysql table it is very important to trim($variable of mysql name table) before create, because if "$variable of mysql name table" have space in the edns or in the start mysql not create table. And the last when you call dinamically $variable of mysql name table in query you have to trim($variable of mysql name table) again.

php generate a string and check from mysql with not exist

I want to generate a string to post a url. Then make the post url like: http://www.mydomain.com/post/afCeYk, and store this url in the mysql. In order to avoid a repeat url , I think first should check the mysql whether the url has already existed. In my code, I just check once, I can not ensure the second generate string hasn't already existed. So how do I make a loop?
$shufstr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$rdstr = substr(str_shuffle($shufstr),0,6);
$query = mysql_query("select * from table where post_url = '".$rdstr."'");
if(mysql_num_rows($query)>0){
//insert the url rules into db
}else{
//generate a new string and check the db again
}
You should query the database once to collect all of the data from the table, then generate a string and check it against the array you get.
As opposed to querying the database over and over, this has a performance benefit.
(not actual code)
$url_list = query("SELECT `post_url` FROM `table`");
do {
$random_string = generate_random_string();
}
while(!in_array($random_string, $url_list));
In addition, make sure no duplicate is entered by making the column UNIQUE.
You can use a while loop, but it would get pretty slow after you have a few thousand URLs saved:
$shufstr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$validString=false;
while(!$validString){
$rdstr = substr(str_shuffle($shufstr),0,6);
$query = mysql_query("select * from table where post_url = '".$rdstr."'");
if(mysql_num_rows($query)==0){ //This is also different from your code as you don't want to do the insert if there is 1+ row with that url.
$validString=true;
//insert the url rules into db
}
}
If it were my project, I would add a UNIQUE constraint on the post_url column itself, this will ensure that no duplicates will be entered from any point of entry (app, command line, etc). More info on MySQL unique.

Categories