Secure string variable in PDO - php

Finally i am migrating from sql to PDO but i am little bit confused about string'
Here is my code which work perfect and secured from sql injection
$connect = new PDO("mysql:host = localhost;dbname=sqlitest" , "root" , "");
$catId = $_GET["Id"]; //Id = int eg:1
$query = "select * from viewimage where ImageCategory =? ";
$result = $connect->prepare($query);
$result->execute(array($catId));
$result->setFetchMode(PDO::FETCH_ASSOC);
while($fetch = $result->fetch()):
$img = $fetch["Image"];
echo "<img src='img/event/$img' height='300px' width='300px'>";
endwhile;
but when $catId = $_GET["Id"]; where Id is a string string eg: ColorDay and i try
localhost/test/view.php?id=ColorDay'
no image display in above case if I put
localhost/test/view.php?id=1'
result same and redirect on same page containing image,which command should i use to secured from 'No Image Result' in string

this line:
$result->execute(array($catId));
Makes your code secure. If the image is not returned, it's another problem but to me it looks like it's an expected behavior.

Encode any string that goes into your url and decode data before you use in application (see this)
Watch out for XSS, don't just output string from your database to browser.
See this answer on how to completely prevent SQL Injection.

Related

Update database with php is not working

i have a form to update informations about a product. the form gets the values from the database and sends it to the page that should update the database. i checked that form sends the values to the second page correctly. but the update function of database is not updating.
the code of the update (second) page is like that:
include("database.php");
if (isset($_REQUEST["kullanici"])) {
include "database.php";
$sql = ("select * from uye");
}
else {
header ("Location: uyari.html");
}
$id = $_POST['id'];
$urunadi = $_POST['urunadi'];
$malzemekodu = $_POST['malzemekodu'];
$urunkategorisi = $_POST['urunkategorisi'];
$birim = $_POST['birim'];
$miktar = $_POST['miktar'];
$personel = $_POST['personel'];
$birimfiyat = $_POST['birimfiyat'];
$fiyatbirimi = $_POST['fiyatbirimi'];
$resim = $_POST['resim'];
$sql = ("UPDATE depo SET id = $id, urunadi = $urunadi, malzemekodu = $malzemekodu, urunkategorisi = $urunkategorisi, birim = $birim, miktar = $miktar, personel = $personel, birimfiyat = $birimfiyat, fiyatbirimi = $fiyatbirimi, resim = $resim WHERE id = $id");
$kayit = mysql_query($sql);
if (isset ($kayit)){
echo "Stok Kaydınız Yapılmıştır.";
}
else {
echo "Stok Kayıt Başarısız.";
}
how could i solve this problem?
query variable should be quoted try change update query to
$sql = ("UPDATE depo SET id = '$id', urunadi = '$urunadi', malzemekodu = '$malzemekodu', urunkategorisi = '$urunkategorisi', birim = '$birim', miktar = '$miktar', personel = '$personel', birimfiyat = '$birimfiyat', fiyatbirimi = '$fiyatbirimi', resim = '$resim' WHERE id = '$id'");
If still issue check your post data is getting on this page Also use mysql_real_escape_string() to escape your post data
Note :- mysql_* has been deprecated use mysqli_* or PDO
You must add quotes around the fields when updating / inserting strings. The same applies to date fields.
Also you should format all strings with mysql_real_escape_string() as this prevents hackers being able to attack your database by passing SQL in the string. For integers and floats you should use intval() and floatval() for the same reason.
Lastly, you should also length cut a string to the text length of the string field, in PHP use substr(). This prevents an error if the string length is longer than the field allows (some older browsers don't support lengthcut).
$personel = mysql_real_escape_string(substr($_POST['personel'], 0, 45)); // 45 = string length
$id = intval($_POST['id']);
Try using mysqli instead of mysql (depreciated) in PHP, you can also use PDO, however PDO is not as comprehensive and upto date as MYSQLI, and due to this is slightly slower. The only advantage of PDO over MYSQLI is that PDO also works with PostgeSQL, so switching database engine is easier, however the SQL between MYSQL and PostreSQL differ slightly, so it's not that easy.

php save html-code in phpmyadmin

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

SQL syntax error edit post

getting :
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 's Creed III', description='The plot is set in a fictional
history of real ' at line 2
when trying to edit posts on a database.
heres my display and edit php:
$result = mysql_query("SELECT * FROM gallery");
while ($row = mysql_fetch_array( $result )){
// while looping thru each record…
// output each field anyway you like
$title = $row['title'] ;
$description = $row['description'];
$year = $row['year'];
$rating = $row['rating'];
$genre = $row['genre'];
$filename = $row['filename'];
$imageid = $row['imageid'];
include '../modules/edit_display.html';
}
// STEP 2: IF Update button is pressed , THEN UPDATE DB with the changes posted
if(isset($_POST['submit'])){
$thisTitle = $_POST['title'];
$thisDescription = $_POST['description'];
$thisYear = $POST['year'];
$thisRating = $POST['rating'];
$thisGenre = $POST['genre'];
$thisNewFilename = basename($_FILES['file']['name']);
$thisOneToEdit = $_POST['imageid'];
$thisfilename = $_POST['filename'];
if ($thisNewFilename == ""){
$thisNewFilename = $thisfilename ;
} else {
uploadImage();
createThumb($thisNewFilename , 120, "../uploads/thumbs120/");
}
$sql = "UPDATE gallery SET
title='$thisTitle',
description='$thisDescription',
year='$thisYear',
rating='$thisRating',
genre='$thisGenre',
filename='$thisNewFilename'
WHERE
imageid= $thisOneToEdit";
$result = mysql_query($sql) or die (mysql_error());
}
You're suffering from an imminent dose of SQL Injection due to using a dangerous user input model.
When you type "Assassin's Creed III" in the title field, that gets placed in single quotes in the UPDATE statement in your code (via the $_POST['title'] variable):
'Assassin's Creed III'
The problem there is that MySQL sees it as 'Assassin', followed by s Creed III'. It doesn't know what to do with the latter.
Of course, this becomes a HUGE problem if someone types in valid SQL at that point, but not what you expected. Have a look at How can I prevent SQL injection in PHP? or any of several other advices on avoiding SQL Injection.
i have seen you are adding ' into database so you need to escape it using addslashes()
addslashes($thisTitle)
You have syntax error here. Use $_POST instead of $POST.
Replace
$thisYear = $POST['year'];
$thisRating = $POST['rating'];
$thisGenre = $POST['genre'];
With
$thisYear = $_POST['year'];
$thisRating = $_POST['rating'];
$thisGenre = $_POST['genre'];
you need to escape your input like
$thisDescription = mysql_real_escape_string($_POST['description']);
do this for all input that contains quotation marks etc..
NOTE: mysql will soon be gone so its advised to write new code using mysqli instead
You have alot of issues in your script.
You're trying to add ' character to database, you need to escape it properly with addslashes.
You're vulnerable to SQL Injection. Escape it properly with mysql_real_escape_string, or even better, use PDO.
Third, it is $_POST, not $POST. You're using it wrong in some areas.
Add quotes to $thisOneToEdit in query.
The error is causing because you're trying to add Assasin's Creed III string to database. The single quote breaks your query and creates a syntax error.
Do a addslashes() on the values that might contain single or double quotes like below before using them in query
$thisTitle = addslashes($_POST['title']);

mysql table fields - Resource id #6

I have a database (db_name=members) with a lot of fields but the relevant ones for this are:
security_question, security_answer, email
The php code is:
$email = $_COOKIE['site_user'];
$select_sa = mysql_query("SELECT security_answer FROM members WHERE email='".$email."'");
$result_sa = mysql_query($select_sa);
$arr_sa = mysql_fetch_row($result_sa);
$result2 = $arr_sa[0];
$get_sa = $result2;
If I
echo $select_sa;
It prints "Resource id #6" although in the table I can see the security answer as a word and not "Resource id #6".
If I
echo $get_sa;
It prints nothing.
Could you please help me to be able to read the securty_answer field from the database ?
Thanks,
Ray
You're doing the query twice, feeding the result handle from the first time into the query text parameter of the second one. That's invalid. Try this instead:
$select_sa = "SELECT security_answer FROM members WHERE email='".$email."'";
$result_sa = mysql_query($select_sa);
$arr_sa = mysql_fetch_row($result_sa);
$result2 = $arr_sa[0];
$get_sa = $result2;
Please also make sure that the $email field is being passed through mysql_real_escape_string() before being used in the query. All data fetched from the user, e.g. via $_GET, $_POST or $_COOKIE, must be escaped properly. If you don't escape it, you'll be open to SQL injection attacks.

Insert special characters to a string for web address

Im fetching an array from my sql database, but the string has spaces in it (ie B54DT45 GDT4563 HaK7698).
This needs to go into a webadress like %30B54dT45%20 so that the outcome is
Here is my code:
$pid = mysql_query("SELECT cPushID FROM tblUsers WHERE intUserID='20' AND Length(cPushID) > 70 AND cAlerts = 'All'");
$url = rawurlencode("");
$msg = "test";
file_get_contents("http://domain/push.php?msg=$msg&to=$url");
The string in the database is something like as an example. That exact string needs to be send to the push.php script on the remote server for it to run correctly
rawurlencode()
because the space must be %20 according to the question.
edit: the question wasn't very clear, but to add < and > before encoding, just do
rawurlencode("<$txt>");
edit: the question has evolved into a mysql question, here's a short answer
$res = mysql_query("SELECT `this` FROM `that`");
$row = mysql_fetch_row($res);
$this = $row[0];
or
$res = mysql_query("SELECT `this` FROM `that`");
$row = mysql_fetch_assoc($res);
$this = $row['this'];
urlencode or rawurlencode, depending on if you want spaces as + or %20.
Use urlencode then urldecode it before inserting it to the database.

Categories