Unicode message decode via MySQL - mysql

<?php
function unicodeMessageEncode($message){
return '#U' . strtoupper(bin2hex(mb_convert_encoding($message, 'UTF-16','UTF-8')));
}
function unicodeMessageDecode($message) {
$message = substr($message, 2);
$_message = hex2bin($message);
$message = mb_convert_encoding($_message, 'UTF-8', 'UTF-16');
return $message;
}
$message = "Testing Message 😀😁😬";
$encode_message = unicodeMessageEncode($message);
$decode_message = unicodeMessageDecode($encode_message);
echo $message;
echo "\n";
echo $encode_message;
echo "\n";
echo $decode_message;
echo "\n";
?>
I m using the above PHP code to encode and decode Unicode message, Could any know how can I decode Unicode message via MySQL query? (I don't want to run a loop of MySQL result).
For Example: Select id,somefunction(message) from table;

Related

Print data via GET https://api.groovehq.com/v1/tickets

I'm trying to get data trough a JSON API from Groove.
https://www.groovehq.com/docs/tickets#listing-tickets
and https://www.groovehq.com/docs
This is the code I made:
<?php
function timjson_front($atts, $content) {
global $wpdb;
$access_token = ""; //insert token
$user_email = ""; // insert customers email
$json = getJSON($access_token, $user_email);
$html = "";
foreach($json as $key => $waarde) {
$html .= $key . ' = ' . $waarde;
}
return html_entity_decode($html);
}
function getJSON($access_token, $user_email) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'https://api.groovehq.com/v1/tickets?acces_token=' . $access_token . '&customer=' . $user_email);
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
return $obj;
}
?>
The code runs on a wordpress page and is part of a self made plugin. The idea is that the tickets from a customer gets printed on a page.
Wordpress gives a error at foreach(). Does anyone know what i'm doing wrong? Or has some advice?
First
You're iterating on $obj but $obj = json_decode($result); will returns an object. You need to iterate through an array so use json_decode($result, true)
Second
Based on the API, the first key is tickets and has multiple tickets
So you want to start with tickets in the foreach:
foreach($json['tickets'] as $ticket){
foreach($ticket as $key => $waarde) {
$html .= $key . ' = ' . $waarde;
}
}
Third
You're concatenating strings with $html .= $key . ' = ' . $waarde;
But based on the API, the values are not ALWAYS strings.
foreach($json['tickets'] as $ticket){
foreach($ticket as $key => $waarde) {
if(!in_array($key, ['tags','links'])){ // ignore the keys "tags" and "links" because they are array
$html .= $key . ' = ' . $waarde;
}
}
}
Edit: POC https://3v4l.org/dblmj

Fatal error: Call to undefined function updateRows()

I got this error:
Fatal error: Call to undefined function updateRows()
but I have defined updateRows(), so what is wrong?
Here is my code:
<?php
if ($this->num_rows > 0) {
$i = 0;
while ($row = $stmt->fetchObject()) {
$appleIDS[$i] = array(
$row->id,
$row->pass,
$row->en_b_y,
$row->en_b_m,
$row->en_b_d,
$row->sqa1,
$row->sqa2,
$row->sqa3
);
$i++;
}
updateRows($this->pre_head, $head);
killTheConnection();
return $appleIDS;
}
killTheConnection();
return $check;
}
function updateRows($pre_head, $head) // here is my function
{
$this->mysqli_connet();
try {
$sql = "UPDATE appleid " . "SET taken = 'yes'" . "," . "taken_time=now()" . "WHERE num>=$pre_head AND num<=$head;";
$stmt = $GLOBALS['$connection']->prepare($sql);
$stmt->execute();
echo $stmt->rowCount();
}
catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
killTheConnection();
}
?>

How to retrieve composite column from Cassandra table in PHP

