Returning JSON from a PHP function - php

I want to transform this PHP function.. that should return JSON data.
<?php
$query = 'SELECT * FROM `' . mix_player::table() . '` a';
if (isset($_GET['cat']) || isset($_GET['order']))
if (isset($_GET['cat'])) {
$query .= ' INNER JOIN `' . mix_player::table_cat_rel() . '` b '
. "ON (a.`id` = b.`idtrack`) WHERE `idcat` = '" . $wpdb->escape($_GET['cat']) . "'";
$random = $wpdb->get_var('SELECT `random`, `order` FROM `' . mix_player::table_categories() . "` WHERE `id` = '"
. $wpdb->escape($_GET['cat']) . "'");
if (!$random)
$order = $wpdb->get_var(NULL, 1);
}
if (isset($_GET['order']))
$order = $_GET['order'];
if ($order != '') {
if (isset($_GET['cat']))
$query .= ' AND ';
else
$query .= ' WHERE ';
$tracks = mix_player::order_list($query, $order);
}
} else {
$random = '0';
}
$query .= ' ORDER BY `id` ASC';
if (isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A))) {
// option "shuffle = true" not always working into mix. Do it our own way...
if ($random == 1) { // shuffle tracks?
list($usec, $sec) = explode(' ', microtime());
mt_srand((float) $sec + ((float) $usec * 100000));
$nrows = count($tracks);
for ($i = 0; $i < $nrows; $i++) {
$j = mt_rand(0, $nrows - 1); // pick j at random
$row = $tracks[$i]; // swap i, j
$tracks[$i] = $tracks[$j];
$tracks[$j] = $row;
}
}
foreach ($tracks as $row) {
$artist = (mix_player::entities($row['artist']));
echo ($artist);
$title = (mix_player::entities($row['title']));
echo ($title);
$url =(xspf_player::entities($row['url']));
echo ($url);
}
}
?>
to display like this json file :
{"title":"title", "artist":"artist","media":"url media.mp3","color":"#56B0E8" },
Can you help me?
Thanks in advance.

You can simply create an array and populate it with your desired values, then return it as JSON:
function tracks2json( $tracks )
{
$retval = array();
foreach( $tracks as $row )
{
$array = array();
$array['artist'] = mix_player::entities($row['artist']);
$array['title'] = mix_player::entities($row['title']);
$array['media'] = 'url '.xspf_player::entities($row['url']);
$array['color'] = '#56B0E8';
$retval[] = $array;
}
return json_encode( $retval );
}
if( isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A)) )
{
// Your MySQL routine here
$json = tracks2json( $tracks );
}

echo json_encode(array("title"=>$title,"artist"=>$artist,"url"=>$url));

Related

Using loops by reading data from a database

