Placing PHP variable inside SQL - mysql

I am trying to send city from a page to another and then show items from database where city is the mentioned city but this code does not return any results. Please guide. I am sure everything else is fine with the code.
$city = $_POST["city"];
$sql = "SELECT id,full_name, email, password,full_address,city,age,contact_number,gender,education FROM users WHERE city=$city";

// strip tags from the input
$city = strip_tags($_POST["city"]);
// escape the input to prevent sql injection (assuming you are using mysqli() as your connection method...)
$city = mysqli_real_escape_string($city);
// your query does not work because you need to put strings inside single quotes
$sql = "SELECT id,full_name, email, password,full_address,city,age,contact_number,gender,education FROM users WHERE city='$city'";

Actually, you're not even executing the request on your mysql server, but if you are using PDO (what you SHOULD do), just do something like this:
<?php
$bdd = new PDO(etc);
$req = $bdd->prepare("SELECT id,full_name, email, password,full_address,city,age,contact_number,gender,education FROM users WHERE city=?");
$req->execute(array($_POST['city']));
print_r($req->fetchAll());
?>
And here you go, $req->fetchAll() will return you an array with each element returned by your request, and the best part is that prepare will prevent you from every SQLi
Edit: You can use short syntax for array [$_POST['city']] or old and complete syntax: array($_POST['city'])

Related

Get content from another DB in wordpress

I have found out how to make a page for WordPress, where I can write PHP code into.
However, I can not figure out how to retrieve content from another database.
I have found the connect code:
$wpdb2 = new wpdb($dbname, $dbpass, $dbuname, $dbhost);
but I cannot figure out how to retrieve content from the database.
Can someone give an example?
If, for example, have this query
SELECT number
FROM qr_statistic
WHERE date = '$today'
please see this:
wpdb::get_results( string $query = null, string $output = OBJECT )
now you can write your query:
$result = $wpdb->get_results("SELECT number FROM $wpdb->qr_statistic WHERE WHERE date = '$today'");
also see this link

how to inject sql in login process

I've received an old application which completely lacks user input sanitization and is vulnerable to sql injection. To prove gravity of the situation i need to give client an example and what can be better to scare him than the login process. I've tried standard techniques but the problem with them is that they return multiple rows and due to nature of the code it returns an error instead of logging him in. What sql should i inject so that only a single row is returned and the execution reaches "return $access" line in order to pass the value of this "access" column to code calling this login function. The request is made via POST method and magic quotes are off on the server. Please let me know if you need any other information.
function login($username, $pw)
{
global $dbname, $connection, $sqluser, $sqlpw;
$db = mysql_connect($connection,$sqluser,$sqlpw);
mysql_select_db($dbname);
if(!($dba = mysql_query("select * from users where username = '$username' AND password = '$pw'"))){
printf("%s", sprintf("internal error5 %d:%s\n", mysql_errno(), mysql_error()));
exit();
}
$row = mysql_fetch_array($dba);
$access = $row['access'];
if ($access != ''){
return $access;
} else {
return "error occured";
}
mysql_close ($db);
}
Note: it turns out that magic_quotes_gpc is turned on and the php version is 5.2.17
Thanks
Starting with the goal query:
SELECT *
FROM users
WHERE username = '' OR '1'='1'
AND password = '' OR 1=1 LIMIT 1;#'
We get username is ' OR '1'='1 and password is ' OR 1=1 LIMIT 1;#
It depends what values the login function is called with. If there's sanitation before passing it to the function it might actually be safe. However it's better to filter it right before the query so you can see that your built query is safe.
However if you have something like this:
login($_POST['user'], $_POST['pass']);
In that case just put foo' OR 1=1 OR ' in the user field in the login form :)

Retrieving email addresses with special characters using MySQL query

