Update Oracle CLOB with PHP - php

I have an Oracle table with 1 field of datatype CLOB.
I want to replace the contents of the CLOB with a long string (over 4,000 characters).
Is OCI8 the easiest way to do this using PHP?
Regular sql would be simply something like this:
Update TableX
Set clobFieldX = 'my very long string'
Where keyField = 'value';
I've been googling for a simple example but can't find one that updates the CLOB with a 'where something = something' clause.
http://php.net/manual/en/function.oci-new-descriptor.php has an example of an insert statement. I'll try it in a bit, but it is as simple as changing the insert example to an update example?
Side note: is OCI the best way to interact with Oracle with PHP? Is there is a friendlier library/extension?

This worked: function updateClob($groupId,$memberList,$conn) {
$sql = "UPDATE LP_GROUP SET MEMBER_EXPR_XML = EMPTY_CLOB() WHERE GROUP_ID = '$groupId' RETURNING MEMBER_EXPR_XML INTO :lob";
//echo $sql."\n";
$clob = OCINewDescriptor($conn, OCI_D_LOB);
$stmt = OCIParse($conn, $sql);
OCIBindByName($stmt, ':lob', &$clob, -1, OCI_B_CLOB);
OCIExecute($stmt,OCI_DEFAULT);
if($clob->save($memberList)){
OCICommit($conn);
echo $groupId." Updated"."\n";
}else{
echo $groupId." Problems: Couldn't upload Clob. This usually means the where condition had no match \n";
}
$clob->free();
OCIFreeStatement($stmt);
}

Related

Convert sql result (object) to string variable for future input into sql table (I do not want to echo the result)

I have read most of the questions here and read the php manual in regards to the problem of converting an sql result to a string, however none of them is working for me. The examples given I understand, however they are echoing the sql results, I do not want the result to be echoed, I just want it to be stored in a variable so I can immediately insert it into a next sql table.
This is my code:
$cnt_fips = mysqli_query($con, "SELECT cc_fips FROM location2 WHERE location_name = '$cnt'");
$row = mysqli_fetch_assoc($cnt_fips);
These are the codes I have used to convert to string but failed with
$myStr = !is_array($row) ? trim(addslashes($row)):'';
and
$myStr = (string)$row;
and
$myStr = print_r($row,true);
and also
$myStr = (string)$row;
And insert into the table below
$query2 = mysqli_query($con, "INSERT INTO location3 VALUES ('','$myStr')");
$row is always an array with column names as the keys, use:
$myStr = $row['cc_fips'];
Also, I'm pretty sure you can do that all in one insert with a sub-select (though maybe not if a row with $cnt doesn't exist). If so, maybe someone will post it.

php insert data from fetch array to other table on version 5.4

I have moved to IIS 8 in PHP 5.4. I am trying to collect data from a table and insert them to a different one, i know my code is correct, but seems to be not working, probably because of the php version, can anyone help me?
here's my code
$query = odbc_exec($conn, "SELECT * FROM member");
while($rows = odbc_fetch_array($query)) {
$querystring = "INSERT INTO oldusers (username, password, regdate) VALUES ('$rows['userid']', '$rows['passwd']', '$rows['registdate']')";
$query2 = odbc_exec($conn, $querystring);
odbc_free_result($query2);
//echo $rows['userid']." ".$rows['passwd']." ".$rows['registdate']."<br>";
}
thanks in advance.
instead trying to insert one by one record, better to insert like below:
INSERT INTO oldusers (username, password, regdate) SELECT userid,passwd,registdate FROM member
for more information :http://dev.mysql.com/doc/refman/5.5/en/insert-select.html
You're placing $rows['passwd'] inside of a double-quoted string. Instead you should do:
$str = "some sql $rows[passwd] rest of sql"; // notice the absence of single quotes
or:
$str = "some sql {$rows['passwd']} rest of sql";
or (I think this way is most readable):
$str = 'some sql' . $rows[passwd] . ' rest of sql';
If your column contains text you'll need to add surrounding single quotes where necessary.
Having said all that, you should instead use parameterized queries (if your database supports it) as it's safer (from SQL injection). If that's unavailable you will at the very least need to escape the data before concatenating it to the string.

How save binary data in SQL Server with PEAR

