Cannot display image from DB2 in php pdo from blob format - php

we are working on HRM system where user profile pictures are displayed. We have a working Java version which take blob from db2 and after processing displays it. It works fine. Now we are trying to do the same stuff with php using pdo.
Here is the code we use to get the job done but it does not work.
BLOB is in format of
FFD8FFE000104A46494600010201012C012C0000FFE1129345786966000049492A000800000009000F01 ....
Code:
static function arr('SELECT * FROM TABLE WHERE ID_PERSON= 22')
{
global $conn;
$n = count($conn->query($sql)->fetchAll());
if ($n > 0) {
$q = $conn->query($sql);
if (!$q) {
$rs = $conn->errorInfo();
}
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
$rs[]=$row;
}
} else {
$rs = 'empty';
}
return $rs;
}
in page it is located as like this
<img src="data:image/jpeg;base64,<?=base64_encode(hex2bin($rs['IMAGE_COLUMN']))?>"
and it is view like this (almost similar like the java result but it is not and does not work).
src="data:image/jpeg;base64, /9j/4AAQSkZJRgABAgEBLAEsAAD/4RKTRXhpZgAASUkqAAgAAAAJAA8BAgAGAAAAegAAABABAgAWAAAAgAAAABIBAwABAAAAAQAAABoBBQABAAAAlgAAABsBBQABAAAAngAAACgBAwABAAAAAgAAADEBAgAbAAAApgAAADIBAgAHYCAACdggUAAQAAAH4CAAAiiAMAAQAAAAMAAAAniAMAAQAAAPQBAAAwiAMAAQAAAAIAAAAyiAQAAQAAAPQBAAAAkAcABAAAADAyMzADkAIAFAAAAIYCAAAEkAIAFAAAAJoCAAABkgoAAQAAAK4CA ....
We are might be wrong on hex2bin but it is taken advise from Stack Overflow and its result much more like the working one. and without it is is not looking like base64 at all.

Related

mysqli_query only returning results when there's a WHERE statement

MySQL query is only showing information if I have a condition in the SQL statement.
I've successfully used the SQL statement in phpmyadmin and it works great. I've changed the table name in the PHP code and it functions properly, the "people" table is the only one that causes a problem.
<?php
include 'dbconnectLocal.php';
$sql = "SELECT * FROM people WHERE nameFirst = 'Karen'";
$billings = array();
$billingResults = mysqli_query($connL, $sql);
while($row = mysqli_fetch_assoc($billingResults)){
$billings[] = $row;
}
mysqli_close($connL);
$jsonOutput = json_encode($billings);
print("<pre>".json_encode($billings, JSON_PRETTY_PRINT)."</pre>");
?>
The above code produces the desired result, it gives me a JSON result of everyone whos name is Karen. But if I were to change it to $sql = "SELECT * FROM people" I get a blank screen.
Json have 4 mb limitation. You can make a var_dump of $billings to check what you get from db
After much digging around and frustration, it turned out to be a json_encode error. Specifically a UTF8 problem. Found this solution on php.net. I ran the array through this function before encoding it and it worked perfect.
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}

Results of MySQL Query limited

I try to get a RESTApi with php ans MySQL running and I got pretty far. I'm more a Frontend guy so maybe you can help me figure this out. My code is this:
$sql = 'SELECT * FROM op_content';
$connection = new PDO(DB_CONN, DB_USERNAME, DB_PASSWORD);
$query = $connection->prepare($sql);
$query->execute();
$result = array();
if ($query->rowCount() > 0) {
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
$this->response($this->_toJson($result), 200);
} else {
$this->response('', 204);
}
private function _toJson($data) {
return is_array($data) ? json_encode($data) : '';
}
I dont get any results back from this, only if I add LIMIT 7 (Limit hast to be <= 7) to the SQL-Query. Are there any server-side limits (working on XAMPP atm) or where can that come from?
Edit:
Playing around a little bit I found out that I can return the results as XML (all of them), is there any reason this does not work with json?
OK, I finally figured it out. Since I'm from Germany we use umlauts, and altough I got back utf8, somehow it didnt really work, so I had to encode it first.

