Inserting data in oracle DB using oci_8. Sample query to insert string with special characters or quotes
update TABLENAME set COMMENTS = 'As per Mark's email dated 28-Feb-2015 - Bill Gates & Team's effort' where ID = 99;
To insert/update
$query = 'update TABLENAME set COMMENTS = '$_POST[comments]';
$result = customexecute($new_query);
public function customexecute($query)
{
$resutlt = parent::customquery($query);
return $resutlt;
}
public static function customquery($query)
{
try{
$stmt = oci_parse($conn, $query);
oci_execute($stmt,OCI_COMMIT_ON_SUCCESS);
oci_commit(db_singleton::getInstance());
oci_free_statement($stmt);
}catch (Exception $e)
{
print_r($e);
}
}
Executing it on ORACLE DB it says SQl command not properly ended. Looked into Parameterized queries mentioned here but not able to integrate it succesfully.
$query = 'UPDATE tablename SET field = :field WHERE id = :id';
$stmt = oci_parse($oracleConnection, $query);
oci_bind_by_name($stmt, ':field', "The field value with 'apostrophes' and so");
oci_bind_by_name($stmt, ':id', '125');
$result = oci_execute($stmt);
I can pass :bind_comments in my query which is in my controller. But $stmt resides in my db_singleton file (general for all DB queries) and can not pass seperately for a individual query.
How can I sanitize user input or do not allow data to be used in creating SQL code
From the update function, pass everything needed to the execute function:
$result = customExecute(
'update xxx set comments=:COMMENTS where id=:ID',
[
':COMMENTS' => $_POST['comment'],
':ID' => 99
]
);
Then in the execute function simply iterate the array to bind all params:
public static function customExecute($sql, array $params = [])
{
$stmt = oci_parse($conn, $sql);
foreach ($params as $key => &$value) {
oci_bind_by_name($stmt, $key, $value);
}
$result = oci_execute($stmt);
...
}
No, unsurprisingly, MySQL functions won't work with Oracle DB :)
You need to parameterise things, e.g.:
$query = 'update TABLENAME set COMMENTS = :bind_comments where id = :bind_id';
$stmt = $dbh->prepare($query);
$stmt->bindParam(':bind_comments', $_POST['comments']);
$stmt->bindParam(':bind_id', $_POST['id']);
$stmt->execute();
The correct way of using the OCI8 PHP extensions is:
$query = 'UPDATE tablename SET field = :field WHERE id = :id';
$stmt = oci_parse($oracleConnection, $query);
oci_bind_by_name($stmt, ':field', "The field value with 'apostrophes' and so");
oci_bind_by_name($stmt, ':id', '125');
$result = oci_execute($stmt);
More information: http://php.net/manual/book.oci8.php
Related
I noticed that if you open a connection with PDO :: SQLSRV_ATTR_ENCODING = PDO :: SQLSRV_ENCODING_UTF8 (default configuration) there is a problem when using LIKE with named parameters on char fields.
No automatic trim of the padding spaces is performed, an operation that is performed in all other cases.
How to reproduce the problem:
Create a table and insert data in it:
CREATE TABLE testDB.dbo.TEST_TABLE (
ID_FIELD int IDENTITY(1,1) NOT NULL,
CHAR_FIELD char(15) COLLATE Latin1_General_CI_AS DEFAULT ' ' NOT NULL
CONSTRAINT TEST_TABLEK00 PRIMARY KEY (ID_FIELD)
);
INSERT INTO TEST_TABLE (CHAR_FIELD) VALUES ('Test data'), ('MyString'), ('My data 123');
Then on PHP I get this results
$options = array();
$pdo = new PDO("sqlsrv:Server=testServer;Database=testDB", 'test', 'test', $options);
$stmt = $pdo->prepare("SELECT * FROM TEST_TABLE WHERE CHAR_FIELD = 'Test data'");
$stmt->execute();
$results = $stmt->fetchAll(); //Returns 1 row
$stmt = $pdo->prepare("SELECT * FROM TEST_TABLE WHERE CHAR_FIELD LIKE 'Test data'");
$stmt->execute();
$results = $stmt->fetchAll(); //Returns 1 row
$stmt = $pdo->prepare("SELECT * FROM TEST_TABLE WHERE CHAR_FIELD = :CHAR_FIELD");
$value = 'Test data';
$stmt->bindParam('CHAR_FIELD', $value, PDO::PARAM_STR);
$stmt->execute();
$results = $stmt->fetchAll(); //Returns 1 row
$stmt = $pdo->prepare("SELECT * FROM TEST_TABLE WHERE CHAR_FIELD LIKE :CHAR_FIELD");
$value = 'Test data';
$stmt->bindParam('CHAR_FIELD', $value, PDO::PARAM_STR);
$stmt->execute();
$results = $stmt->fetchAll(); //Returns 0 rows
$stmt = $pdo->prepare("SELECT * FROM TEST_TABLE WHERE CHAR_FIELD LIKE :CHAR_FIELD");
$value = 'Test data ';
$stmt->bindParam('CHAR_FIELD', $value, PDO::PARAM_STR);
$stmt->execute();
$results = $stmt->fetchAll(); //Returns 1 row
$options = array(PDO::SQLSRV_ATTR_ENCODING => PDO::SQLSRV_ENCODING_SYSTEM);
$pdo = new PDO("sqlsrv:Server=testServer;Database=testDB", 'test', 'test', $options);
$stmt = $pdo->prepare("SELECT * FROM TEST_TABLE WHERE CHAR_FIELD LIKE :CHAR_FIELD");
$value = 'Test data';
$stmt->bindParam('CHAR_FIELD', $value, PDO::PARAM_STR);
$stmt->execute();
$results = $stmt->fetchAll(); //Returns 1 row
The behavior of the like together with the named parameter, when opening the connection to the DB in UTF8, is not uniform with all the other behaviors.
Only in that case is the field not automatically trimmed while in all other cases it is. Personally, it seems to me more of a bug than a deliberate behavior.
I find myself managing a huge application, developed over 10 years and which can interface with different databases (mysql, postgres, oracle and sqlserver).
Changing the queries one by one is impossible, I would need a solution at the configuration level (some flags to set in the PDO or on SqlSever itself) or at least find a way to normalize this behavior to all the others automatically via code.
This is the code that makes the error:
$sql = 'INSERT INTO pedidos (pagado, instalado) VALUES ("'.$_POST['email'].'", "'.$_POST['b'].'") WHERE email="'.$_POST['2'].'"';
$stm = $conn->prepare($sql);
$conn->exec($stm);
That's not the proper way to use prepare and execute. The reason this was created was so that you wouldn't need to put logic and data together and put yourself at risk of an SQL injection attack.
$sql = 'INSERT INTO pedidos (pagado, instalado) VALUES (:pagado, :instalado)';
$stm = $conn->prepare($sql);
$stm->bindParam(':pagado', $_POST['email']);
$stm->bindParam(':instalado', $_POST['b']);
$stm->execute();
It also doesn't make sense to put a WHERE in an INSERT query. You're inserting into your table, you're not getting data.
However, if you're updating data based on other data, then you should use an UPDATE query.
UPDATE pedidos SET pagado=?, instalado=? WHERE email=?
An example of this would be:
$sql = 'UPDATE pedidos SET pagado=:padago, instalado=:instalado WHERE email=:email';
$stm = $conn->prepare($sql);
$stm->bindParam(':pagado', $_POST['email']);
$stm->bindParam(':instalado', $_POST['b']);
$stm->bindParam(':email', $_POST['2']);
$stm->execute();
UPDATE - 2:
$sql = 'INSERT INTO pedidos SET pagado = ?, instalado = ? WHERE email = ?';
$stm = $conn->prepare($sql);
$stm->bindParam(1,$_POST['email']);
$stm->bindParam(2,$_POST['b'] );
$stm->bindParam(3,$_POST['2'] );
$stm->execute(); // here your code generate error
Reason: You put $stm in execute() , which makes an error.
I have two stored procedures in my database Postgres, both have the same name but the difference are the parameters.
procedure1(::string, ::integer, ::string, ::integer)
procedure1(::string, ::integer, ::integer)
In PDO doing bindParam correct, is coming STR, INT, INT but the prepere always performs procedure1.
How do I get him to understand what I call the procedure2?
Some information for more help? I clear? thanks
EDIT ===
...
$bounds = null; // forced for debug
if(!is_null($bounds)){
$query = "SELECT procedure1(:name, :domain, :geo, :userid)";
$stmt = $db->prepare($query);
$stmt->bindParam('name', $name, PDO::PARAM_STR);
$stmt->bindParam('domain', $idDomain, PDO::PARAM_INT);
$stmt->bindParam('geo', $geoString, PDO::PARAM_STR);
$stmt->bindParam('userid', $userId, PDO::PARAM_INT);
}else{
$query = "SELECT procedure1(:name, :domain, :userid)";
$stmt = $db->prepare($query);
$stmt->bindParam('name', $name, PDO::PARAM_STR);
$stmt->bindParam('domain', $idDomain, PDO::PARAM_INT);
$stmt->bindParam('userid', $userId, PDO::PARAM_INT);
}
$result = $stmt->execute();
...
The error it gives is that he is running a procedure that requires four parameters
Try changing your $query statements to explicitly tell PDO the types, and to avoid extra code switch to bindValue (PDO uses the PARAM flags to format SQL, not to cast data types):
$bounds = null; // forced for debug
if(!is_null($bounds)){
$query = "SELECT procedure1(:name::VARCHAR, :domain::INTEGER, :geo::VARCHAR, :userid::INTEGER)";
$stmt = $db->prepare($query);
$stmt->bindValue('name', $name);
$stmt->bindValue('domain', $idDomain);
$stmt->bindValue('geo', $geoString);
$stmt->bindValue('userid', $userId);
}else{
$query = "SELECT procedure1(:name::VARCHAR, :domain::INTEGER, :userid::INTEGER)";
$stmt = $db->prepare($query);
$stmt->bindValue('name', $name);
$stmt->bindValue('domain', $idDomain);
$stmt->bindValue('userid', $userId);
}
$result = $stmt->execute();
I have a connection to a database and want to update(override) an existing string called profile by a new one.
$uid = 1;
$serProfile = 'abc';
$sql = 'UPDATE
Users
SET
profile = ?
WHERE
id = ?';
$stmt = $db->prepare($sql);
if (!$stmt) { safeExit($db->error, 'msgError'); }
$stmt->bind_param('si', $serProfile, $uid);
if (!$stmt->execute()) { safeExit($stmt->error, 'msgError'); }
$stmt->close();
However, although the variables exist, the fields exist and there are no errors, the values in the database do not get changed. How to resolve this behaviour?
Test this one
$sql = 'UPDATE Users SET profile = :profile WHERE id = :id';
$stmt = $db->prepare($sql);
$stmt->execute(array('id'=>$uid,'profile'=>$serProfile));
I've tried following the PHP.net instructions for doing SELECT queries but I am not sure the best way to go about doing this.
I would like to use a parameterized SELECT query, if possible, to return the ID in a table where the name field matches the parameter. This should return one ID because it will be unique.
I would then like to use that ID for an INSERT into another table, so I will need to determine if it was successful or not.
I also read that you can prepare the queries for reuse but I wasn't sure how this helps.
You select data like this:
$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator
You insert in the same way:
$statement = $db->prepare("insert into some_other_table (some_id) values (:some_id)");
$statement->execute(array(':some_id' => $row['id']));
I recommend that you configure PDO to throw exceptions upon error. You would then get a PDOException if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $db object:
$db = new PDO("...");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I've been working with PDO lately and the answer above is completely right, but I just wanted to document that the following works as well.
$nametosearch = "Tobias";
$conn = new PDO("server", "username", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT `id` from `tablename` WHERE `name` = :name");
$sth->bindParam(':name', $nametosearch);
// Or sth->bindParam(':name', $_POST['namefromform']); depending on application
$sth->execute();
You can use the bindParam or bindValue methods to help prepare your statement.
It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name)); Especially if you are binding multiple values/variables.
Check the clear, easy to read example below:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
If you are expecting multiple rows remove the LIMIT 1 and change the fetch method into fetchAll:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetchAll(PDO::FETCH_ASSOC);
//$check will now hold an array of returned rows.
//let's say we need the second result, i.e. index of 1
$row_id = $check[1]['id'];
// do something
}
A litle bit complete answer is here with all ready for use:
$sql = "SELECT `username` FROM `users` WHERE `id` = :id";
$q = $dbh->prepare($sql);
$q->execute(array(':id' => "4"));
$done= $q->fetch();
echo $done[0];
Here $dbh is PDO db connecter, and based on id from table users we've get the username using fetch();
I hope this help someone, Enjoy!
Method 1:USE PDO query method
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Getting Row Count
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$row_count = $stmt->rowCount();
echo $row_count.' rows selected';
Method 2: Statements With Parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->execute(array($name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Method 3:Bind parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->bindValue(1, $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
**bind with named parameters**
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
or
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->execute(array(':name' => $name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Want to know more look at this link
if you are using inline coding in single page and not using oops than go with this full example, it will sure help
//connect to the db
$dbh = new PDO('mysql:host=localhost;dbname=mydb', dbuser, dbpw);
//build the query
$query="SELECT field1, field2
FROM ubertable
WHERE field1 > 6969";
//execute the query
$data = $dbh->query($query);
//convert result resource to array
$result = $data->fetchAll(PDO::FETCH_ASSOC);
//view the entire array (for testing)
print_r($result);
//display array elements
foreach($result as $output) {
echo output[field1] . " " . output[field1] . "<br />";
}