How to Insert a Value That Might Contain an Apostrophe - php

How would I go about writing a SQL statement that would insert values that might contain an apostrophe (for example one person's last name was Conner and another's was O'Conner)? After some searching, I found examples using a double apostrophe (O''Conner example) but each example had the string hard coded in the the INSERT. I haven't run across any examples where the value may or may not contain an apostrophe.
My simple statement doesn't have any issues when no apostrophe is used but when one is it fails. I know I could replace the apostrophe using str_replace but, obviously, that would cause the O'Conner example to be displayed as OConner. 
Here is a shorthand version, just for an example:
page1.php
// PHP
include_once('phpdata.php');
if (isset($_POST['firstname']) && isset($_POST['lastname'])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
// SQL connection
$insert = doInsert($firstname, $lastname);
// Execute statement using odbc_exec, etc.
}
// HTML
<input type="text" class="required" name="firstname" id="firstname" />
<input type="text" class="required" name="lastname" id="lastname" />
phpdata.php
function doInsert($firstname, $lastname) {
$insert = "INSERT INTO mytable (firstname, lastname)
VALUES ('$firstname', '$lastname')";
return $insert;
}

Using PDO with prepared statements will take care of escaping your inputs :
$dsn = "mysql:host=localhost;dbname=your_db_name";
try {
$db = new PDO($dsn, 'your_username', 'your_pass');
} catch (PDOException $e) {
die( "Erreur ! : " . $e->getMessage() );
}
$query = "INSERT INTO mytable (firstname, lastname)
VALUES (:firstname', :lastname)";
$stmt = $db->prepare($query);
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->execute();
Doc : PHP Data Objects

You could use replace to replace all ' with ''. However, the proper way to do it is use parameterized queries where you pass your value to insert to the SQL Statement as a parameter. Then the language can clean up ' and any other characters/keywords that could cause an issue. No matter the language, parameterized queries are the way to go.

Consider using prepared statements. It's the best way to input user submitted data into a database. It makes sure the data is properly escaped automatically!
phpdata.php
<?php
function doInsert($firstname, $lastname) {
$insert = "INSERT INTO mytable (firstname, lastname)
VALUES (?, ?)";
$pstmt = odbc_prepare($odb_con, $insert); /* Use global $odb_con to access the connection */
$res = odbc_execute($pstmt, array($firstname, $lastname));
return $res; /* Should return TRUE on success. */
}
?>
Do note that I haven't included any error checking in my code. Might be wise to implement that as well.
Good luck!

You can try use function addslashes for prepare data before insert.
I don't know how your work with database but this function is simple way for ask to your question.
AddSlashes

Related

What is wrong with my PHP/SQL registration script?

I'm trying to make my first registration script using PHP/SQL. Part of my code isn't working:
if(!$errors){
$query = "INSERT INTO users (email, password) VALUES ($registerEmail, $registerPassword)";
if(mysqli_query($dbSelected, $query)){
$success['register'] = 'Successfully registered.';
}else{
$errors['register'] = 'Registration did not succeed.';
}
}
When I test my code I get the error 'Registration did not succeed.' For reference, $errors and $success are arrays. Is there anything wrong with this part of my script?
$dbSelected is:
$dbLink = mysqli_connect('localhost', 'root', 'PASSWORD');
if (!$dbLink) {
die('Can\'t connect to the database: ' . \mysqli_error());
}
$dbSelected = mysqli_select_db($dbLink, 'devDatabase');
if (!$dbSelected) {
die('Connected database, but cannot select
devDatabase: ' . \mysqli_error());
}
I'm sure I am connecting and selecting the database.
Any help would be greatly appreciated! I am very new to PHP/SQL so forgive me for any noob mistakes.
Quote the string like below
$query = "INSERT INTO users (email, password) VALUES ('$registerEmail', '$registerPassword')";
You can also do
echo $query;
and take the output on the browser, copy and paste into PHPMyAdmin and execute it from there. It should tell you what is wrong with the query.
I suggest you to use prepared statement as using string concatenation in SQL Statement is prone to SQL injection attack. Refer the example PHP mysqli prepare
First off, PHP is deprecating mysql_ functions, you should migrate to PDO instead.
Also, make sure since you're using the older mysql_ functions to sanitize your entries using mysql_real_escape_string
Also, your entries need to be quoted. Here's a redo of your query string:
$query = "INSERT INTO users (email, password) VALUES ('{$registerEmail}', '{$registerPassword}')";

Pushing a comment to my database on localhost

So, I'm trying to push a comment to my database (icposts, below), and I'm not getting any results. I can pull and display the comments I directly insert into the database table fine, but when I try to send a comment from the html form, it doesn't seem to work at all.
<?php
$connect=mysqli_connect("localhost","root","");
$database=mysqli_select_db("icposts");
$username=$_POST['poster'];
$title=$_POST['postTitle'];
$body=$_POST['postText'];
$date=$_POST['currentDate'];
$submit=$_POST['submit'];
if($submit)
{
$query=mysql_query("INSERT INTO 'posts'('id', 'username', 'title', 'body', 'date') VALUES ('','$username','$title','$body','$date')");
}
?>
Here's the form's html, for reference:
<form name="input" action="comments.php" method="POST">
Username: <input id = "poster" type="text" name="poster"value="Guest" /><br>
Tite: <input id = "postTitle" type="text" name="postTitle" /><br>
Comment: <br> <textarea id = "postText" name = "postText"rows="4" cols="50"></textarea>
<input id = "submit" name = "submit" type="submit" value="Submit" />
<input id = "currentDate" name = "currentDate" type = "hidden" value = "" />
</form>
I've been looking at various examples, and I don't see anything wrong with what I've got there, when I compare it to what other people have posted online.
First, you need to pass connection to $database=mysqli_select_db("icposts");.
Then you're starting to mix MySQL APIs with mysql_query. They just don't intermix.
$database=mysqli_select_db($connect,"icposts");
then you're using the wrong identifiers for your table and columns, being quotes.
Either use ticks, or remove them (quotes) and also pass connection to the query:
$query=mysqli_query($connect,"INSERT INTO `posts` (`id`, `username`, `title`, `body`, `date`)
VALUES ('','$username','$title','$body','$date')");
Also add or die(mysqli_error($connection)) to mysqli_query() to check for DB errors, which is the reason why you are not getting errors; you're not checking for them. Error reporting is another you should look into.
Example:
if (!mysqli_query($connection,"INSERT INTO `posts` (`id`, `username`, `title`, `body`, `date`)
VALUES ('','$username','$title','$body','$date')");
)
{
echo("Error description: " . mysqli_error($connection));
}
else{
echo "Success!";
}
You can also use all 4 parameters instead:
$connect=mysqli_connect("localhost", "root", "", "icposts");
You may also want to replace if($submit) with
if(isset($_POST['submit']))
You can then get rid of $submit=$_POST['submit'];. It's best to use isset().
Nota: You will need to make sure that your currentDate column allows for blank data, otherwise you will need to give it some form of value.
Another note about the "id" column. If it is an auto_increment, you can just omit it from the query.
The database will increase on its own.
Sidenote:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
In the meantime till you get into using prepared statements, change your code using:
$username = stripslashes($_POST['poster']);
$username = mysqli_real_escape_string($connection, $_POST['poster']);
and do the same for all your variables.
Here is a prepared statements primer:
<?php
$link = new mysqli('localhost', 'root', '', 'database');
if ($link->connect_errno) {
throw new Exception($link->connect_error, $link->connect_errno);
}
// Check that the expected value has been provided via a POST request
if (!isset($_POST['input1'])) {
throw new Exception('Missing POST request parameter [input1]');
}
// now prepare an INSERT statement
if (!$stmt = $link->prepare('INSERT INTO `your_table` (`name`) VALUES (?)')) {
throw new Exception($link->error, $link->errno);
}
// bind parameters
$stmt->bind_param('s', $_POST['input1']);
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
$connect=mysqli_connect("localhost","root","");
Should be (the select db can simply be removed)
$connect=mysqli_connect("localhost","root","", "icposts");
And
$query=mysql_query("INSERT INTO 'posts'('id', 'username', 'title', 'body', 'date') VALUES ('','$username','$title','$body','$date')");
Should be
$query=mysqli_query("INSERT INTO 'posts'('id', 'username', 'title', 'body', 'date') VALUES ('','$username','$title','$body','$date')", $database);
Please do keep in mind that this is a really bad aprouch, also looking at your query it seems like the id is an auto incremented column. If that's the case, you don't even have to write it in the query itself.
You might wanna look further into Parameterizing queries.
This is a nice post for that.
How can I prevent SQL injection in PHP?

PDO Insert Into DB

I've seen so many tutorials with so many different ways to insert using PDO. None of them seem to work for me. Can't seem to get mine to send to the database. I have no issue connecting and retreiving the data using FETCH but can't seem to post this data.
Any help with getting my post to work and redirect using the header or meta refresh would be nice. I am $_POST from an html form. Connecting to the db works just fine but can't get the data in.
$hostdb = 'myremoteip';
$namedb = 'cpdemo';
$userdb = 'root';
$passdb = 'mypassword';
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
if(isset($_POST['fname'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$title = $_POST['title'];
$photo = $_POST['photo'];
$stmt = "INSERT INTO row_users (fname,lname,title,photo)
VALUES (:first,:last,:title,:photo)";
$q = $conn->prepare($stmt);
$results = $q->execute(array(
":first"=>$fname,
":last"=>$lname,
":title"=>$title,
":photo"=>$photo
));
echo 'User Added<br/>';
}
header ('Location:../insertUser.html');
exit();
What you have to understand that there is no such thing like "PDO Insert Into DB"
There is INSERT query, irrelevant to PDO but regular to database you are using.
And there is PDO prepared statement, irrelevant to query type. You have to follow exactly the same pattern, no matter if it insert or delete.
So - all you need is just a tutorial on PDO prepared statements. That's all. Preferably one that teach you to enable error reporting in the first place.
As requested by OP, comment leading to an answer (to close the question and marked as solved).
I tested your code "as is", and it worked fine.
The only thing I can tell that could be the issue is, that your insert won't happen unless it meets the conditional statement you've set if(isset($_POST['fname']))
Check to see if your HTML form's elements are indeed named?
I.e. <input type="text" name="fname"> etc. If one of those are not not named or has a typo, then your whole query will fail.
You can try binding parameter before passing it to execute, like for example in the below code
<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>

PHP PDO access to MySQL

I went through the process of converting mysql_* code into PDO code. I've run it and checked that it works and everything. I just want Stack Overflow's review of it, to make sure that I'm killing the connection properly, whether I should use some other method instead (e.g. transactions), making sure there are not massive security flaws. Here's the code:
<?php
try {
$link = new PDO('mysql:****;dbname=****;charset=UTF-8','****','****');
$link->exec("INSERT INTO Registration (`First Name`, `Last Name`) VALUES ('$_POST[fname]', '$_POST[lname]')");
} catch(PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Like I said, it works, but I want it to be safe and effective when 100 people register at the same time. Does everything look okay?
No .. you are converting mysql_ to PDO 1:1. This way, issues in mysql_ will also be a issue in PDO.
You should look at prepared queries and parameter binding.
Here is a example of what I mean:
$dbh = new PDO('mysql:****;dbname=****;charset=UTF-8','****','****');
$first = 'John';
$last = 'Doe';
$stmt = $dbh->prepare(
"INSERT INTO Registration (firstname, lastname) VALUES (:first, :last)");
$stmt->bindParam(':first', $first);
$stmt->bindParam(':last', $last);
$stmt->execute();
// insert another row with different values
$first = 'John';
$last = 'Smith';
$stmt->execute();

Inserting records into MySQL DB

Im using the follow script to insert records into my DB:
$sql = "INSERT INTO fotetweets VALUES('$tweetid','$dp', '', '$username','$tag', '$twittercontent', '$twittertimestamp', '')";
mysql_query($sql);
However what if $twittercontent contains the ' char, I think it will fail. Correct?
If so how can I deal with it correctly?
You will want to look into mysql_real_escape_string. However, I would look into using the mysqli or PDO class instead and utilize prepared statements.
EDIT
Note, these can all be found / were pretty much taken from the PHP Manual under examples for prepared statements.
Example Usage for MySQLi:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_database");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* create a prepared statement */
$stmt = $mysqli->stmt_init();
if ($stmt->prepare("INSERT INTO fotetweets VALUES(?, ?, '', ?, ?, ?, ?, '')")) {
/* bind parameters for markers */
$stmt->bind_param("issssi", $tweetid, $dp, $username, $tag, $twittercontent, $twittertimestamp);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
?>
Example Usage PDO:
<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sth = $dbh->prepare('INSERT INTO fotetweets VALUES(?, ?, '', ?, ?, ?, ?, '')');
$sth->execute(array($tweetid, $dp, $username, $tag, $twittercontent, $twittertimestamp));
?>
Example of mysql_real_escape_string usage:
$tweetid = (int) $tweetid; // static cast to integer, if that is what it should be.
$sql = "INSERT INTO fotetweets VALUES(
$tweetid,'" . mysql_real_escape_string($dp) . "',
'', '" . mysql_real_escape_string($username) . "',
'" . mysql_real_escape_string($tag) . "',
'" . mysql_real_escape_string($twittercontent) . "',
'" . mysql_real_escape_string($twittertimestamp) . "', '')";
You can find more information and extra usage examples at the manual pages listed above. Given I do know what $dp is I cannot tailor this exactly.
SIDE NOTE
This is all the assumption I am willing to make. The OP could be getting the data from POST and/or in an array form, or he could be getting it from a different means. Either or, given the example the OP posted, this is as accurate as I could be to tailor to the OP. If you have an issue or think it could be better explained / shown, well go ahead and add another answer which addresses it and not just another complaining comment remark about how no one does anything right when you are not willing to pony up the "correct" answer yourself.
And of course if it is an array, this changes a lot of items and the OP should clear that up and not just random people making "guesses" as to where and how the data is being retrieved.
Correct. Not only it will fail but it will also leave you open to SQL Injection attacks.
To avoid these problems, you can use:
mysql_real_escape_string()
PDO and Prepared Statements
Remember, user input should always be sanitized.
Just before you run this query, use this:
$twittercontent = mysql_real_escape_string($twittercontent);
yes it would fail as it would prematurely terminate the string. To fix this use
mysql_real_escape_string($twittercontent) in place of $twittercontent
Make your life simpler:
//$pdo = new PDO("mysql:host=localhost;dbname=testdb", user, pass);
$pdo->prepare("INSERT INTO fotetweets VALUES (?,?,?,?,?,?,?,?)")
->execute( array($tweetid, $dp, '', $username, $tag, $twittercontent, $twittertimestamp, '') );
This sends the data correctly to the database, without security issues. Use it as template for all queries. (Note that you still have to apply htmlspecialchars() when outputting your database content again later...)
That's why you should use mysql_real_escape_string() function first
http://www.php.net/manual/en/function.mysql-real-escape-string.php
It is important, that you always escape (or in general sanitize) variables you interpolate into your queries that come from untrusted sources (i.e. not from you ;) ). Topic for you to Google for read about: 'SQL injection'
You can also use addslashes(). mysql_real_escape_string() is better though. I agree with using PDO.
As it was mentioned before me you can use mysql_real_escape_string
OR
if you use PDO you can also use binding and the you do not have to worry about escaping.
$stmt = $db->prepare("INSERT INTO fotetweets VALUES(:tweetid,:dp, '', :username,:tag, :twittercontent, :twittertimestamp, '')");
$stmt->bindParam(':tweetid', $tweetid);
$stmt->bindParam(':dp', $dp);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':tag', $tag);
$stmt->bindParam(':twittercontent', $twittercontent);
$stmt->bindParam(':twittertimestamp', $twittertimestamp);
$stmt->execute();
As it was mentioned above, you have to use mysql_real_escape_string()
note that you have to use this function not for the $twittercontent variable only,
but for the every field in the query
and not only for inserting and not only for this table.
and from "untrusted input".
But literally every variable you are going to put into query in quotes, should be processed with this function. No exceptions or conditions.
Note if you don't put variable in quotes in the query, this function become useless
Another way, already mentioned too, is to change entire database driver.
Unfortunately, noone bring a useful example of real life usage, which could be extremely useful.

Categories