How save binary data in SQL Server with PEAR - php

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.

Related

Update Oracle CLOB with 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);
}

Database query not returning full string

I'm saving a json string in the database which appears to be stored correctly in SQL Server, however when trying to fetch the data it only returns part of the json string.
I'm using PDO and json_encode to save the data.
The json string stored is approximately 1000 characters long, and the table field allows a length of 4096.
Fetching result:
$sql = "SELECT TOP 1 * FROM MyTable WHERE id = :id ORDER BY id DESC;";
$params = array(
":id" => $id
);
$sth = $this->db->prepare($sql);
$sth->execute($params);
$result = $sth->fetch(PDO::FETCH_ASSOC);
Saving result:
$json = json_encode($_POST);
$sql = "INSERT INTO MyTable(data) VALUES (:data);";
$params = array(
":data" => $data
);
$stmt = $this->db->prepare($sql);
$stmt->execute($params);
Example Json stored in SQL Server:
{
"checkbox_1":"on",
"checkbox_2":"on",
"checkbox_3":"on",
"text_1":"my text",
"images":[
13685
],
"date":"11-11-2015"
}
Example Json returned:
{
"checkbox_1":"on",
"checkbox_2":"on",
"checkbox_3":"on",
"text_1
Update
It appears that the length of the string returned is always: 255
Could this be an SQL Server configuration or perhaps PDO?
Turns out that the protocol I was using to connect to SQL Server via PDO limits to 255 characters when fetching from a varchar column.
The workaround is to either change the column to TEXT or cast it to text in the SQL
SELECT CAST(my_column as TEXT)
ODBC query on MS SQL Server returning first 255 characters only in PHP PDO (FreeTDS)
Edit: Looks like OP's issue was something else, but I'll leave this below for future people that might have a similar issue, which can be solved by looking to TEXTSIZE.
Looks like the issue might be with the TEXTSIZE variable in SQL Server, which limits the length of returned text via PHP.
See what the current value is using
SELECT ##TEXTSIZE
and update it to a higher value using
SET TEXTSIZE 2147483647
Where the number is the max character count (defaults to/maxes out at the above value).
Here's the MSDN page on TEXTSIZE: https://msdn.microsoft.com/en-us/library/ms186238.aspx

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.

Creating a json array using concat with MySql

I'm creating a json array from MySql data using concat like this:
$id = '5705';
$sql = 'select concat("{""type:""colName"",""id"":""$id""}") as myJson from table where etc.;
$stmt = $conn->prepare($sql);
What's happening is, instead of getting data from colName from the table and the value of $id, I'm getting the result as it is in $sql. How do I break out of it and get colName and $id's value?
Current Result
{""type:""colName"",""id"":""$id""}
Desired Result
{""type:""novice"",""id"":""5705""}
//Here novice is data from colName, and 5705 is the value of $id
Please DON'T DO THAT. Trying to format data into JSON in your SQL will be fragile as encoding things into JSON is subtly more tricky that you would expect and you will inevitably get it wrong.
You should use the json_encode function in PHP. It will work reliably whereas your code will almost certainly break.
$dataArray = array();
while($statement->fetch()){
$data = array();
$data['type'] = $typeColumn;
$data['id'] = $id;
$dataArray[] = $data;
}
json_encode($dataArray, JSON_HEX_QUOT);
Also, formatting data to send to a client really shouldn't be part of an SQL query.
You need a better concatenation either in query and php
'select concat("{""type:"",colName,"",""id"":""'.$id.'""}")
Despite it is not really needed you could surround column name with backticks `
Your variables inside your string are not substituted with their values, as you got single quotes. Double quoted strings will expand variables with their values
Thus, you could invert your quotes, like this, in order to get the actual values of your variables:
$sql = "select concat('...')"

Wrong mysql query in php file?

I'm trying to insert some data into my mysql database. The connection is working fine but im having a problem with sending the query correctly to the database. Below you can find the code in my php file. I also post what for type of fields they are in the Database.
Fields in the mysql database:
Reservaties_id = int
Materialen_id = int
aantal = int
effectief_gebruikt = tinyint
opmerking = Varchar2
datum_van = date
datum_tot = date
$resID = $_REQUEST['resID'];
$materialen_id = $_REQUEST['materialen_id'];
$aantal = $_REQUEST['aantal'];
$effectief_gebruikt = $_REQUEST['effectief_gebruikt'];
$opmerking = $_REQUEST['opmerking'];
$datum_van = date('YYYY-MM-DD',$_REQUEST['datum_van']);
$datum_tot = date('YYYY-MM-DD',$_REQUEST['datum_tot']);
$string = "INSERT INTO `materialen_per_reservatie`(`reservaties_id`, `materialen_id`, `aantal`, `effectief_gebruikt`, `opmerking`, `datum_van`, `datum_tot`) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', $datum_van, $datum_tot)";
mysql_query($string);
you have to include single quotes for the date fields '$dataum_van'
$string = "INSERT INTO `materialen_per_reservatie`(reservaties_id, materialen_id, aantal, effectief_gebruikt, opmerking, datum_van, datum_tot) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', '$datum_van', '$datum_tot')";
and this is only a example query, while implementing don't forget to sanitize your inputs
Your code has some serious problems that you should fix. For one, it is not doing any error checking, so it's no surprise the query breaks silently when it fails. Check for errors and it will tell you what goes wrong - how to do it is outlined in the manual on mysql_query() or in this reference question.. Example:
$result = mysql_query($string);
// Bail out on error
if (!$result)
{
trigger_error("Database error: ".mysql_error(), E_USER_ERROR);
die();
}
In this specific case, I'm fairly sure it's because you are not putting your values into quotes after the VALUES keyword.
Also, the code you show is vulnerable to SQL injection. You need to escape every value you use like so:
$resID = mysql_real_escape_string($_REQUEST['resID']);
for this to work, you need to put every value in your query into quotes.
try this
$string = "INSERT INTO `materialen_per_reservatie`(`reservaties_id`) VALUES ('".$resID."')";

Categories