I have a database where I store data of users and devices. Every user has a list of devices. When the user logs into his account the php code below generates a list of the users devices:  $query_user="SELECT * FROM devices WHERE users_id = '".$user_id."'";  $result = mysqli_query($db, $query_user);  // generating device list and ON and OFF device links while($row = $result-&gt;fetch_assoc())  {     echo "&lt;br&gt;&lt;p&gt;". $row["device"] ."&lt;/p&gt;&lt;a href=on.php?data=" . $row["device"] . "&gt;ON&lt;/a&gt;&lt;br&gt;&lt;a href=off.php?data=" . $row["device"] . "&gt;OFF&lt;/a&gt;&lt;br&gt;"; }   The code also generates a ON and OFF link so the user can manipulate his devices. When the user click for example ON then the following URL is passed to the browser:  https://.../on.php?data=device23   The part of the on.php code that handles the URL data:  if(isset($_GET["data"])) {     $device_name = $_GET["data"]; }  $query_user="UPDATE devices SET status='ON' WHERE device = '".$device_name."'";  mysqli_query($db, $query_user);   So my problem here is that this approach is vulnerable to SQL injection, for example someone can type:  https://.../on.php?data=device17   in the browser and turn the device17 on.  My question is how the generate ON and OFF links for a list of devices and pass the data safe to the on.php and off.php files.  EDIT:  My main problem here is how to generate ON and OFF links for every users device (every user has a different number of devices). When the user clicks the ON link of for example device23 (or any other device, initially I don't know the device name, I am getting the device names from the first db query) I have to pass the device name to the on.php file so it can preform the SQL query that updates the device status.
73
If user input is inserted without modification into an SQL query, then the application becomes vulnerable to , like in the following example:  $unsafe_variable = $_POST['user_input'];   mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')");   That's because the user can input something like value'); DROP TABLE table;--, and the query becomes:  INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')   What can be done to prevent this from happening?
110550
For a new project that I'm doing in PHP I've created an SQLMethods class to connect to the database and perform queries. Tonight was the first night that I actually got to test it (I wrote it a week or so ago and forgot about it) and an unexpected error occured: When it was calling my ExecuteQuery() function, it wouldn't use the database I selected in the constructor.  The constructor:      public function SQLMethods() {         $SQLConnection = mysql_connect($SQLDBAddress, $SQLUserName, $SQLPassword);          if (!$SQLConnection) {             die('Could not connect: ' . mysql_error());         }          mysql_select_db($SQLDB, $SQLConnection);     }   The function in question:      public function ExecuteQuery($Query) {         mysql_query($Query, $SQLConnection) or die('Could not perform query: ' . mysql_error());     }   Does anyone see what the issue might be? Does the connection close after the constructor completes?
74983
I'm writing a php app to access a MySQL database, and on a tutorial, it says something of the form  mysql_connect($host, $user, $pass) or die("could not connect");   How does PHP know that the function failed so that it runs the die part? I guess I'm asking how the "or" part of it works. I don't think I've seen it before.
7387
Can someone explain SQL injection?  How does it cause vulnerabilities?  Where exactly is the point where SQL is injected?
119920
I'm working on an application for work that is going to query our employee database. The end users want the ability to search based on the standard name/department criteria, but they also want the flexibility to query for all people with the first name of "James" that works in the Health Department. The one thing I want to avoid is to simply have the stored procedure take a list of parameters and generate a SQL statement to execute, since that would open doors to SQL injection at an internal level.  Can this be done?
121031
I have a the following code:  // Create an Entity with wrapper   $node = entity_create('node', array('type' =&gt; 'person'));   $entity = entity_metadata_wrapper('node',  $node);    // Add a node title   $entity-&gt;title = $person['name'];    // Add the address information   $entity-&gt;field_person_address-&gt;thoroughfare = $person['address'];   $entity-&gt;field_person_address-&gt;locality = $person['city'];   $entity-&gt;field_person_address-&gt;administrative_area = $person['state'];   $entity-&gt;field_person_address-&gt;postal_code = $person['postalcode'];   $entity-&gt;field_person_address-&gt;country = $person['country'];    // Save the entity   $entity-&gt;save();   The data is saved in the DB perfeclty, but I need to get the entity ID of the new save node.   How do I do that?
65216
I am dissecting some code and came across this,   $sql = 'SELECT page.*, author.name AS author, updator.name AS updator '      . 'FROM '.TABLE_PREFIX.'page AS page '      . 'LEFT JOIN '.TABLE_PREFIX.'user AS author ON author.id = page.created_by_id '      . 'LEFT JOIN '.TABLE_PREFIX.'user AS updator ON updator.id = page.updated_by_id '      . 'WHERE slug = ? AND parent_id = ? AND (status_id='.Page::STATUS_REVIEWED.' OR status_id='.Page::STATUS_PUBLISHED.' OR status_id='.Page::STATUS_HIDDEN.')';   I am wondering what the "?" does in the WHERE statement.  Is it some sort of parameter holder?
10527
In PHP you can just use $_POST for POST and $_GET for GET (Query string) variables. What's the equivalent in Python?
20284
I'm supposed to test a web application for SQL injections. I'm new to this type of security testing and I'd like to get some tips on the matter. Are there any best practices or do I simply search on the Internet for the most common SQL injections and try them out on my application?  I hope some guidance would be profitable for other newbies like me, so please, help me complete the following lists:   List of "places" in the application to be tested:   username  password(s)  e-mail search field  text fields any other fields that are available to the user  List of tests to be performed:   ...?    Thanks!
24749
At the moment, I apply a 'throw everything at the wall and see what sticks' method of stopping the aforementioned issues. Below is the function I have cobbled together:  function madSafety($string) {  $string = mysql_real_escape_string($string); $string = stripslashes($string); $string = strip_tags($string); return $string;  }   However, I am convinced that there is a better way to do this. I am using FILTER_ SANITIZE_STRING and this doesn't appear to to totally secure.   I guess I am asking, which methods do you guys employ and how successful are they? Thanks
6735
I've got a working PHP script that gets Longitude and Latitude values and then inputs them into a MySQL query. I'd like to make it solely MySQL. Here's my current PHP Code:  if ($distance != "Any" &amp;&amp; $customer_zip != "") { //get the great circle distance      //get the origin zip code info     $zip_sql = "SELECT * FROM zip_code WHERE zip_code = '$customer_zip'";     $result = mysql_query($zip_sql);     $row = mysql_fetch_array($result);     $origin_lat = $row['lat'];     $origin_lon = $row['lon'];      //get the range     $lat_range = $distance/69.172;     $lon_range = abs($distance/(cos($details[0]) * 69.172));     $min_lat = number_format($origin_lat - $lat_range, "4", ".", "");     $max_lat = number_format($origin_lat + $lat_range, "4", ".", "");     $min_lon = number_format($origin_lon - $lon_range, "4", ".", "");     $max_lon = number_format($origin_lon + $lon_range, "4", ".", "");     $sql .= "lat BETWEEN '$min_lat' AND '$max_lat' AND lon BETWEEN '$min_lon' AND '$max_lon' AND ";     }   Does anyone know how to make this entirely MySQL? I've browsed the Internet a bit but most of the literature on it is pretty confusing.
122983
I use PHP 5.4.3 and I want to connect to a MySQL database (DB for brevity) remotely (the PHP script resides on a different server than the DB) with normal object-oriented programming (OOP) way:  $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);   and I get the error:      Warning: mysqli::mysqli(): The server requested authentication method unknown to the client [mysql_old_password]   Connect Error (2054) The server requested authentication method unknown to the client   I found  and  but they don't seem to help. I used PHP 5.2.9 and everything worked OK, but downgrading the PHP version is not a solution for me.   I also have to mention that I don't have full access to DB's settings cause the client doesn't give me that kind of access. I told him to ask Hostgator for a newer password format support, but they answered that they cannot do anything which was not what I was expecting. I did a new effort from another remote server and I get now this:     Connect Error (1045) Access denied for user 'user'@'host' (using password: YES)   by using PHP 5.3.9. It looks like the DB doesn't "let me in" because of the remote server's PHP script, but with Oracle's Workbench everything works fine.  Thanks for your time.
58526
As mentioned in , it's possible to use bind variables in dynamic SOQL queries.  This seems like a great way to avoid SOQL-injection, and to build a query string once but use it multiple times with different values in the variables.  I'm working on a method that returns a list of objects.  It accepts a class with multiple properties as its only parameter.  The properties of this class are used to filter the results to just the required records.  It will eventually be driven by a Visualforce component, which will be configured by querystring parameters in the URL.  I just ran into an issue where the query fails when I use dotted bind variables.  If I copy the constructed dynamic SOQL into a static query, it works fine.  This may be a bug, because in doing tests I found that :foo.bar would actually try to use local variable bar.  Here's one of my queries, which uses related custom objects.  I've stripped it down to just the part that's failing (wrapped for legibility):  result = Database.query('SELECT Name, Another_Object__r.Name,      Another_Object__r.Custom_Field__c      FROM Custom_Object__c       WHERE Another_Object__r.Custom_Field__c = :filter.deviceType');   The error reported is System.QueryException: Variable does not exist: filter.deviceType.  As mentioned above, the query works fine as static SOQL, just not dynamic:  result = [SELECT Name, Another_Object__r.Name, Another_Object__r.Custom_Field__c FROM Custom_Object__c WHERE Another_Object__r.Custom_Field__c = :filter.deviceType];   It also works in this case:  String deviceType = filter.deviceType; Database.query('SELECT Name, Another_Object__r.Name, Another_Object__r.Custom_Field__c FROM Custom_Object__c WHERE Another_Object__r.Custom_Field__c = :deviceType');   I haven't read about this being a known limitation.  I don't know if I should be using some other syntax/notation in the query -- the dotted notation appears correct.  Time to report a bug?  Thoughts on workarounds other than creating local variables to stand in for each member of the class?
43952
Which is the equivalent of mysql_data_seek using pdo objects? Can you give me an example?  Thanks!
65043
Apparently, I can connect to MySQL (at least from my localhost) without having to provide any username or password. I can even put anything as username, as long as the password is empty. I have access to the information_schema and test databases. I can create tables. If I run SELECT USER() it returns the proper value randomstring@localhost, where the random string is whatever I used for username when I connected.  The mysql.user table contains root@localhost, root@127.0.0.1, @localhost and pma@localhost. I manually set encrypted passwords to all the records (UPDATE user SET password=...) and only root has any privileges, the other two records have "N" for all privileges. That record with the empty username looks suspicious, but I don't think it has anything to do with this and I think it was there from the beginning.  To make matters worse, if I add a user with a password, I can only connect using empty string as password (just like if I put anything as username). If I try to connect using the username I created and password I supplied when creating it (CREATE USER .. IDENTIFIED BY ..) it doesn't work.  Does anyone know what is wrong and how I can fix this?  Note: I am using MySQL 5.5.16 for Windows, provided by the XAMPP package.
69918
So I have an SQL dump file that needs to be loaded using mysql_query(). Unfortunately, it's not possible to execute multiple queries with it.  -> It cannot be assumed that the mysql command-line client (mysql --help) is installed -- for loading the SQL file directly  -> It cannot be assumed that the mysqli extension is installed  /* contents of dump.sql, including comments */ DELETE FROM t3 WHERE body = 'some text; with semicolons; scattered; throughout'; DELETE FROM t2 WHERE name = 'hello'; DELETE FROM t1 WHERE id = 1;   The explode() below won't work because some of the dump content's values contain semicolons.  $sql = explode(';', file_get_contents('dump.sql')); foreach ($sql as $key =&gt; $val) {     mysql_query($val); }   What's the best way to load the SQL without modifying the dump file?
2798
I'm looking for a library that has functionality similar to Perl's , but for PHP. Basically, it should allow me to submit HTTP GET and POST requests with a simple syntax, and then parse the resulting page and return in a simple format all forms and their fields, along with all links on the page.  I know about CURL, but it's a little too barebones, and the syntax is pretty ugly (tons of curl_foo($curl_handle, ...) statements  Clarification:  I want something more high-level than the answers so far. For example, in Perl, you could do something like:  # navigate to the main page $mech-&gt;get( 'http://www.somesite.com/' );   # follow a link that contains the text 'download this' $mech-&gt;follow_link( text_regex =&gt; qr/download this/i );  # submit a POST form, to log into the site $mech-&gt;submit_form(     with_fields      =&gt; {         username    =&gt; 'mungo',         password    =&gt; 'lost-and-alone',     } );  # save the results as a file $mech-&gt;save_content('somefile.zip');   To do the same thing using HTTP_Client or wget or CURL would be a lot of work, I'd have to manually parse the pages to find the links, find the form URL, extract all the hidden fields, and so on. The reason I'm asking for a PHP solution is that I have no experience with Perl, and I could probably build what I need with a lot of work, but it would be much quicker if I could do the above in PHP.