Make Pdo Preserve Backslash - php

Basically i want to store a path to an image into the database
Example:I want to save 'C:\wampp\www\project\images' into database
Instead Pdo remove all the backslash and make it into 'C:wamppwwwprojectimages'
Is there a way to make Pdo keep the backslash?
Update with code:
$sql = "INSERT INTO meal (pic_path) VALUES('C:\wamp\www\project')";
$db = new PDO( $dsn, $username, $password );
$stmt = $db->prepare( $sql );
$stmt->execute();

The reason that this is happening is because you're using double quotes (") around your query, and since the back slash (\) is the escape character, it's being dropped. You can fix this by placing two back slashes together so it will yield one (C:\\wamp\\www\\project).
However, Passing it to prepare as an argument would be a better idea, and you can keep the double quotes.
$directory = "C:\wamp\www\project";
$sql = "INSERT INTO meal (pic_path) VALUES(?)";
$db = new PDO( $dsn, $username, $password );
$stmt = $db->prepare( $sql );
$stmt->execute(array($directory));
Read more about prepared statements.

You should use PDO's variable substitution to safely insert values into the database. To edit your code, it would look like this:
$sql = "INSERT INTO meal (pic_path) VALUES(?)";
$db = new PDO( $dsn, $username, $password );
$stmt = $db->prepare( $sql );
$stmt->execute(array('C:\wamp\www\project'));
PDO will replace the ? in your query with the escaped version of the string you pass.

Related

How to update and retrieve strings safely using mysqli prepared statement?

I am using a form to update data displayed on a site. This is just text information but it will contain apostrophes and quotes.
I figured using a prepared statement with parameters for both the Update SQL statement and Select statements would automatically escape and unescape the special characters respectively. This doesn't seem to happen. The prepared statement still messes up with an apostrophe due to the statement being malformed because of the apostrophe.
I work around this using mysqli_real_escape_string on my strings before updating but when I get the strings using another prepared statement (select with one parameter) the escaped apostrophe shows up in the text on the html page (ex: /'hello/' instead of 'hello' ).
So I use stripslashes. This works but I thought that mysqli prepared statements did this for you. Any ideas?
Update:
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "UPDATE table SET mycol= ? WHERE myparam= ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('ss', $mycol, $myparam);
if (!$stmt->execute()) {
echo "Error updating record: " . $stmt->error;
}
Get:
$mysqli = new mysqli($servername, $username, $password, $dbname);
if($mysqli->connect_error)
{
die("$mysqli->connect_errno: $mysqli->connect_error");
}
$sql= "Select * From table Where myvar= ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $myparam);
$stmt->execute();
$stmt_result = $stmt->get_result();
if ($stmt_result->num_rows>0) {
$row = $stmt_result->fetch_assoc(); }
Use "mysqli_real_escape_string" function to avoid security risks.
Sorry to bother people!
The prepared statement works as intended and I do not need to use mysqli_real_escape_string.
The issue I was seeing afterwards was me double escaping the text. It is fixed.
Thanks to everyone who responded!

PHP SQL prepared select query not returning anything

When I run the code below, it returns nothing. When I explicitly type a string in the place of the '?', it will return the expected result but using the prepared version has not worked for me thus far. I do not believe there is any kind of versioning issue as using prepared statements for INSERT queries has worked for me in the past. What might be the problem here with the prepared statement?
$pdo = new PDO("mysql:host=localhost;dbname=database", $user, $pass);
$sql = "SELECT * FROM table WHERE column LIKE '%?%';";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($_GET['searchterm']));
$results = $stmt->fetchAll();
print_r($results);
You are preparing the value so it isn't behaving as if you just put the string inside of the query.
When preparing a string you don't need to add " or ', that is done for you. You need to add the %'s into the value that you are escaping.
$pdo = new PDO("mysql:host=localhost;dbname=database", $user, $pass);
$sql = "SELECT * FROM table WHERE column LIKE ?;";
$stmt = $pdo->prepare($sql);
$stmt->execute(array("%{$_GET['searchterm']}%"));
$results = $stmt->fetchAll();
print_r($results);

mysql query does not get updated due to apostrophe sign