I have a form with three fields that I want to read separately from the database
$_POST['wkNumer1'];
$_POST['wkNumer2'];
$_POST['wkNumer3'];
How can I read this data without repeating the same code 3 times? In this code, only the variable $wkNumer value will be change.
<?php
if (isset($_POST['show_diagram'])) {
$goodname = $_POST['htDriver'];
$wkNumer = $_POST['wkNumer1'];
// Table with data
$sql = "SELECT WorkingDay, OrderNo, NameFinish, Type FROM `status` where WEEK(WorkingDay) = :wknumer AND NameFinish = :nameFinish"; // SQL with parameters
$stmt = $conn->prepare($sql);
$stmt->bindParam("wknumer", $wkNumer);
$stmt->bindParam("nameFinish", $goodname);
$stmt->execute();
$OCSdatas = $stmt->fetchAll(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
$countWithoutE = 0;
$countE = 0;
foreach ($OCSdatas as $data) {
if ($data['Type'] != 'E') {
$countWithoutE = $countWithoutE + 1 ;
}
if ($data['Type'] == 'E') {
$countE = $countE + 1 ;
}
}
echo $goodname . '<br />';
echo $wkNumer . '<br />';
echo $countWithoutE . '<br>';
echo $countE . '<br>';
$countE = $countE/2;
$countTotal = $countWithoutE + $countE;
echo $countTotal/5 . '<br>';
echo $count/5;
}
?>
You can put the numbers inside an array and iterate through that array to execute the same code.
$goodname = $_POST['htDriver'];
// Add the numbers to an array which we can iterate
$numbers = [
$_POST['wkNumber1'],
$_POST['wkNumber2'],
$_POST['wkNumber3'],
];
// Prepare the statement only once before the loop and reuse it
$sql = "SELECT WorkingDay, OrderNo, NameFinish, Type FROM `status` where WEEK(WorkingDay) = :wknumer AND NameFinish = :nameFinish";
$stmt = $conn->prepare($sql);
// Loop through the numbers
foreach ($numbers as $number) {
// Add the current number
$stmt->bindParam("wknumer", $number);
$stmt->bindParam("nameFinish", $goodname);
$stmt->execute();
// Now have everything as you had before
$OCSdatas = $stmt->fetchAll(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
$countWithoutE = 0;
$countE = 0;
foreach ($OCSdatas as $data) {
if ($data['Type'] != 'E') {
$countWithoutE = $countWithoutE + 1 ;
}
if ($data['Type'] == 'E') {
$countE = $countE + 1 ;
}
}
echo $goodname . '<br />';
echo $wkNumer . '<br />';
echo $countWithoutE . '<br>';
echo $countE . '<br>';
$countE = $countE/2;
$countTotal = $countWithoutE + $countE;
echo $countTotal/5 . '<br>';
echo $count/5;
}
How does this work for you?
$workNumbers = array($_POST['wkNumer1'],$_POST['wkNumer2'],$_POST['wkNumer3']);
foreach($workNumbers as $wkNumer){
//Your Code block here
}

PHP Oracle inserting data on loop got incorrect id

I'm continuing my previous question.
Now I need to insert the value to DB. But ID inserted is not correct as on my database master.
$qModel = oci_parse($c1, "SELECT MODELID, MODEL_NAME FROM WA_LFO_TBL_MODEL
WHERE ACTIVE = 'Y'");
oci_execute($qModel);
while($dModel = oci_fetch_array($qModel))
{
$qDtl2 = oci_parse($c1, "SELECT * FROM WA_LFO_TBL_MODEL_CONFIGURATION WHERE MODELID_FK = '" . $dModel['MODELID'] . "'");
oci_execute($qDtl2);
while($dDtl2 = oci_fetch_array($qDtl2))
{
$q = oci_parse($c1, "SELECT * FROM WA_LFO_TBL_REJECT_PROCESS WHERE MODELID_FK = '" . $dModel['MODELID'] . "' ORDER BY SORT_NO ASC");
oci_execute($q);
while($d = oci_fetch_array($q))
{
$idkeys[] = $d['RP_ID'];
$keys[] = $d['RP_NAME'];
}
$values = array_fill(0, count($keys), 0);
$values = array_combine($keys, $values);
for($i = $readRowAfter; $i < count($linesReject); $i++)
{
// if the fileReject is "Tue, Sep 18<tab>2018<tab>23:59:53<tab>"
$dateobjReject = DateTime::createFromFormat($createFromFormat, $linesReject[$i]);
// check if date is in your Timespan
if($dateobjReject < $toDateTime && $dateobjReject > $fromDateTime)
{
$rowsintimespanReject++; // count if in timespan
$lineContent = explode("\t", $linesReject[$i]);
// loop through line elements and count them
$x = 0;
for ($j = 0; $j < count($keys); $j++) {
if (!isset($lineContent[$j])) {
continue;
}
// remember position of last not empty column
if (trim($lineContent[$j]) != '') {
$x = $j;
}
}
if ($x > 0) {
$values[$keys[$x]]++;
}
}
}
$i = 0;
$sql = "";
foreach ($values as $value)
{
if($value != 0)
{
$sql = oci_parse($c1,"INSERT INTO WA_LFO_TBL_REJECT_OUTPUT(MODELID_FK, QUANTITY, RPID_FK, CONFIGURATIONID_FK)VALUES('" . $dModel['MODELID'] . "', '" . $value . "', '" . $idkeys[$i] . "', '" . $dDtl2['CONFIGURATIONID'] . "')");
oci_execute($sql);
}
$i++;
}
}
}
As you can see that I'm trying to insert the date on foreach function.
But inserted data for ID is not correct for RPID_FK.
I realize maybe something wrong with the code, tried to get the solution but still stuck on it.
Is something wrong on that code?

Creating a php class for database insert functions

I am trying to create a class to save time on cleaning up my variables before sending them to the database to prevent sql injections. The basic systems is working now but i cant seem to get a where/or statement implemented. Does anyone know how to add this?
<?php
class Database {
private $db = '';
private $database = '';
function __construct($settings) {
$this->db = new mysqli('127.0.0.1', $settings['mysql_user']['username'], $settings['mysql_user']['password']);
$this->database = $settings['mysql_user']['database'];
print_r('Database Loaded!<br/>');
}
public function query($method, $database, $rows, $params, $where = array(), $or = array()) {
$count = 0;
$amount = count($rows);
$final_rows = '';
$final_data = '';
$bind_names = array();
$bind_names[0] = '';
$param_types = array(
"int" => "i",
"string" => "s",
"double" => "d",
"blob" => "b"
);
switch($method) {
case 'INSERT':
foreach ($rows as $row) {
$count = $count + 1;
$final_rows .= '`' . $row . '`' . ($count != $amount ? ', ' : '');
$final_data .= '?' . ($count != $amount ? ', ' : '');
}
$stmt = $this->db->prepare('INSERT INTO `' . $this->database . '`.`' . $database . '` (' . $final_rows . ') VALUES (' . $final_data . ')');
for ($i = 0; $i < count($params); $i++)
{
$bind_name = 'bind'.$i;
$$bind_name = $params[$i][1];
$bind_names[0] .= $param_types[$params[$i][0]];
$bind_names[] = &$$bind_name;
}
call_user_func_array( array ($stmt, 'bind_param'), $bind_names);
return $stmt->execute();
break;
case 'UPDATE':
foreach ($rows as $row) {
$count = $count + 1;
$final_rows .= '`' . $row . '`' . ($count != $amount ? ', ' : '');
$final_data .= '?' . ($count != $amount ? ', ' : '');
}
$stmt = $this->db->prepare('UPDATE `' . $this->database . '`.`' . $database . '` SET ' . $final_rows . '');
for ($i = 0; $i < count($params); $i++)
{
$bind_name = 'bind'.$i;
$$bind_name = $params[$i][1];
$bind_names[0] .= $param_types[$params[$i][0]];
$bind_names[] = &$$bind_name;
}
call_user_func_array( array ($stmt, 'bind_param'), $bind_names);
return $stmt->execute();
break;
case 'REPLACE':
foreach ($rows as $row) {
$count = $count + 1;
$final_rows .= '`' . $row . '`' . ($count != $amount ? ', ' : '');
$final_data .= '?' . ($count != $amount ? ', ' : '');
}
$stmt = $this->db->prepare('REPLACE INTO `' . $this->database . '`.`' . $database . '` (' . $final_rows . ') VALUES (' . $final_data . ')');
for ($i = 0; $i < count($params); $i++)
{
$bind_name = 'bind'.$i;
$$bind_name = $params[$i][1];
$bind_names[0] .= $param_types[$params[$i][0]];
$bind_names[] = &$$bind_name;
}
call_user_func_array( array ($stmt, 'bind_param'), $bind_names);
return $stmt->execute();
break;
}
}
}
?>
Going to make a few assumptions, but first I'll recommend you use an ORM before whipping up your own solution. Here's a good list of PHP libraries (I've linked to the database sections, which includes some very well done stand-alone ORMs https://github.com/ziadoz/awesome-php#database)
That being said I'm going to assume the $where and $or arrays are both for the WHERE construct and the items in $where are combined via AND and the $or is combined via OR.
Because you didn't describe what kind of output you were looking for I'm also assuming your $where and $or are key/value pairs which translates to "key=value AND key=value AND (key=value OR key=value)".
DISCLAIMER: This example is kind of hacky, but is the shortest/simplest way to get the example across.
$whereQuery = '';
foreach ($where as $key => $value) {
$whereQuery .= "$key = $value AND";
}
if ($or !== array()) {
$whereQuery .= '(';
foreach ($or as $key => $value) {
$whereQuery .= "$key = $value OR";
}
}
if ($whereQuery !== '') {
if (($temp = strlen($whereQuery) - strlen('AND')) >= 0 && strpos($whereQuery, 'AND', $temp) !== false) {
$whereQuery = substr($whereQuery, -4);
} else {
$whereQuery = substr($whereQuery, -3) . ')';
}
$whereQuery = "WHERE $whereQuery";
}
You can then stick the $whereQuery at the end of an UPDATE or SELECT. Even if $where and $or are empty it'll still work.
You could move the loops into functions and make it recursive if the $value was another array so you could create more complex WHERE statements.

How To Change Numbers Based On Results

I have a follow up question on something I got help with here the other day (No Table Three Column Category Layout).
The script is as follows:
$res = mysql_query($query);
$system->check_mysql($res, $query, __LINE__, __FILE__);
$parent_node = mysql_fetch_assoc($res);
$id = (isset($parent_node['cat_id'])) ? $parent_node['cat_id'] : $id;
$catalist = '';
if ($parent_node['left_id'] != 1)
{
$children = $catscontrol->get_children_list($parent_node['left_id'], $parent_node['right_id']);
$childarray = array($id);
foreach ($children as $k => $v)
{
$childarray[] = $v['cat_id'];
}
$catalist = '(';
$catalist .= implode(',', $childarray);
$catalist .= ')';
$all_items = false;
}
$NOW = time();
/*
specified category number
look into table - and if we don't have such category - redirect to full list
*/
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE cat_id = " . $id;
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$category = mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0)
{
// redirect to global categories list
header ('location: browse.php?id=0');
exit;
}
else
{
// Retrieve the translated category name
$par_id = $category['parent_id'];
$TPL_categories_string = '';
$crumbs = $catscontrol->get_bread_crumbs($category['left_id'], $category['right_id']);
for ($i = 0; $i < count($crumbs); $i++)
{
if ($crumbs[$i]['cat_id'] > 0)
{
if ($i > 0)
{
$TPL_categories_string .= ' > ';
}
$TPL_categories_string .= '' . $category_names[$crumbs[$i]['cat_id']] . '';
}
}
// get list of subcategories of this category
$subcat_count = 0;
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE parent_id = " . $id . " ORDER BY cat_name";
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$need_to_continue = 1;
$cycle = 1;
$column = 1;
$TPL_main_value = '';
while ($row = mysql_fetch_array($result))
{
++$subcat_count;
if ($cycle == 1)
{
$TPL_main_value .= '<div class="col'.$column.'"><ul>' . "\n";
}
$sub_counter = $row['sub_counter'];
$cat_counter = $row['counter'];
if ($sub_counter != 0)
{
$count_string = ' (' . $sub_counter . ')';
}
else
{
if ($cat_counter != 0)
{
$count_string = ' (' . $cat_counter . ')';
}
else
{
$count_string = '';
}
}
if ($row['cat_colour'] != '')
{
$BG = 'bgcolor=' . $row['cat_colour'];
}
else
{
$BG = '';
}
// Retrieve the translated category name
$row['cat_name'] = $category_names[$row['cat_id']];
$catimage = (!empty($row['cat_image'])) ? '<img src="' . $row['cat_image'] . '" border=0>' : '';
$TPL_main_value .= "\t" . '<li>' . $catimage . '' . $row['cat_name'] . $count_string . '</li>' . "\n";
++$cycle;
if ($cycle == 7) // <---- here
{
$cycle = 1;
$TPL_main_value .= '</ul></div>' . "\n";
++$column;
}
}
if ($cycle >= 2 && $cycle <= 6) // <---- here minus 1
{
while ($cycle < 7) // <---- and here
{
$TPL_main_value .= ' <p> </p>' . "\n";
++$cycle;
}
$TPL_main_value .= '</ul></div>'.$number.'
' . "\n";
}
I was needing to divide the resulting links into three columns to fit my html layout.
We accomplished this by changing the numbers in the code marked with "// <---- here".
Because the amount of links returned could be different each time, I am trying to figure out how to change those numbers on the fly. I tried using
$number_a = mysql_num_rows($result);
$number_b = $number_a / 3;
$number_b = ceil($number_b);
$number_c = $number_b - 1;
and then replacing the numbers with $number_b or $number_c but that doesn't work. Any ideas?
As mentioned before, you can use the mod (%) function to do that.
Basically what it does is to get the remainder after division. So, if you say 11 % 3, you will get 2 since that is the remainder after division. You can then make use of this to check when a number is divisible by 3 (the remainder will be zero), and insert an end </div> in your code.
Here is a simplified example on how to use it to insert a newline after every 3 columns:
$cycle = 1;
$arr = range (1, 20);
$len = sizeof ($arr);
for ( ; $cycle <= $len; $cycle++)
{
echo "{$arr[$cycle - 1]} ";
if ($cycle % 3 == 0)
{
echo "\n";
}
}
echo "\n\n";

Echoing out a variable variables list

I need to create a string like ‘Acme’, ‘Umbrella’, ‘Waymart’ for use in a java function. So far, I have:
$info0 = "SELECT DISTINCT Company FROM CETracker";
$rs0=odbc_exec($conn1,$info0);
$count = 1;
while($row = odbc_fetch_array($rs0))
{
${'V'.$count++} = "" . $row['Company'] . "";
}
$categories = "'$V1', '$V2', '$V3'";
echo $categories;
I then have $categories echo in the place the function needs the company list. This work as long as there are just 3 companies. But when more are added, I’ll have to add ‘$V4’, ‘$V5’ and so on. Any ideas? Thanks.
Use arrays instead of variable variables, you can then implode the results:
$info0 = "SELECT DISTINCT Company FROM CETracker";
$rs0 = odbc_exec($conn1,$info0);
$companies = array();
while($row = odbc_fetch_array($rs0)) {
$companies[] = "'" . $row['Company'] . "'";
}
$categories = implode(', ', $companies);
echo $categories;
... if you would like to continue with variable variables, use a loop to create your string:
$info0 = "SELECT DISTINCT Company FROM CETracker";
$rs0=odbc_exec($conn1,$info0);
$count = 1;
while($row = odbc_fetch_array($rs0)) {
${'V'.$count++} = "" . $row['Company'] . "";
}
$categories = '';
for($x = 1; $x <= $count; $x++) {
if($x > 1) $categories .= ', '; // add the comma
$categories .= "'" . ${'V'.$x} . "'"; // add the variable variable
}
echo $categories;
Please try this:
$info0 = "SELECT DISTINCT Company FROM CETracker";
$rs0=odbc_exec($conn1,$info0);
$count = 1;
$str = '';
while($row = odbc_fetch_array($rs0))
{
$str .= "'".$row['Company']."',";
}
$str = substr($str,0,strlen($str)-1);
echo $str;

Categories