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().
Related
I want to insert data into CLOUD and IDC tables.
Cloudid is the foreign key of IDC table, so i want to use transaction.
Before $conn->beginTransaction(); and $conn->commit(); are added ,it works fine, but without them, it works fine.
Here is my code:
<?php
if($_GET["act"]=="add")
{
try
{
$conn=new PDO('mysql:host=localhost;port=3306;dbname=xxx' , 'root' , 'xxxx');
//$conn->beginTransaction();
$query="
insert into CLOUD (name,date) VALUES('".$_POST['customerName']."','".$_POST['firstDay']."');
insert into IDC (name,id,phone,cloudid) VALUES('".$_POST['engName3']."','".$_POST['engID3']."','".$_POST['engPhone3']."',LAST_INSERT_ID());
insert into IDC (name,id,phone,cloudid) VALUES('".$_POST['engName4']."','".$_POST['engID4']."','".$_POST['engPhone4']."',LAST_INSERT_ID());
";
$stmt=$conn->query($query);
//$conn->commit();
echo "success";
}
catch(PDOException $e)
{
$conn->rollBack();
echo "connect failed!".$e->getMesage();
exit;
}
}
?>
Transactions are only available when the database uses InnoDB as the storage engine. You are probably using MyISAM
Have a look here for more details on the difference between the storage engines https://dev.mysql.com/doc/refman/5.7/en/storage-engines.html
As a side note, your code is vulnerable to SQL injections because you use raw post data in non prepared queries. you should have a look there : How can I prevent SQL injection in PHP?
Try to initiate your connection and get last inserted id like below, also i would recommend you to use prepared statements (see http://php.net/manual/ru/pdo.prepare.php):
if($_GET["act"]=="add")
{
try {
$dbh = new PDO('mysql:host=localhost;port=3306;dbname=xxx', 'root', 'xxx',
array(PDO::ATTR_PERSISTENT => true));
echo "Connected\n";
} catch (Exception $e) {
die("Unable to connect: " . $e->getMessage());
}
try {
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->beginTransaction();
$stmt = $dbh->prepare('insert into CLOUD (name,date) VALUES(:customerName,:firstDay)');
$stmt->execute([
'customerName' => $_POST['customerName'],
'firstDay' => $_POST['firstDay']
]);
$cloud_id = $dbh->lastInsertId();
$stmt = $dbh->prepare('insert into IDC (name,id,phone,cloudid) VALUES(:name,:id,:phone,:cloudid)');
$stmt->bindParam(':name', $name);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':phone', $phone);
$stmt->bindParam(':cloudid', $cloud_id);
$name = $_POST['engName3'];
$id = $_POST['engID3'];
$phone = $_POST['engPhone3'];
$stmt->execute();
$name = $_POST['engName4'];
$id = $_POST['engID4'];
$phone = $_POST['engPhone4'];
$stmt->execute();
$dbh->commit();
} catch (PDOException $e) {
$dbh->rollBack();
echo "Failed: " . $e->getMessage();
}
}
I've been working on an iOS web service using PHP, but I'm not having very much luck. I'm attempting to safely query the database and select the id of the user when the name and password match. Unfortunatly, nothing is showing up on the page. I would assume that means the query went wrong somewhere. I've attempted using static values, but to no avail. Any ideas?
P.S. I'm positive the values are correct.
P.P.S. Yes, I know, encrypt. For the simplicity, I'm not bothering.
error_reporting(E_ALL);
ini_set('display errors', 1);
try {
$DBH = new PDO("mysql:host='localhost';dbname='login_test'", 'test', 'development');
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo e->getMessage();
}
$data = array($_GET['name'], $_GET['password']);
$STH = $DBH->prepare('SELECT id FROM users WHERE name = ? AND password = ?');
$STH->execute($data);
$row = $STH->fetch(PDO::FETCH_ASSOC);
print '<pre>';
print_r($row);
Try it ,
try {
$DBH = new PDO("mysql:host='localhost';dbname='login_test'", 'test', 'development');
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo /*here*/ $e->getMessage();
}
$data = array($_GET['name'], $_GET['password']);
$STH = $DBH->prepare('SELECT id FROM users WHERE name = ? AND password = ?');
$STH->execute($data);
$row =$STH->fetch(PDO::FETCH_ASSOC)
print '<pre>';
print_r($row);
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])");
}
I'm using PDO for my querys and try to escape some '&' since they make the request invalid. I already tried with mysql_real_escape_string and pdo quote... both didn't escaped the '&'. My values are for example "James & Jack".
As Connector:
$this->connect = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_pass,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
As Query:
function check_exist($query,$parameter)
{
try
{
$this->connect->prepare($query);
$this->connect->bindParam(':parameter', $parameter, PDO::PARAM_STR);
$this->connect->execute();
return $this->connect->fetchColumn();
unset ($query);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
Finaly the Call to action
$db = new database;
$db->connect('framework','localhost','root','');
$result = $db->check_exist('SELECT COUNT(*) FROM cat_merge WHERE cat=:parameter',$cat);
Try using prepared statements this way:
<?php
// Connect to the database
$db = new PDO('mysql:host=127.0.0.1;dbname=DB_NAME_HERE', 'username', 'password');
// Don't emulate prepared statements, use the real ones
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// Prepare the query
$query = $db->prepare('SELECT * FROM foo WHERE id = ?');
// Execute the query
$query->execute($_GET['id']);
// Get the result as an associative array
$result = $query->fetchAll(PDO::FETCH_ASSOC);
// Output the result
print_r($result);
?>
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.