I have my database and im retrieving data like below.But i need to retrieve them more secure for prevent by the sql injections.in my script im getting all the fields like below and in echo out in a place where i want to show the fields.
Please tell me a secure way to get them.Please help me,any help much appreciated.
And i want to use while function to retrieve all the data.Please help me
<?php
$getdata ="SELECT * FROM tblname ODER BY ";
$result = mysql_query($getdata);
$row = mysql_fetch_array($result);
$bookName = $row['bookName'];
$timestamp = $row['timestamp'];
$Country = $row['Country'];
$Category = $row['Category'];
$Price = $row['Price'];
$Photo1name = $row['Photo1name'];
?>
SQL injection can only be performed if you use user input.
So you are safe with that when you read from database. With your code you must use mysql_real_escape_string, but I suggest using PDO and it's prepared statements to auto-escape values.
$sth = $dbh->prepare('SELECT * FROM tblname WHERE name = :name ORDER BY');
$sth->execute([':name' => $_POST['name']]);
$result = $sth->fetchAll();
To sanitize your output try using htmlentities or strip_tags functions.
To prevent SQL injection you have to escape values:
$pdo = PDO('mysql:host=localhost;dbname=test', 'root', 'iAmD4B3st!');
$sql = $pdo->prepare("INSERT INTO my_table (name, surname) VALUES (:name, :surname)");
$sql->execute([
':name' => isset($_POST['name']) ? $_POST['name'] : '',
':surname' => isset($_POST['surname']) ? $_POST['surname'] : '',
]);
Related
I've got an HTML form into which a user can enter an SQL query.
The query needs to be entered into a field of my MYSql database. But for complex queries that include % _ , ; ' " $ < > etc... it fails.
How would i go about entering this info into the DB without error?
I know the below is not a very secure way to do it, for now, I just need it to work :)
// Get values from form
$username = $_SESSION['user'];
$appname = $_POST['appname'];
$sql2 = $_POST['sql'];
// Insert data into mysql
$sqlquery="INSERT INTO puresql (username,appnm, query)VALUES('$username','$appname', '$sql2')";
$result=mysqli_query($dbconn,$sqlquery);
For anyone else with this issue. the below works, using mysqli_real_escape_string
$date = date("Y/m/d");
echo "$date";
$appname = mysqli_real_escape_string($dbconn, $_POST['appname']);
$sql2 = mysqli_real_escape_string($dbconn, $_POST['sql']);
$username = mysqli_real_escape_string($dbconn, $_SESSION['user']);
// Insert data into mysql
$sqlquery="INSERT INTO livepurespark (username,appnm, query, date)VALUES('$username','$appname', '$sql2', '$date')";
$result=mysqli_query($dbconn,$sqlquery);
Another way of saving complex texts in database fields with added benefit of protection from sql injection is by using parameterized query statements (Prepared Statements).
$username = $_SESSION['user'];
$appname = $_POST['appname'];
$sql2 = $_POST['sql'];
$stmt = mysqli_prepare($dbconn, "INSERT INTO puresql (username,appnm, query)VALUES('?','?','?')");
mysqli_stmt_bind_param($stmt, "sss", $username, $appname, $sql2);
mysqli_stmt_execute($stmt);
I am in need of some help, please? I can successfully do a MySQL query using:
IP_Address/fund_list.php?Id_Number=555666
With this below:
$ID = $_GET['Id_Number'];
$sql = "SELECT * FROM fund_list WHERE Number = ".$ID;
Now I want to use 2 different things in my web call. Like:
IP_Address/fund_list.php?Id_Number=555666&Name=Billy
But I don't know how to write the 'get' line below.
$ID = $_GET['Id_Number'] & $Name = $_GET['Name']; <-- Does not work
I would think the SQL select statement would be:
$sql = "SELECT * FROM fund_list WHERE TheNumber = .$ID AND TheName = .$Name";
All the things I look up online, the syntax is overly confusing, I can't dissect it and make something work. Thank you.
To start with you should really be preparing your statements, passing data directly from a query string into a SQL query is really dangerous. You should also avoid using * in your SELECTs if you insist on not preparing them.
Your issue in this case is you need '' around TheName =
$sql = "SELECT * FROM fund_list WHERE TheNumber = {$ID} AND TheName = '{$Name}'";
Regardless, what you should be doing is this:
$sql = "SELECT Param1, Param2 FROM fund_list WHERE TheNumber = ? AND TheName = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("is", $ID, $Name);
$stmt->execute();
$stmt->bind_result($param1, $param2);
while($stmt->fetch()) {
//Your code
}
That code prevents SQL injection attacks, and a number of other potential issues you can create not using PDO or mysqli prepared statements.
Edit per request:
$ID = $_GET['Id_Number'];
$Name = $_GET['Name'];
$sql = "SELECT * FROM fund_list WHERE TheNumber = {$ID} AND TheName = '{$Name}'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
//your code
}
You need '' when comparing string parameters in SQL.
Have you tried doing this? This always works to me
$ID = $_GET['Id_Number'];
$Name = $_GET['Name'];
I'm sorry if this is a duplicate question but I don't know how to solve my problem. Every time I try to correct my error I fail. My code is:
if (isset($_GET["comment"])) {$id = $_GET["comment"];}
$query = "SELECT * FROM posts WHERE id = {$id['$id']};";
$get_comment = mysqli_query($con, $query);
Can anybody correct the code to not show an error anymore and tell me what did I wrong?
Try this:
$id = isset($_GET['comment']) ? $_GET['comment'] : 0;
$query = "SELECT * FROM `posts` WHERE `id` = " . intval($id);
The use of intval will protect you from SQL injection in this particular case. Ideally, you should learn PDO as it is extremely powerful and makes prepared statements much easier to handle to prevent all injections.
An example using PDO might look like:
$id = isset($_GET['comment']) ? $_GET['comment'] : 0;
$query = $pdo->prepare("SELECT * FROM `posts` WHERE `id` = :id");
$query->execute(array("id"=>$id));
$result = $query->fetch(PDO::FETCH_ASSOC); // for a single row
// $results = $query->fetchAll(PDO::FETCH_ASSOC); // for multiple rows
var_dump($result);
First of all you should prevent injestion.
if (isset($_GET["comment"])){
$id = (int)$_GET["comment"];
}
Notice, $id contanis int.
$query = "SELECT * FROM posts WHERE id = {$id}";
Assuming your $id is an integer and you only want to make the query if it is set, here's how you could do it using prepared statements, which protect you from MYSQL injection attacks:
if (isset($_GET["comment"])) {
$id = $_GET["comment"];
$stmt = mysqli_prepare($con, "SELECT * FROM posts WHERE id = ?");
mysqli_stmt_bind_param($stmt, 'i', $id);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $get_comment);
while (mysqli_stmt_fetch($stmt)) {
// use $get_comment
}
mysqli_stmt_close($stmt);
}
Most of these functions return a boolean indicating whether they were successful or not, so you might want to check their return values.
This approach looks a lot more heavy duty and is arguably overkill for a simple case of a statement containing a single integer but it's a good practice to get into.
You might want to look at the object-oriented style of mysqli which you might find a little cleaner-looking, or alternatively consider using PDO.
I'm trying to sanitize a string going into my database. But with the code below, I don't get the update to my db.
First page posts this in an input form:
$note="Here is some example text";
Receiving page:
$note = $_POST['note'];
$note = mysql_real_escape_string($note);
$sql="UPDATE some_table SET notes='$note' WHERE id='$some_id'";
$result=mysql_query($sql);
When I take out the mysql_real_escape_string line it works, but not with it in there.
What am I missing?
Thanks!
I strongly recommend using Prepared Statement, mysql_real_escape_string() won't full protect you from SQL Injection.
Example for your update:
<?php
// connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$sql = "UPDATE some_table
SET notes=?
WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($$_POST['note'], $some_id));
?>
More details: http://www.php.net/manual/en/intro.pdo.php
Could someone show me how I would go about converting my current UPDATE tablename SET column into a safe and secure statement using PDO to protect against SQL injection ? I am trying to better understand binding and PDO but am having trouble with setting it up with PDO. Here is what I currently have with regular msqli
<?php
session_start();
$db = mysqli_connect("hostname", "username", "password", "dbname");
$username = $_SESSION['jigowatt']['username'];
mysqli_query($db, "UPDATE login_users SET Points=Points+15 WHERE username='$username'");
?>
MySQL
You don't need PDO or MySQLi for that. mysql_real_escape_string protect you against sql injection:
$name = 'Bob';
$age = 25;
$description = "' OR 1=1"; // a SQL injection string
$query = "
UPDATE people(name, age, description)
VALUES ('".mysql_real_escape_string($name)."', ".(int) $age.", '".mysql_real_escape_string($description)."');";
// a secure query execution
$result = mysql_query($query);
PDO
With PDO::quote()
PDO::quote() is equal to mysql_real_escape_string:
$pdo = new PDO(...);
$name = 'Bob';
$age = 25;
$description = "' OR 1=1"; // a SQL injection string
$query = "
UPDATE people(name, age, description)
VALUES (".$pdo->quote($name).", ".(int) $age.", ".$pdo->quote($description).");";
// a secure query execution
$result = $pdo->query($query);
With prepared statements
You can use prepared statements. You could put the hole query inside the prepared statement, but it is better to use placeholders for variables:
$pdo = new PDO(...);
$name = 'Bob';
$age = 25;
$description = "' OR 1=1"; // a SQL injection string
$query = "
UPDATE people(name, age, description)
VALUES (:name, :age, :description);";
$stmt = $pdo->prepare($query); // prepare the query
// execute the secure query with the parameters
$result = $pdo->execute(array(
':name' => $name,
':age' => $age,
':description' => $description,
));