Using PDO to CRUD with SQLITE3. When I insert a string 'didn't', the string goes into the table as 'didn\'t'.
So, later when I read the string back out, to ouput to HTML, I get didn\'t in my web page.
So, if PDO is escaping the single quote on the INSERT with the backslash, how do I strip out the escaping backslashes for presentation?
Does that make sense?
EDIT - Including code. $eventBody is the string in question.
try {
$db = new PDO('sqlite:../posts.sqlite');
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e)
{
echo $e->getMessage();
die;
}
//using the sqlite functions to do date/time stuff
$query = 'INSERT INTO posts (eDay, eMonth, eYear, eTitle, eBody,author, eURL, eTime)
VALUES( strftime(\'%d\',\'now\') , strftime(\'%m\',\'now\') , strftime(\'%Y\',\'now\') ,"'. $eventTitle .'","'.$eventBody.'","' . $eventAuthor. '","' . $eventURL . '",time(\'now\',\'localtime\'));' ;
try
{
$result=$db->query($query);
if(!($result))
{
echo "INSERT FAILED.<br>";
echo "QUERY STRING: ".$query ." <br>";
die;
}
echo "Successfully Added Record";
$eventTitle = '';
$eventBody='';
$eventURL='';
$eventAuthor='';
// urlRedirect("Referback.php");
}
catch (PDOException $ex)
{
echo $ex->getMessage();
die;
}
catch (Exception $exc)
{
echo $exc->getMessage();
die;
}
}
PDO works the way it should, you should check how you do your insert (build the queries) and the data source (meaning what's coming from $_POST/$_GET).
And specially the magic quotes gpc. If you don't know what it is, check it out. It's a very recurrent problem. Before you start using stripslashes/addslashes and such.
You should also use the prepared statement, it's not only nicer, but a lot less work and safer.
$stmt = $db->prepare('INSERT INTO posts '.
'(eDay, eMonth, eYear, eTitle, eBody, author, eURL, eTime) '.
'VALUES (?, ?, ?, ?, ?, ?, ?, ?);');
$result = $stmt->execute(array(
date('d'),
date('m'),
date('Y'),
$eventTitle,
$eventBody,
$eventAuthor,
$eventURL,
time('now', 'localtime')
));
You could also print the data you give to ̀ execute` to make sure, it is what you want.
Related
I use this code to insert some data into my database.
I adapt my previous code based on mysqli to use PDO now.
For the 2 parameters name and id, do i need to escape them using a function like mysqli_real_escape_string with PDO ? or is it OK to pass these params direclty in the query ?
<?php
try
{
$pdo = new PDO('mysql:host='.$servername.';port='.$dbport.';dbname='.$dbname.'', $username, $decodedPwd);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$json = $_POST['jsonData'];
$id = $json["id"]
$name = $json["name"]
$pdo->beginTransaction();
// do request
$pdo->query('INSERT INTO test(id, name) VALUES ('$id', '$name')');
$pdo->commit();
echo 'Everything is OK';
}
catch(Exception $e)
{
$pdo->rollback();
echo 'An error occurred :<br />';
echo 'Error : '.$e->getMessage().'<br />';
echo 'N° : '.$e->getCode();
exit();
}
You need to prepare your statement, try this:
$query = $pdo->prepare('INSERT INTO test(id, name) VALUES (:theid, :thename)');
$query->execute(array(
'theid' => $id,
'thename' => $name
));
You don't have to escape strings but you have to use preared statements.
Here is what your code should be.
<?php
$pdo = new PDO('mysql:host='.$servername.';port='.$dbport.';dbname='.$dbname.'', $username, $decodedPwd);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$json = $_POST['jsonData'];
$pdo->prepare('INSERT INTO test(id, name) VALUES (:id,:name)')->execute($json);
echo 'Everything is OK';
note that a transaction is useless for just a single query and the way you are reporting errors is wrong.
also, if $json already contains the all the data for thequery, no need to store its contents in separate variables.
It's not okay. You need to use prepared statements or PDO::quote().
Trying to insert user input into a MYSQL database. I am utilizing the REPLACE INTO because the column email has a unique key to prevent duplication. The table name is launch_email. I am trying to prevent SQL injection by using prepare and bindParam, however I keep getting this error: Call to undefined function bindParam(). Any solutions?
PHP/SQL:
require(ROOT_PATH . "inc/database.php");
try {
$replace = $db->prepare("REPLACE INTO launch_email VALUES (:email_str)");
$replace = bindParam(":email_str", $email, PDO::PARAM_STR);
$replace->execute();
} catch (Exception $e) {
echo "Data could not be submitted to the database.";
exit;
}
EDIT: The code below solved my problem. I was assigning a method to a non-object.
require(ROOT_PATH . "inc/database.php");
try {
$replace = $db->prepare("REPLACE INTO launch_email VALUES (:email_str)");
$replace->bindParam(":email_str", $email, PDO::PARAM_STR);
$replace->execute();
} catch (Exception $e) {
echo "Data could not be submitted to the database.";
exit;
}
Remember bindParam is a method of the Classes PDO, MySQLi or whatever database you're using... So it must be called this way:
$replace->bindParam(":email_str", $email, PDO::PARAM_STR);
PDOStatement::bindParam is a PDOStatement method .
this should work
require(ROOT_PATH . "inc/database.php");
try {
$stm = $db->prepare("REPLACE INTO launch_email VALUES (:email_str)");
$stm->bindParam(":email_str", $email, PDO::PARAM_STR);
$stm->execute();
} catch (Exception $e) {
echo "Data could not be submitted to the database.";
exit;
}
bindParam is not a language function. It is a method of the PDOStatement object.
$replace->bindParam(":email_str", $email, PDO::PARAM_STR);
It would be better if instead of using $replace as your variable name, you call it something like $stmt so that it is more apparent what that object is.
Alternatively, you can pass your parameter at execution. By writing your code like this:
$stmt = $db->prepare("REPLACE INTO launch_email VALUES (?)");
if ($stmt)
{
// Execute query with parameter
$stmt->execute(array($email));
}
else
{
// Could not prepare statement
echo $db->errorInfo();
}
I have the following PHP code:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$insert_query = mysql_query("INSERT INTO articles(articleTitle, articleContent, typeID)
VALUES
('$_POST[articleTitle]','$_POST[articleContent]',$_POST[articleType])");
}
typeID => is number, the other values are text.
There is no error in this code, but the insert query doesn't work (I have no idea why because I don't get any error message).
How can I fix it?
There are a number of problems with your code.
It's open to SQL injectoion
mysql_* functions have been deprecated
This code is untested but should give you an idea:
try
$dbh = new PDO('mysql:host=localhost;dbname=your_database_name', $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $dbh->prepare('INSERT INTO Persons (articleTitle, articleContent, typeID) VALUES (:articleTitle, :articleContent, :articleType)');
$sth->execute($_POST);
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
}
Have a look at this article on Why you Should be using PHP’s PDO for Database Access
Try this
if(isset($_POST[articleTitle])) {
$insert_query = mysqli_query("INSERT INTO Persons (articleTitle, articleContent,typeID)
VALUES
('$_POST[articleTitle]','$_POST[articleContent]',$_POST[articleType])");
}
Hi I am inserting image data into a database each time an image is uploaded to my server. The code I am using looks a bit 'chunky' especially the binds. Can it be done differently to reduce the amount of text and execute more quickly or should I not worry about it?
Here is the code I am using:
function($file_name, $cat, $year, $desc, $title, $image_size, $image_width, $image_height){
//test the connection
try {
//connect to the database
$dbh = new PDO("mysql:host=localhost;dbname=mjbox","root", "usbw");
//if there is an error catch it here
} catch( PDOException $e ) {
//display the error
echo $e->getMessage();
}
$stmt = $dbh->prepare("INSERT INTO mjbox_images(img_file_name,img_cat,
img_year,img_desc,img_title,img_size,img_width,img_height)
VALUES(?,?,?,?,?,?,?,?)");
$stmt->bindParam(1,$file_name);
$stmt->bindParam(2,$cat);
$stmt->bindParam(3,$year);
$stmt->bindParam(4,$desc);
$stmt->bindParam(5,$title);
$stmt->bindParam(6,$image_size);
$stmt->bindParam(7,$image_width);
$stmt->bindParam(8,$image_height);
$stmt->execute();
}
Depending on how much code you want to rewrite, you could always swap from using pure PDO to something like RedBean (which is actually quite nice, being a zero-config ORM).
http://www.redbeanphp.com/
Worth a look, even if you won't use it now; it's definitely a great tool.
Inserts would then take just modifying bean properties, reducing the overall amount of code you'd use.
You could do it like this, passing an array of values and use the keys as place holders, that way you can use the same function to insert into different tables:
<?php
$insert = array('img_file_name'=>'',
'img_cat'=>'',
'img_year'=>'',
'img_desc'=>'',
'img_title'=>'',
'img_size'=>'',
'img_width'=>'',
'img_height'=>'');
insert('mjbox_images',$insert);
function insert($table,$values=array()){
//test the connection
try{
//connect to the database
$dbh = new PDO("mysql:host=localhost;dbname=mjbox","root", "usbw");
//if there is an error catch it here
} catch( PDOException $e ) {
//display the error
echo $e->getMessage();
}
$fieldnames = array_keys($values);
$sql = "INSERT INTO $table";
$fields = '( ' . implode(' ,', $fieldnames) . ' )';
$bound = '(:' . implode(', :', $fieldnames) . ' )';
$sql .= $fields.' VALUES '.$bound;
$stmt = $dbh->prepare($sql);
$stmt->execute($values);// whoops
}
//INSERT INTO mjbox_images( img_file_name ,img_cat ,img_year ,img_desc ,img_title ,img_size ,img_width ,img_height ) VALUES (:img_file_name, :img_cat, :img_year, :img_desc, :img_title, :img_size, :img_width, :img_height )
?>
I'm facing some doubts in PHP database connections. Since I can't just put a large try/catch/finally block on my method (Java style), what's the best approach to properly closing all connections and prepared statements when size/logic tends to increase? Considering the next method, is everything done right?
public function createRegister($register) {
$this->openConnection();
$query = "INSERT INTO register (username, password, email, confirmationToken) VALUES (?, ?, ?, ?)";
$result = $this->mysqli->query($query);
if ($statement = $this->mysqli->prepare($query)) {
$statement->bind_param("ssss", $register->username, $register->passwordHash, $register->email, $register->confirmationToken);
if (!$statement->execute()) {
$this->closeConnection();
throw new DAOException("Failed to execute statement: " . $statement->error);
}
$statement->close();
} else {
$this->closeConnection();
throw new DAOException("Failed to prepare statement: " . $this->mysqli->error);
}
$this->closeConnection();
}
You can still use try/catch in PHP:
public function createRegister($register) {
$this->openConnection();
$query = "INSERT INTO register (username, password, email, confirmationToken) VALUES (?, ?, ?, ?)";
try {
// This line is not needed
// $result = $this->mysqli->query($query);
if ($statement = $this->mysqli->prepare($query)) {
$statement->bind_param("ssss", $register->username, $register->passwordHash, $register->email, $register->confirmationToken);
if (!$statement->execute()) {
throw new DAOException("Failed to execute statement: " . $statement->error);
}
$statement->close();
} else {
throw new DAOException("Failed to prepare statement: " . $this->mysqli->error);
}
} catch (Exception $e) {
if ((isset($statement)) && (is_callable(array($statement, 'close')))) {
$statment->close();
}
$this->closeConnection();
throw $e;
}
$this->closeConnection();
}
This works well for establishing a connection for one specific task, but what if you want to share the same connection for multiple tasks that also need access to the same schema? You may want to consider a more advanced solution using a singleton/factory pattern for creating and access database connections. I posted such an example as a solution to another question. It is a bit more advanced but once you get your head around it, it is more performant.