I have a CassandraHandler that retrieves the queries in rows
class CassandraHandler
{
private $keyspace = 'blabla'; //default is oyvent
private $cluster = NULL;
private $session = NULL;
function __construct(){
$this->cluster = \Cassandra::cluster()
->build(); // connects to localhost by default
$this->session = $this->cluster->connect($this->keyspace);
}
/**
* #return Rows
*/
public function execute($query){
$statement = new \Cassandra\SimpleStatement($query);
$result = $this->session->execute($statement);
return $result;
}
}
When I use for normal columns it's fine but I can't get my photo column in php
I created the column like this
photos frozen<set<map<text,text>>>
my json example
{{"urllarge": "1.jpg", "urlmedium": "2.jpg"},
{"urllarge": "3.jpg", "urlmedium": "4.jpg"}}
And here how can I use PHP to retrieve the composite columns?
$cassandraHandler = new CassandraHandlerClass();
$rows = $cassandraHandler->fetchLatestPosts($placeids, $limit);
foreach ($rows as $row) {
$tmp = array();
$tmp["userid"] = doubleval($row["userid"]);
$tmp["fullname"] = $row["fullname"];
$tmp["photos"] = $row["photos"] //????????
}
I know there is this documentation of the PHP driver https://github.com/datastax/php-driver
But I am a little confused.. I just need to get the json value like I get in cqlsh
You have two options to convert the composites into useable JSON:
Create a function to convert the deserialized/unmarshalled objects into JSON.
Retrieve the values from Cassandra as JSON.
Here is an example that demonstrates both options:
<?php
$KEYSPACE_NAME = "stackoverflow";
$TABLE_NAME = "retrieve_composites";
function print_rows_as_json($rows) {
foreach ($rows as $row) {
$set_count = 0;
echo "{\"photos\": [";
foreach ($photos = $row["photos"] as $photo) {
$map_count = 0;
echo "{";
foreach ($photo as $key => $value) {
echo "\"{$key}\": \"{$value}\"";
if (++$map_count < count($photo)) {
echo ", ";
}
}
echo "}";
if (++$set_count < count($photos)) {
echo ", ";
}
}
echo "]}" . PHP_EOL;
}
}
// Override default localhost contact point
$contact_points = "127.0.0.1";
if (php_sapi_name() == "cli") {
if (count($_SERVER['argv']) > 1) {
$contact_points = $_SERVER['argv'][1];
}
}
// Connect to the cluster
$cluster = Cassandra::cluster()
->withContactPoints($contact_points)
->build();
$session = $cluster->connect();
// Create the keypspace (drop if exists) and table
$session->execute("DROP KEYSPACE IF EXISTS {$KEYSPACE_NAME}");
$session->execute("CREATE KEYSPACE {$KEYSPACE_NAME} WITH replication = "
. "{ 'class': 'SimpleStrategy', 'replication_factor': 1 }"
);
$session->execute("CREATE TABLE ${KEYSPACE_NAME}.{$TABLE_NAME} ( "
. "id int PRIMARY KEY, "
. "photos frozen<set<map<text, text>>> )"
);
// Create a multiple rows to retrieve
$session->execute("INSERT INTO ${KEYSPACE_NAME}.{$TABLE_NAME} (id, photos) VALUES ( "
. "1, "
. "{{'urllage': '1.jpg', 'urlmedium': '2.jpg'}, "
. "{'urllage': '3.jpg', 'urlmedium': '4.jpg'}}"
. ")");
$session->execute("INSERT INTO ${KEYSPACE_NAME}.{$TABLE_NAME} (id, photos) VALUES ( "
. "2, "
. "{{'urllage': '21.jpg', 'urlmedium': '22.jpg'}, "
. "{'urllage': '23.jpg', 'urlmedium': '24.jpg'}}"
. ")");
// Select and print the unmarshalled data as JSON
$rows = $session->execute("SELECT photos FROM ${KEYSPACE_NAME}.{$TABLE_NAME}");
print_rows_as_json($rows);
// Select the data as JSON and print the string
$rows = $session->execute("SELECT JSON photos FROM ${KEYSPACE_NAME}.{$TABLE_NAME}");
foreach ($rows as $row) {
echo $row["[json]"] . PHP_EOL;
}
From the above example you can see that selecting the data as JSON involves less code for your application while also moving the processing onto the server. This probably the preferred choice for your application needs.
NOTE: This example is using v1.3.0 of the DataStax PHP driver which added support to pass a query strings directly to Session::execute() and Session::executeAsync(). If you are using an earlier version you will need to convert all query strings to Cassandra\Statement objects before passing to $session->execute(...).

