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).
Related
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'])
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 :)
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
I am doing a project work on php. During my work every single query work smoothly. But when I want to delete any object using it won't delete ...
Here's my php code
<?php
//delete item
if(isset($_GET['deletecat'])){
$id_to_delete = $_GET['deletecat'];
$sql = mysql_query("DELETE FROM `category` WHERE `Category_id`=$id_to_delete LIMIT 1") or die('Error: Could not delete.');
}
else{
header('location: category.php');
exit();
}
?>
and after that I only get the error message.
GET value is OK. And on my phpmyadmin this SQL running OK. But there's a pop up message appear when I want to delete any object. what can I do now?
there's a few layers where you could be having issues: with the db connection, the query, or the data which you are sending.
also, you are not filtering for " and ' marks so you could be in trouble there, and you're not ensuring that your id is a number so your sql could also be failing there.
but, you can figure that out with a few adjustments to your code.... you can insert some diagnostics into your code to see what mysql is reporting the error as and get a better idea of how to fix it.
note that it is [generally recommended][1] to use mysqli extension instead of mysql extension, but irregardless, here's sample code with the extension you are currently using
hope this helps!
<?php
if ( isset($_GET['deletecat'])) {
#dbh -> database resource.
$dbh = mysql_connect()
#mysql_connect returns false if it fails. capture error and echo to output.
if (!$dbh) {
die("Could not connect to database server: ".mysql_error()."\n");
#if using mysqli use mysql_connect_error() instead
}
#never trust input. use an escape function.
$id_to_delete = mysql_real_escape_string($_GET['deletecat'],$dbh);
#force $id_to_delete to be treated as a number, or make it safer in your sql.
#i used the latter method below.
$sql = "DELETE FROM `category` WHERE `Category_id` = '$id_to_delete' LIMIT 1");
#mysql_query returns false on failure
$result = mysql_query($sql,$dbh);
#on failure catch the error and display the exact contents of 'deletecat' in a web-friendly way.
if (!$result) {
$error=mysql_error($dbh);
die ("Error: Could not delete '"
.htmlentities(print_r($_GET['deletecat'],true)).". Error: $error\n"
);
}
#if we did not trigger die() above we are ok.
header('location: category.php');
exit();
}
?>
:
[1]: see warning at http://php.net/manual/en/function.mysql-connect.php
You should escape the GET variable first to avoid any SQl injection attacks as already said by deceze. Then, you should understand that the message given by phpmyadmin is a confirmation if you need to execute the delete query. you can use mysql_real_escape_string($value) to escape but as php vendor says, this function will be removed very soon and is currently deprecated.
bye..
This is my first code-question! I'm a beginner at both MySQL and PHP, so this might be really simple! Here is my code:
This is a file included in my Index.php...:
<?php
$query="SELECT * FROM wines WHERE Type='$type' AND Country='$country'";
$products=mysql_query($query);
?>
And these are the variables set with the $_GET function:
<?php
$type=$_GET['type'];
$fruit=$_GET['fruit'];
$country=$_GET['country'];
?>
And then later I'll fetch the array and work with it.
The problem is that my $query works fine with just the '$type'-variable, but not with the $country -variable - - - - or any other variable I've tried.
I use Microsoft Webmatrix and it tells me that the issue arises the very moment I type in the $-sign in the second variable...
So confused! Hope you can help a newcomer :)
EDIT: I found out the problem was with the "ticks" around my variables. The correct way to do it is with backticks ( `` ). Also, I started using PDO and MySQLi instead of mysql. For beginners, MySQLi is probably the easiest. Started sanitizing too.
Just a couple of (important) points to note...
You should probably be using the mysqli_* functions in the place of the mysql_ functions, as they are going to be deprecated in a following release.
start sanitizing your input before making DB queries. It's a good habit to get into early, and will save you a lot of headaches in the long run!
a good habit it to use sprintf and mysqli_real_escape_string to build your SQL before executing it on the db:
$sql = sprintf("SELECT * FROM wines WHERE Type='%s' AND Country='%s'" ,
mysqli_real_escape_string($db_object, $type),
mysqli_real_escape_string($db_object, $country));
$results = mysqli_query($db_object, $sql);
ps. in my example $db_object is coming from the call to mysqli_connect()
EDIT:
Using the (soon-to-be-defunct) mysql_ functions would be something like the following for the above example:
$sql = sprintf("SELECT * FROM wines WHERE Type='%s' AND Country='%s'" ,
mysql_real_escape_string($type),
mysql_real_escape_string($country));
$results = mysql_query($sql);
If you don't send a $type in your query string, the query is
SELECT * FROM wines WHERE Type='' AND [other stuff];
which will give back only wines with type = '';
Try:
<?php
$wheres=array();
if (isset($type)){$wheres['Type']=$type;}
if (isset($type)){$wheres['Country']=$country;}
// and so forth for each parameter
$query="SELECT * FROM wines";
if (count($wheres) != 0){
$query.=" WHERE ";
foreach ($wheres as $k => $v){$query.="$k='$v' AND ";}
$query.=" 1=1;"
}
$products=mysql_query($query);
?>