I am fairly new to PHP and Mysql. The question I am going to ask will be begging for someone to tell me to use prepared statements so first of all let me say I am learning this, but not quite there yet. I have a query that looks to see if an email address is in the database. The email addresses may contain unusual characters like - , / | "" etc etc. I can't seem to retrieve them - here is my code (the repeatemail is coming from a form). Works perfectly with email addresses without this characters.
$checkemail = $_POST['repeatemail'];
$checkemail = mysqli_real_escape_string($con, $checkemail);
//Perform database to see if email exists
$query = "SELECT email FROM scorers WHERE email = '{$checkemail}'";
$result = mysqli_query($con, $query);
$row = mysqli_fetch_row($result);
if ($row[0] == $checkemail){
echo "found";
} else {
echo "not found";
}
As it stands I have wondered if the escape string is stripping the unusual characters and therefore once its queried it been altered but that doesn't seem to be the case. Also, I have no problem entering addresses like simon.o'malley#nhs.uk but just can't check them with the above code. Looked up many explanations regarding UTF etc but its a bit above my head at this point. Could someone give me a solution to this....how do I alter the code above so it will pick out these funky email addresses? Many thanks
Got it...this works fine but if any of you have major concerns let me know. Its the magic quotes issue that seemed to be the only problem. All other characters seem fine
$checkemail = $_POST['repeatemail'];
$check_email_no_slashes = $checkemail;
$checkemail = mysqli_real_escape_string($con, $checkemail);
echo $check_email_no_slashes . "</br>";
//Perform database to see if email exists
$query = "SELECT email FROM scorers WHERE email = '{$checkemail}'";
$result = mysqli_query($con, $query);
$row = mysqli_fetch_row($result);
if ($row[0] == $check_email_no_slashes){ etc etc etc .......}
Thanks for your input Tim.
You really need to use prepared statements. If you don't, you're asking for SQL injection issues (see http://en.wikipedia.org/wiki/SQL_injection). For example, I could send you an email address that would delete all the rows in your table.
Prepared statements aren't hard; here's an example:
$stmt = $mysqli->prepare("SELECT email FROM scorers WHERE email = ?")
// use the string in $checkemail in place of the ?
$stmt->bind_param("s", $checkemail);
// run the query
$stmt->execute();
// put the result into $email
$stmt->bind_result($email);
if ($stmt->fetch()) {
// found a matching email; do something about it
}
$stmt->close();
You can read more about prepared statements in the PHP docs: http://php.net/manual/en/mysqli.prepare.php

mysql_real_escape_string with variables extracted from an array

original post:
My script is not working (it's not recording the data). It was working before I added the mysql_real_escape_string, so I'm wondering if maybe I have not implemented it correctly:
$array = json_decode($downstream,TRUE);
$name = $array["status"]["name"];
$title = $array["status"]["title"];
$table = "mrTable";
$insert = "INSERT INTO $table (name, title) VALUES ('".mysql_real_escape_string($name)."', '".mysql_real_escape_string($title)."')";
Does that implementation at INSERT look correct to you?
UPDATE:
Here is the entire code, hopefully this will help. It is still not working though. When the real_escape_string function is used, NONE of the data elements get recorded in the database. As soon as I remove the escape function, data is written fine (unless of course an apostrophe shows up).
Here we go:
//read contents of this file:
$json_data = file_get_contents('../list.txt');
//json to a php array
$array = json_decode($json_data,TRUE));
//store in mysql table
$table = "table1";
$name = mysql_real_escape_string($array["current"]["name"]);
$code = mysql_real_escape_string($array["current"]["code"]);
$insert="INSERT INTO $table (name, code) VALUES ('$name', '$code')";
$con = mysql_connect($db, $user, $pass);
if (!$con)
{
die ('Could not connect: ' . mysql_error());
};
mysql_select_db($yup, $con);
mysql_query($insert) OR die(mysql_error());
mysql_close($con);
UPDATE 2
Fixed! You need to connect to the database before first mentioning mysql_real_escape_string. Everything is working now...no blank data.
You need to be connected to a database to use mysql_real_escape_string. You don't seem to be. Make sure mysql_connect is over your line where you define $insert
Never insert values directly into a query string! Even if they are escaped, it's not a smart idea. Instead, use parametrised statements as such, which will render attacks like ' OR 1 = 1-- useless. You don't need to escape values for parametrised statements either...
PREPARE statement FROM
'INSERT INTO table (col1, col2)
VALUES
(?, ?)'
EXECUTE statement USING ('val1', 'val2')
DEALLOCATE statement
Deallocate only when you're done. You can re-execute as many times as you'd like with different values. If you are going to re-execute anyways, there is a gain in performance as well from doing it this way! (Because the statement is only prepared once for an infinite number of executions.) I advise you to implement this method and then come back if you are still having problems.
Please don't try to escape your parameters. Use bind variables. See http://bobby-tables.com/php.html for examples.

Query only working on PHPMyAdmin

I'm trying this query:
//connect;
$site = mysql_real_escape_string($_GET['site']);
$data = mysql_query("SELECT * FROM Items WHERE Site = '$site'");
while($row = mysql_fetch_array( $data ))
{
print $row['type'];
}
doesn't print anything, running SELECT * FROM Items WHERE Site = 'http://rollingstone.com/' from PHPMyAdmin returns one row.
I'm sure it must be something really basic, since I haven't got much experience with MySQL.
I'm trying it here btw: http://www.chusmix.com/game/insert/get-items.php?site=http://rollingstone.com/
What am I doing wrong?
Make sure $site actually contains something; doing a quick echo $site before your mysql_query() should tell you this. If it's empty, try print_r($_GET) to see if it's in the $_GET array. It should be, but it might not for some other reason; check any code above this snippet for stuff that modifies $_GET or $_REQUEST in any way.
To request data from a MySQL table, you need to connect to the server using mysql_connect(), then select the database with mysql_select_db(). PHP should throw errors, but to be sure put these lines at the top of your script:
error_reporting(E_ALL);
ini_set('display_errors', '1');
All errors will now be shown.
In addition, you can also test for how many rows that were returned using mysql_num_rows(). For example:
if(mysql_num_rows($data) !== false)
{
while(...)
{
...
}
}
else
{
echo "No rows";
}
Will echo No rows if there weren't any results from the query. This is all error detection code; the cause of your error isn't obvious, so a little investigation is necessary, using the above methods (and any more you can think of).
Have you called mysql_select_db('your_database_name'); on the connection first? Have you tried echoing out the SQL before it's executed to confirm that Site is what you expect it to be?
$query = sprintf("SELECT * FROM Items WHERE Site ='%s'",
mysql_real_escape_string($site));
$result = mysql_query($query);
Just to be on the safe side (avoid SQL Injections).