change MySQL to PDO

I have to change an old mysql to PDO, I am working with a code its made by someone else, so I have this following code to change in PDO
The original code is
function liste($a,$b,$c)
{
$queryliste= "SELECT id,nom,prenom
FROM table";
$this->list = Connection_Base($querylistactu);
}
//Connection_Base
function Connection_Base($query)
{
$link = mysql_connect(DATABASESERVER, DATABASEUSER, DATABASEPASSWORD);
$ret = mysql_select_db(DATABASEDB, $link);
if (!$ret)
{
die("Echec de connection");
} else {
$mysql_desc = DATABASEDB;
if(!$result = mysql_query( $query))
{
return 0;
} else {
return $result;
}
mysql_close($link);
}
}
This is the part with which I have problem. I want to change it using PDO.
while( list($x,$y,$z) = mysql_fetch_row($lactu->list) )
I am proceed like this but it doesn't work
while( list($x,$y,$z) = $lactu->list->fetch(PDO::FETCH_NUM)
any ideas ?
Why don't you use PDO::FETCH_ASSOC? Check the code sample for connecting to database, executing the query, fetching all rows and iterate over the rows.
//Your query
$queryliste = "SELECT id, nom, prenom FROM table";
//Initialize pdo connection use your $name, $host, $username and $password
$pdoLink = new PDO("mysql:dbname={$name};host={$host};charset=utf8", $username, $password);
//Prepare statement
$statement = $pdoLink-> prepare($queryliste);
//Execute query
$statement -> execute();
//(1) Fetch rows using PDO::FETCH_ASSOC
$rows = $statement -> fetchAll(PDO::FETCH_ASSOC);
$statement -> closeCursor();
foreach($rows as $row) {
echo $row['id'];
echo $row['nom'];
echo $row['prenom'];
}
//(2) or you can use PDO::FETCH_NUM
$rows = $statement -> fetchAll(PDO::FETCH_NUM);
$statement -> closeCursor();
foreach($rows as list($x, $y, $z)) {
echo $x;
echo $y;
echo $z;
}
//(3) or you can rewrite the last in the same form you are using as
while((list($x, $y, $z) = $statement->fetch(PDO::FETCH_NUM))) {
echo $x;
echo $y;
echo $z;
}
$statement -> closeCursor();

Live Search With Mysql and PHP

I am building a Live Search function on my website, I used the W3schools example, which worked perfectly. But I want to use MySQL database instead of the XML file, so I am working on a code to take the MySQL database and turn it into an XML file.
<?php
header("Content-type: text/xml");
include 'dbc.php';
$query = "SELECT * FROM airports";
$result = mysql_query($query, $link)
or die('Error querying database.');
$xml_output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
$xml_output .= "<entries>\n";
for($x = 0 ; $x < mysql_num_rows($result) ; $x++){
$row = mysql_fetch_assoc($result);
$xml_output .= "\t<entry>\n";
$xml_output .= "\t\t<ident>" . $row['ident'] . "</ident>\n";
// Escaping illegal characters
$row['name'] = str_replace("&", "&", $row['name']);
$row['name'] = str_replace("<", "<", $row['name']);
$row['name'] = str_replace(">", ">", $row['name']);
$row['name'] = str_replace("\"", """, $row['name']);
$xml_output .= "\t\t<name>" . $row['name'] . "</name>\n";
$xml_output .= "\t</entry>\n";
}
$xml_output .= "</entries>";
echo $xml_output;
?>
I am getting this error:
Warning: DOMDocument::load() [domdocument.load]: Start tag expected, '<' not found in /public_html/sql2xml.php, line: 11 in /public_html/livesearch.php on line 12
no suggestion
I have read the explanation at: Avoid DOMDocument XML warnings in php
But I have no idea how to fix that in my code. Any suggestions?
This will take the data from the 'Name' column in your mysql table and put it into an array its the same array w3c school looks up as you type
$mysqli = new mysqli(HOST,USER,PASSWORD,DATABASE);
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM table";
$result = $mysqli->query($query);
while($row = $result->fetch_array())
{
$a[]=$row["Name"];
}
/* free result set */
$result->free();
/* close connection */
$mysqli->close();
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
if (isset($q))
{
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
}