Display PHP code on web page

I am creating a library for PHP scripts and I want to be able to show php code on a html webpage.
I have looked at using highlight_file(); but this will show the whole page
For example, If I have a page called code.php which has an sql query on ( select code from table where sequence = $_GET["id"] ) - example then I use
Highlight_file('code.php?id=123');
This will work but will also show the select query which I do not want to show. I would just want to show the code from the database (code column)
How can I display just the code from the database with the correct colours and formatting etc
UPDATE:
<?php
$conn=mysql_connect("localhost","charlie_library","Pathfinder0287");
mysql_select_db("charlie_library",$conn);
function highlight_code_with_id($id, $conn)
{
$query = "select * from library_php where sequence = '$id' ";
$rs = mysql_query($query,$conn);
$code = mysql_fetch_array($rs);
echo highlight_string($code["code"]);
}
// and, use it like this:
highlight_code_with_id($_GET['id'], $conn);
?>
I have tried the above code, which is just displaying the code in plain text
use highlight_string function, like this:
<?php
highlight_string($code);
?>
where $code is the code you have obtained from your SQL query.
You can create a function around this (something along the following lines):
<?php
function highlight_code_with_id($id, $mysqli) {
$query = $mysqli->query("select code from table where sequence = '$id'");
$code = current($query->fetch_assoc());
return highlight_string($code);
}
// and, use it like this:
echo highlight_code_with_id($_GET['id'], $mysqli);
UPDATE:
Your code is a bit incorrect, you can use:
<?php
$conn=mysql_connect("localhost","charlie_library","Pathfinder0287");
mysql_select_db("charlie_library",$conn);
function highlight_code_with_id($id)
{
$query = "select * from library_php where sequence = '$id' ";
$rs = mysql_query($query);
$code = mysql_fetch_assoc($rs); // change is in this line
echo highlight_string($code["code"]);
}
// and, use it like this:
highlight_code_with_id($_GET['id']);
?>
Note that you do not need to include $conn in your function, it can be ommitted. Also, note that you should use mysqli->* family of functions, since mysql_* family has been deprecated.
Perhaps this would work for you.
This post is originally for HTML, but the answer linked above shows an example using PHP.

Executing Multiple MySQL Queries in a PHP/HTML Webpage: only first query runs

