I have this quick question, i have got the username variable from a form and i need to insert it in a query, can you please tell me where i'm going wrong, it says: Unknown column '$username' in 'field list'
Here is the code:
echo $HTTP_POST_VARS['username'];
echo $username;
$query = sprintf( 'SELECT $username FROM hostess' );
In the code supplied you never set $username.
You're wide open for Sql injection.
You're using sprintf without any reason - it formats a string but you're not supplying any formatting, my example below does
You're trying to 'SELECT $username FROM hostess' but that's not a valid Sql statement at all.
You'd be wanting something more like:
$query = sprintf( "SELECT * FROM hostess WHERE username='%s'", $username);
AFTER making sure you clean $username.
Uhmm about everything seems wrong..
First of all, you never defined the variable $username.
What you are doing would only be valid in a version of PHP that still supports suberglobals.
Second, why are you using sprintf for a query?
By the way, HTTP_POST_VARS is deprecated. Use POST
Correct code would be something like this;
$username = $_POST['username'];
echo $username;
$query = mysql_query("SELECT ".$username." FROM hostess");
in PHP, using the single quote for strings will not parse the string for variables. Use either concatenation or double quotes:
$query = sprintf( 'SELECT ' . $username . ' FROM hostess' );
$query = sprintf( "SELECT $username FROM hostess");
Of course, this is to say nothing about the terrible risks using a POST var this way implies.
$query = sprintf( 'SELECT %s FROM hostess', $username);
-or, if that's a string value, I suspect you may want to include that in single quotes in the query text -
$query = sprintf( "SELECT '%s' FROM hostess", $username);
NOTE: The generated SQL statement looks a bit odd, in that its going to return the same literal value for every row in the hostess table. If there's a hundred rows in the hostess table, you are going to return 100 rows with the same literal value. This may be what you want, but it strikes me as VERY odd.
NOTE: The sprintf function looks for %s, %d, etc. placeholders in the first argument, and replaces them with values from the remaining arguments.)
NOTE: If $username contains a value coming in from a form, and has not been validated, to thwart SQL injection attacks, I would use the (admittedly old school) mysql_real_escape_string function. (Others will offer suggestions for better, more modern techniques to accomplish the same result.)
$query = sprintf("SELECT '%s' FROM hostess",mysql_real_escape_string($username));
Related
I have made a simple amateur component in Joomla...
In it there is a select>option drop-down list, which add parameters to the URL.
The problem was that it did not worked with 1.1 value and it works with a 1.5 value.
A friend of mine fixed the problem, but I want to know why it happened
Original Query:
$query = "SELECT * FROM `TABLE 2` WHERE Power='".$_GET["Power"]."' AND Poles='".$_GET["Poles"]."'";
The new working query:
$query = "SELECT * FROM `TABLE 2` WHERE Power=".floatval($_GET["Power"])." AND Poles='".$_GET["Poles"]."'";
If you're using Joomla, you should really be sticking to Joomla's coding standards and methods for everything, this includes database queries:
https://docs.joomla.org/Selecting_data_using_JDatabase
You should also be using JInput instead of $_POST or $_GET calls:
http://docs.joomla.org/Retrieving_request_data_using_JInput
Looking at your query, it should looking something like this:
$db = JFactory::getDbo();
$input = JFactory::getApplication()->input;
$power = $input->get('Power', '', 'RAW');
$polls = $input->get('Pols', '', 'RAW');
$query = $db->getQuery(true);
$query->select($db->qn(array('*')))
->from($db->qn('#__table'))
->where($db->qn('Power') . ' = ' . $db->q($power), 'AND')
->where($db->qn('Polls') . ' = ' . $db->q($polls));
$db->setQuery($query);
$results = $db->loadObjectList();
// Do what you want with the $results object
Using this means that column names and data values are escaped properly and you've not left with SQL vulnerabilities as #skidr0w mentioned.
Note: #__ is the database table prefix, assuming you've followed this approach. If not, simply replace #__table with the full name of your table
The table column Power is of type float or double. In your first query you try to insert a string value. The second query inserts the correct float by first casting the request value to float and removing the quotes around the value.
By the way, you sould never ever use unfiltered user-input (such as $_GET values) in a sql query.
Actually, after several days I found that the problem and the solution were simpler.
Just removing the '-sign solved the problem
Power='".$_GET["Power"]."'
with
Power=".$_GET["Power"]."
Regards
I have moved to IIS 8 in PHP 5.4. I am trying to collect data from a table and insert them to a different one, i know my code is correct, but seems to be not working, probably because of the php version, can anyone help me?
here's my code
$query = odbc_exec($conn, "SELECT * FROM member");
while($rows = odbc_fetch_array($query)) {
$querystring = "INSERT INTO oldusers (username, password, regdate) VALUES ('$rows['userid']', '$rows['passwd']', '$rows['registdate']')";
$query2 = odbc_exec($conn, $querystring);
odbc_free_result($query2);
//echo $rows['userid']." ".$rows['passwd']." ".$rows['registdate']."<br>";
}
thanks in advance.
instead trying to insert one by one record, better to insert like below:
INSERT INTO oldusers (username, password, regdate) SELECT userid,passwd,registdate FROM member
for more information :http://dev.mysql.com/doc/refman/5.5/en/insert-select.html
You're placing $rows['passwd'] inside of a double-quoted string. Instead you should do:
$str = "some sql $rows[passwd] rest of sql"; // notice the absence of single quotes
or:
$str = "some sql {$rows['passwd']} rest of sql";
or (I think this way is most readable):
$str = 'some sql' . $rows[passwd] . ' rest of sql';
If your column contains text you'll need to add surrounding single quotes where necessary.
Having said all that, you should instead use parameterized queries (if your database supports it) as it's safer (from SQL injection). If that's unavailable you will at the very least need to escape the data before concatenating it to the string.
I have a little problem to save html-code in phpmyadmin.
Thats the html-code ($html_txt) which I would like to save in the sql-table. I get the code from an other sql-query.
An günstigen Tagen "Paradies" ist es dienlich.
Test/Test<br /><br />"Test"
And that is my query.
$id = 1;
$html = "'".$html_txt"'";
$sql = 'UPDATE table SET text = '.$html_txt.' WHERE id = '.$id.'';
That does not work. Any idea? I tried it also like this:
$id = 1;
$html_txt;
$sql = 'UPDATE table SET text = '.$html_txt.' WHERE id = '.$id.'';
You must escape the string statements before querying. Your query should be like the following:
$con = mysqli_connect("localhost","user","password","db");
$id = mysqli_real_escape_string($con, $id);
$html_txt = mysqli_real_escape_string($con, $html_txt);
$sql = 'UPDATE table SET text = ' . $html_txt . ' WHERE id = ' . $id . '';
I die if I do not say:
Please use parameterized query
Please avoid using vulnerable sql statements.
use mysql_escape_string to support for html entities and may the text be the kwyword so use like this text
$id = 1;
$html =mysql_real_escape_string($html_txt);
$sql = 'UPDATE table SET `text` = '.$html.' WHERE id = '.$id.'';
This should be a comment - but it's a bit verbose.
It should be obvious to most PHP developers that the problem is lack of escaping of the HTML string, however that in itself is not a reason for this being a poor question.
You've not provided details of any attempt to investigate the problem yourself. "Doesn't work" is not a good description of what happenned - in this case the expected outcome is fairly obvious to me, but that's not always the case. I aslo know what the actual outcome would be - but you've not documented that either. In most occassions where code does not behave as expected, an error message will be reported somewhere - you should be looking for it. The DBMS would have returned a specific error message - which your code should poll - especially if you are running into problems.
If you had viewed the SQL you were sending (or included it in your post) this would also have helped diagnosis.
You should properly escape your HTML value. Though this solution is not optimal as it does not use parameterized queries (PDO, ....), try this:
$html = 'An günstigen Tagen "Paradies" ist es dienlich. Test/Test<br /><br />"Test"';
$id = 1;
$sql = 'UPDATE table SET text = '.mysql_real_escape_string($html).' WHERE id = '.$id.'';
i would suggest you use mySQli prepared statement, WHY : i think somewhere along the line your variable have funny characters that r messing up with your query..with prepared statements the query is send alone then after your variables are binded to it, pls check above code
$conn = new mysqli("localhost", "your username", "your pass", "your db");
$myString = "Your string here";
$id = 1;
$insertDB = $conn->prepare("UPDATE table SET text = ? WHERE id = ?");
$insertDB->bind_param('si', $myString, $id); //bind data, type string and int 'si'
$insertDB->execute(); //execute your query
$conn->close(); //close connection
I have been using the block of code below to supposedly stop sql injections. It is something someone showed me when I first started php(which was not that long ago)
I place it in every page just as shown on the open. I am wondering if it is effective? I do not know how to test for sql injections
<?php
//Start the session
session_start();
//=======================open connection
include ('lib/dbconfig.php');
//===============This stops SQL Injection in POST vars
foreach ($_POST as $key => $value) {
$_POST[$key] = mysql_real_escape_string($value);
}
foreach ($_GET as $key => $value) {
$_GET[$key] = mysql_real_escape_string($value);
}
My typical insert and update queries look like this
$insert = ("'$email','$pw','$company', '$co_description', '$categroy', '$url', '$street', '$suite', '$city', '$state', '$zip', '$phone', '$date', '$actkey'");
mysql_query("INSERT INTO provider (email, pw, company, co_description, category, url, street, suite, city, state, zip, phone, regdate, actkey) VALUES ($insert)") or die ('error ' . mysql_error());
mysql_query("UPDATE coupon SET head='$_POST[head]', fineprint='$_POST[fineprint]', exdate='$exdate', creationdate=NOW() WHERE id='$cid'") or die ('error ' . mysql_error());
That's somewhat effective, but it's suboptimal -- not all of the data you receive in _GET and _POST will go into the database. Sometimes you might want to display it on the page instead, in which case mysql_real_escape_string can only hurt (instead, you'd want htmlentities).
My rule of thumb is to only escape something immediately before putting it into the context in which it needs to be escaped.
In this context, you'd be better of just using parameterized queries -- then escaping is done for you automatically.
This is not enough.
1. You're missing cookies, $_COOKIE variable.
2. If you use $_REQUEST you're in trouble.
3. You didn't show your queries, you must enquote each variable with single quotes '' when you put it into query (especiall when the data is supposted to be an integer and you might think that quote is not necessary in that case, but that would be a big mistake).
4. Data used in your query could come from other source.
The best way is to use data binding and have the data escaped automatically by the driver, this is available in PDO extension.
Example code:
$PDO = new PDO('mysql:dbname=testdb;host=127.0.0.1' $user, $password);
$stmt = $PDO->prepare("SELECT * FROM test WHERE id=? AND cat=?");
$stmt->execute(array($_GET["id"], $_GET["cat"]));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
You can also bind data using string keys:
$stmt = $PDO->prepare("SELECT * FROM test WHERE id = :id AND cat = :cat");
$stmt->execute(array(":id" => $_GET["id"], ":cat" => $_GET["cat"]));
If you want to learn PDO, you might find useful these helper functions I use:
http://www.gosu.pl/var/PDO.txt
PDO_Connect(dsn, user, passwd) - connects and sets error handling.
PDO_Execute(query [, params]) - only execute query, do not fetch any data.
PDO_InsertId() - last insert id.
PDO_FetchOne(query [, params]) - fetch 1 value, $count = PDO_FetchOne("SELECT COUNT(*) ..");
PDO_FetchRow(query [, params]) - fetch 1 row.
PDO_FetchAll(query [, params]) - fetch all rows.
PDO_FetchAssoc(query [, params]) - returns an associative array, when you need 1 or 2 cols
1) $names = PDO_FetchAssoc("SELECT name FROM table");
the returned array is: array(name, name, ...)
2) $assoc = PDO_FetchAssoc("SELECT id, name FROM table")
the returned array is: array(id=> name, id=>name, ...)
3) $assoc = PDO_FetchAssoc("SELECT id, name, other FROM table");
the returned array is: array(id=> array(id=>'',name=>'',other=>''), id=>array(..), ..)
Each of functions that fetch data accept as 2nd argument parameters array (which is optional), used for automatic data binding against sql injections. Use of it has been presented earlier in this post.
Kind of.
The mysql_real_escape_string function takes the given variable and escapes it for SQL queries. So you can safely append the string into a query like
$safe = mysql_real_escape_string($unsafe_string);
$query = 'SELECT * FROM MyTable WHERE Name LIKE "' . $safe . '" LIMIT 1';
It does NOT protect you against someone putting malicious code into that query to be displayed later (i.e. XSS or similar attack). So if someone sets a variable to be
// $unsafe_string = '<script src="http://dangerous.org/script.js"></script>'
$safe = mysql_real_escape_string($unsafe_string);
$query = 'UPDATE MyTable SET Name = "' . $safe . '"';
That query will execute as you expect, but now on any page where you print this guy's name, his script will execute.
This is completely WRONG approach.
In fact, you are mimicking infamous magic quotes, which is acknowledged as a bad practice. With all it's faults and dangers.
To help you understand why your initial way was wrong Magic quotes in PHP
To help you understand why escaping has nothing to do with "data safety" yet not sufficient to protect your query: Replacing mysql_* functions with PDO and prepared statements
To help you understand when prepared statements not sufficient either and what to do in these cases: In PHP when submitting strings to the database should I take care of illegal characters using htmlspecialchars() or use a regular expression?
this is not to prevent SQL Injection the real escape method only add \ to the dangerous
characters like " or ' so a string with "hi"do'like" will become "hi\"do\'like\" so it is
less dangerous
this method is not always usefull ; in case you want to display the content of tha escaped
variable in a page it will only destroy it and make it less readable
I'm trying to retrieve all the data id from a database where their tags(array) is like a given value.
This is what I have done so far...
$new_string = 'nice phone';
$construct = mysql_query("SELECT tag_array, name, id FROM details
WHERE tag_array LIKE $new_string%")
or die("<p>died 20: $construct<br>" . mysql_error());
while($getThis = mysql_fetch_array($construct)){
echo $getThis['id'].'<br />';
echo stripslashes($getThis['name']).'<br />';
}
It doesn't work ATALL.
Could you please point me to the right direction?
I'm really struggling!!
You should put $new_string in quotes.
NOTE It is very bad practice and you should always escape all variables you are passing to SQL. You should really read up on SQL injection and other security issues.
Also if you want to match $new_string anywhere in tag_array (which you most likely want), you need to add dollar sign in front of it too. You can read up more at MySQL reference manual.
So in the end:
"SELECT tag_array, name, id FROM details WHERE tag_array LIKE '%" . mysql_real_escape_string($new_string) . "%'"
You should sanitise the data before putting it in the query like:
$new_string = "blah...; DROP TABLE tag_array; #";
$sql = mysql_real_escape_string($new_string);
$sql = "SELECT tag_array, name, id FROM details WHERE tag_array LIKE %'$sql'%"
This is not enough though it just helps preventing sql inject, consider using regular expressions to clean the data. If you don't yet know about regexp check out this site: regexp info. It helped me mutch.