$url = "example.com";
$data = json_decode($raw);
$pname=$data->name;
$sql="UPDATE `client` SET pname='$pname' WHERE url='$url'";
$query=mysql_query($sql,$link)or die(mysql_error());
When the json data is decoded, the value in variable $pname goes in client table. If there is an apostrophe sign (') in name then it throws an error. What changes can I make in the variable to send the name to database table?
example:
Jerry get updated with no issues
D'Cunha does not get updated as it has the apostrophe sign. The query becomes
"UPDATE `client` SET pname='D'Cunha' WHERE url='example.com'"
I found some articles but that does not say about how to find the apostrophe sign and change the variable value
use mysql_escape_string()
$sql="UPDATE `client` SET pname='".mysql_escape_string($pname)."' WHERE url='$url'";
and learn mysqli or PDO as mysql is deprciated and soon going to be drop
Use prepared statements. Mysqli or PDO. Here's an example with mysqli:
$url = "example.com";
$data = json_decode($raw);
$pname=$data->name;
$mysqli = new mysqli($host, $user, $password, $db);
$stmt = $mysqli->prepare("UPDATE client SET pname = ? WHERE url = ?");
$stmt->bind_param("ss", $pname, $url);
$stmt->execute();
Why shouldn't I use mysql_* functions in PHP?
Try this:
UPDATE client SET pname = 'D\'Cunha' WHERE url = 'example.com'

PHP PDO Insert query with prepared statements

I am trying to run an sql query using PDO prepared statements
$sql = "INSERT INTO tickets (ticketnumber, status) VALUES (1234, Open) ";
$stmt = $connection->prepare($sql);
$stmt->execute();
But it is just not inserting. What have I done wrong?
Here is my connection:
$host = "localhost";
$db_name = "";
$username = "";
$password = "";
$connection = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
Try this. It's much more secure.
Make sure you have included your connection file.
EDITED
$sql = "INSERT INTO `tickets` (ticketnumber, status) VALUES (:ticketnumber, :status)";
$stmt = $connection->prepare($sql);
$stmt->bindValue(':ticketnumber', 1234, PDO::PARAM_INT);
$stmt->bindValue(':status', 'Open', PDO::PARAM_STR);
$stmt->execute();
Also, the named parameters used above must NOT be enclosed in quotes. If you do so, it'll be treated as a literal string and not a named parameter.
You need to use quotes on strings before inserting them into a database.
Why use prepare if you're not preparing your data before sending it to the database?

How can I get PDO bindValue/bindParam to bind with MySQL?

I've been using mysql and mysqli in the past, but am starting a new project, so wanted to go back to OOP with PDO-mysql .. however, it doesn't want to work:
$dbh = new PDO('mysql:host='.$host.';dbname='.$database, $username, $password);
if(isset($_POST["name"]) && isset($_POST["password"]))
{
$pwdHasher = new PasswordHash(8, FALSE);
$hash = $pwdHasher->HashPassword($_POST["password"]);
//$insert = $dbh->prepare('insert into users (username,password) values ("?","?")');
$insert = $pdo->prepare("insert into users (username,password) values (?,?)");
$insert->bindParam(1,$_POST["name"]);
$insert->bindParam(2,$hash);
$insert->execute();
echo "Registration Success!";
}
edit: The above code works if I change the code from the commented line to the non-commented (i.e. single quote to double quotes) However, this doesn't work later:
$query = $pdo->prepare("select * from users where username = ?");
$query->bindParam(1,$_POST["name"]);
$result = $query->execute()
Ok, you've found the answer to your first question.
For the second one it would be
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
called right after connect.
it will tell you what's going wrong with your query.
error_reporting(E_ALL);
also always helps with such errors like misspelled variables ($pdo is not $dbh for example)
If you want to use ? for placeholders, you are supposed to send an array to the execute-method matching the positions of the question marks. $insert->execute(array('value1', 'value2'));
You could however use named placeholders .. WHERE x = :myxvalue and use $insert->bindValue(':myxvalue', 'thevalue', PDO::PARAM_STR);
Also, please have a look at the difference between bindParam and bindValue
The answer to this question is simple and embarrassing:
I need to change the single quotes surrounding the sql statement being prepared to double quotes (and remove the double quotes where the '?' mark is.
change:
$insert = $dbh->prepare('insert into users (username,password) values ("?","?")');
to
$insert = $dbh->prepare("insert into users (username,password) values (?,?)");
and everything works.

Categories