I have a webpage written in HTML. I have a dropdown list that is populated by a database utilizing a MySQL query:
<SELECT NAME = "Participant" STYLE = "WIDTH: 187" TITLE="Begin typing participant last name for fast searching." required>
<OPTION SELECTED VALUE = "">Select Participant...</OPTION>
<?PHP
$allParticipants = getall_participants();
foreach($allParticipants as &$value) {
$dt = date('Y-m-d');
$val = $value->get_id();
$optval = $dt.$val;
echo "<OPTION VALUE='",$optval,"'>";
echo $value->get_first_name()," ",$value->get_last_name();
echo "</OPTION>";
}
?>
</SELECT>
The getall_participants() looks like:
function getall_participants () {
connect();
$query = "SELECT * FROM dbParticipants ORDER BY last_name";
$result = mysql_query ($query);
$theParticipant = array();
while ($result_row = mysql_fetch_assoc($result)) {
$theParticipant = new Participant($result_row['last_name'],
$result_row['first_name'], $result_row['address']);
$theParticipants[] = $theParticipant;
}
mysql_close();
return $theParticipants;
}
And on this same page I have a textbox that is pre-filled-in by another database:
<?php
$dt = date('Y-m-d');
$participants = getall_dbParticipantEntry_byDate($dt);
foreach($participants as &$value) {
$a = $a.$value.", ";
}
echo "<INPUT TYPE='text' NAME='Participants' STYLE='WIDTH:50px;' TITLE='Participants' ";
echo "VALUE='[", $a.' ', "]'/>";
?>
That getall_dbParticipantEntry_byDate($date) looks like:
function getall_dbParticipantEntry_byDate($date) {
connect();
$query = 'SELECT * FROM dbParticipantEntry WHERE date = "'.$date.'"';
$result = mysql_query ($query);
$theParticipantEntry = array();
while ($result_row = mysql_fetch_assoc($result)) {
$theParticipantEntry = new ParticipantEntry($result_row['date'], $result_row['id'], $result_row['call_time'],
$result_row['result'], $result_row['notes']);
$theParticipantEntries[] = $theParticipantEntry->get_id();
}
mysql_close();
return $theParticipantEntries;
}
However, while both of these functions work fine individually, when they're both on the same webpage (like I meant them to be), only the one that comes first runs. I tested this by switching them in and out. They both complete their designated tasks, but only when alone on the page.
How can I get them both to run and populate their respective fields?
Thanks so much.
Try the following order:
Connect to mySQL server
Do task 1
Do task 2
Close Connection
For me it looks, like you have closed the mysqlconnection, before you do task2.
Edit:
Maybe you can do it like that?
function f1 ()
{
$res = mysql_connect(...);
// .. do some queries ..
mysql_query($sql, $res);
mysql_close($res )
}
function f2 ()
{
$res = mysql_connect(...);
// .. do some queries ..
mysql_query($sql, $res);
mysql_close($res )
}
Edit:
From php.net:
Be careful when using multiple links to connect to same database (with same username). Unless you specify explicitly in mysql_connect() to create a new link, it will return an already open link. If that would be closed by mysql_close(), it will also (obviously) close the other connection, since the link is the same.
Had lot of trouble figuring it out, since in <=4.3.6 there was a bug which didn't close the connection, but after the patch to >=4.3.7, all my application broke down because of a single script that did this.
You run them both on the same connection. You need to store the resource id returned from mysql_connect and pass this to each mysql method (each uses it's own relevant resource).
that said, I think it is time to:
Move to something more modern like Mysqli or PDO extensions. Much better API
Use some kind of abstraction on the connection managment, preferably one instance of a DB managment class per connection. Plenty of examples on the web, and it is way above the scope of this site to provide such instructions.

What is a good wrapper/framework/libraries for dealing with interface PHP applications to an SQL database?

I have a table
$query=
"CREATE TABLE screenshot ".
"(screenshot_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, ".
"source_video_id INT UNSIGNED NOT NULL, ".
"screenshot_file_name VARCHAR(128), ".
"x_res INT, ".
"y_res INT, ".
"time INT UNSIGNED);";
mysql_query($query);
Then I insert things into that table.
I often want to do an SQL query and iterate over the result of the query, but end up doing this.
//select all screenshots from video, by video id
$q0=
"SELECT * FROM screenshot ".
"WHERE source_video_id = '$source_video_id' ".
"AND x_res = 120 ".
"AND y_res = 90 ".
"ORDER BY time ASC;";
$r0 = mysql_query($q0);
$n0_num = mysql_numrows($r0);
//for each result
for($n0=0;$n0<$n0_num;$n0++) {
$source_video_id = mysql_result($r0,$n0,'source_video_id');
$time = mysql_result($r0,$n0,'time');
$screenshot_file_name = mysql_result($r0,$n0,'screenshot_file_name');
//do stuff for each returned result!
}
This is just ugly. To get the SQL query results, I have to write this for every column!
$source_video_id = mysql_result($r0,$n0,'source_video_id');
I have to write an ugly loop, get the results for each row returned and do something for each result. Basically I want something like;
foreach($SQL_command) {
//Do for each result
}
I want the column variables for each row to be already set, so that I do not have to do
$source_video_id = mysql_result($r0,$n0,'source_video_id');
For each and every column I want to access!
I am sick of writing boiler plate code to do this for every single table in my data. Are there any frameworks or libraries that would make this less painful?
These are the very basics of a database abstraction layer. It's not hard to program your own, or you can use a generic library like Doctrine or Propel. Every notable PHP framework includes some form of database abstraction as well, you really just need to start using one.
One can suppose I'm a fan of Kohana, but I really love the thing. Get the Kohana 3 and put there the Sprig ORM (it's a fork from original Sprig ORM, but with additional ‘sugar’ :) instead of native Kohana's one. You'll understand how pretty they are together. You'll can access to your tables like this code shows:
//just the basics, updating existing record
$screenshot = Sprig::factory('Screenshot', $id)->load();
$screenshot->x_res = 240;
$screenshot->y_res = 260;
$screenshot->update();
//creating new one
$screenshot = Sprig::factory('Screenshot');
$screenshot->x_res = 300;
$screenshot->y_res = 250;
$screenshot->create();
Additional link to the discussion of the Sprig fork: http://forum.kohanaframework.org/comments.php?DiscussionID=4368
Hope, it'll help you.
If you have the PDO drivers enabled (as you should) you can use the single DB() method as a function from the phunction PHP framework. It was inspired by the DiBi database abstraction layer. The documentation is still underway, but I've posted a short summary in this answer.
function DB($query)
{
static $db = null;
static $result = array();
if (is_null($db) === true)
{
if (preg_match('~^(?:mysql|pgsql):~', $query) > 0)
{
$db = new PDO(preg_replace('~^(mysql|pgsql):(?:/{2})?([-.\w]+)(?::(\d+))?/(\w+)/?$~', '$1:host=$2;port=$3;dbname=$4', $query), func_get_arg(1), func_get_arg(2));
if (preg_match('~^mysql:~', $query) > 0)
{
self::DB('SET time_zone = ?;', 'GMT');
self::DB('SET NAMES ? COLLATE ?;', 'utf8', 'utf8_unicode_ci');
}
}
else if (preg_match('~^(?:sqlite|firebird):~', $query) > 0)
{
$db = new PDO(preg_replace('~^(sqlite|firebird):(?:/{2})?(.+)$~', '$1:$2', $query));
}
}
else if (is_a($db, 'PDO') === true)
{
if (isset($query) === true)
{
$hash = md5($query);
if (empty($result[$hash]) === true)
{
$result[$hash] = $db->prepare($query);
}
if (is_a($result[$hash], 'PDOStatement') === true)
{
if ($result[$hash]->execute(array_slice(func_get_args(), 1)) === true)
{
if (preg_match('~^(?:INSERT|REPLACE)~i', $query) > 0)
{
return $db->lastInsertId();
}
else if (preg_match('~^(?:UPDATE|DELETE)~i', $query) > 0)
{
return $result[$hash]->rowCount();
}
else if (preg_match('~^(?:SELECT|EXPLAIN)~i', $query) > 0)
{
return $result[$hash]->fetchAll(PDO::FETCH_ASSOC);
}
return true;
}
}
return false;
}
}
return $db;
}
Your example query could be written as:
// connect to the MySQL server, do this on your config file or something
DB('mysql://host:port/database_name/', 'username', 'password');
// run the query!
$results = DB('SELECT * FROM screenshot WHERE source_video_id = ? AND x_res = ? AND y_res = ? ORDER BY time ASC;', $source_video_id, 120, 90);
foreach ($results as $result)
{
print_r($result);
}
The above code uses prepared queries which means that you'll also be safe from SQL injection attacks.
PS: I'm biased here, since I'm the developer of the framework. If you run into any problems let me know.
I use RedBean in all my projects and would recommend it without hesitation. The main reasons being:
Minimum configuration required. I don't have to map the database schema into a YAML or JSON file, simply put in the connection parameters and go.
Elegant and easy to understand usage syntax.
Lots of features such as caching and tree relationships.
Pretty good performance.
And here's an example of using it:
$book = R::dispense('book');
$book->title = 'Gifted Programmers';
$book->author = 'Charles Xavier';
$id = R::store($book);

Categories