How do I do an insert into an SQL 'Image' field using the PEAR DB library and sql like this:
insert into MyTable (myBlob) values (BlobData)
where BlobData is obtained using file_get_contents and looks like this:
"BMN\x0\x0\x0\x0\x0\x0\x06\x0\x0\x0(\x0\x0\x0\x2\x0\x0\x0\x3\x0\x0\x0\x1\x0\x18\x0\x0\x0\x0\x0\x18\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0ÿÿÿÿÿÿ\x0\x0\x0\x0ÿÿÿÿ\x0\x0ÿÿÿÿÿÿ\x0\x0"
I get syntax errors, guessing I need to escape the data somehow. Php code:
$data = file_get_contents('c:\\temp\\test.bmp');
$sql = "insert into MyTable (myBlob) values ('".$data."'); //just using inline sql for now to get it working
$db->query($sql);
I found that using bin2hex and writing the binary data as a hex string works:
$FileDataBin = file_get_contents($myFile);
$FileDataHex = '0x'.bin2hex($FileDataBin);
$qry = 'update MyTable set SomeBinaryField = '.$FileDataHex.' where SomeOtherField=?';
$DB->query($qry, array('some data'));
Note the '0x' prefix and that there are no quotes around the data.

SQL Table not updating in PHP

I'm trying to create an update function in PHP but the records don't seem to be changing as per the update. I've created a JSON object to hold the values being passed over to this file and according to the Firebug Lite console I've running these values are outputted just fine so it's prob something wrong with the sql side. Can anyone spot a problem? I'd appreciate the help!
<?php
$var1 = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
$jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object
$name = $jsonObject->{'name'}; // Get name from object
$desc = $jsonObject->{'desc'}; // Get desc from object
$did = $jsonObject->{'did'};// Get id object
mysql_connect("localhost","root",""); // Conect to mysql, first parameter is location, second is mysql username and a third one is a mysql password
#mysql_select_db("findadeal") or die( "Unable to select database"); // Connect to database called test
$query = "UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}";
$add = mysql_query($query);
$num = mysql_num_rows($add);
if($num != 0) {
echo "true";
} else {
echo "false";
}
?>
I believe you are misusing the curly braces. The single quote should go on the outside of them.:
"UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}"
Becomes
"UPDATE deal SET dname = '{$name}', desc='{$desc}' WHERE dealid = '{$did}'"
On a side note, using any mysql_* functions isn't really good security-wise. I would recommend looking into php's mysqli or pdo extensions.
You need to escape reserved words in MySQL like desc with backticks
UPDATE deal
SET dname = {'$name'}, `desc`= {'$desc'} ....
^----^--------------------------here
you need to use mysql_affected_rows() after update not mysql_num_rows

How to make an SQL query using variable column names?

I am making a query like this:
$b1 = $_REQUEST['code'].'A'; //letter 'A' is concatenated to $_REQUEST['code']
$a = $_REQUEST['num'];
echo $b1.$a;
$sql = "SELECT '".$b1."' FROM student_record1 WHERE id=".$a;
$result = mysql_query($sql);
if(!$result)
{
echo '<p id="signup">Something went wrong.</p>';
}
else
{
$str = $row[0]
echo $str;
}
Here $b1 and $a are getting values from another page. The 'echo' in the third line is giving a correct result. And I am not getting any error in SQL. Instead, I am not getting any result from the SQL query. I mean echo at the last line.
Don't do this, it breaks your relational model and is unsafe.
Instead of having a table with columns ID, columnA, columnB, columnC, columnD, columnE and having the user select A/B/C/D/E which then picks the column, have a table with three columns ID, TYPE, column and have TYPE be A/B/C/D/E. This also makes it easier to add F/G/H/I afterwards without modifying the table.
Secondly, with the extra column approach you don't have to build your SQL from input values like that. You can use prepared statements, and be safe from SQL Injection. Building SQL from unfiltered strings is wrong, and very dangerous. It will get your site hacked.
If you must use dynamic table/column/database names, you'll have to run them through a whitelist.
The following code will do:
$allowed_column = array('col1', 'col2');
$col = $_POST['col'];
if (in_array($col, $allowed_column)) {
$query = "SELECT `$col` FROM table1 ";
}
See: How to prevent SQL injection with dynamic tablenames?
For more details.

Categories