I have this piece of code that currently almost does what I need. It needs to select all records from a table and then format them ready for encoding to JSON. However, ONE record will have a "type" field set as "default". This record is placed first in the JSON file and formatted slightly different.
Currently this works prefectly if the record set to default is the last entry in the database table. But, if it isn't, then the formatting breaks when encoding to JSON.
Can anyone help suggest a fix that would force it to ignore where the default entry is, but retain the formatting?
// Get the data from the DB.
$query = 'SELECT type, headline, startDate, text, media, caption, credits FROM #__timeline_entries'.$table.'';
$db->setQuery($query);
// Load it and put it into an array
$list = $db->loadObjectList();
$len = count($list);
$data = array();
for ($i = 0; $i < $len; $i++) {
$temp = (array) $list[$i];
$temp["asset"] = array(
"media" => $temp["media"],
"credit" => $temp["credits"],
"caption" => $temp["caption"]
);
unset($temp["media"]);
unset($temp["credits"]);
unset($temp["caption"]);
if ($temp["type"] == "default") {
$data = $list[$i];
unset($list[$i]);
$list[$i] = $temp;
}
}
// Prep it for JSON
$data->date = &$list;
// Loop it once more!
$dataTwo->timeline = &$data;
// Encode the data to JSON.
$jsondata = json_encode($dataTwo);
This is part of a Joomla component, but it doesn't really use any of the Joomla framework beyond the database connection. I thought I'd mention it just in case it made any difference, though I don't see how.
Add an ORDER BY clause:
ORDER by (type = "default")
This will be 0 for all the records except the default, which is 1, so it will be put last.
Add a WHERE clause to your MySQL statement:
$query = 'SELECT type, headline, startDate, text, media, caption, credits FROM #__timeline_entries'.$table.' WHERE type <> default';
Related
I am new to json, my aim is to maintain the history of specific columns(which are posted through $_POST in php) on every update in mysql using php. I took one json array for the history column and placed it in a while loop, after that I appended the variable which i want to merge with the previous one with array_merge() function. I am getting the output but starting with 0. Let me know how to append the required fields in a proper json format and also how to retrieve the json data in a div tag. Thanks in advance.
PHP Code:
<?php
$query = mysqli_query($conn,"SELECT `history` FROM projects WHERE `no` = '$id'");
$json_data = array();
while ($js = mysqli_fetch_assoc($query))
{
$json_data[] = $js['history'];
$j = $json_data;
}
?>
<?php
if(isset($_POST['submit'])){
if(isset($_GET['id'])){
$id = $_GET['id'];
$assign = mysqli_real_escape_string($conn,$_POST['assign']);
$end_date = mysqli_real_escape_string($conn,$_POST['end_date']);
$comments = mysqli_real_escape_string($conn,$_POST['comments']);
$end_date = [
'assigned_to' => $assign,
'end_date' => $end_date,
'comments' => $comments
];
$json = array_merge($j,$end_date);
$js = json_encode($json);
$ins = mysqli_query($conn,"UPDATE `projects` SET `assigned_to`='$assign',`end_date`='$end_date',
`status`='$status',`comments`='$comments'`history`= '$js' WHERE
`episode_no` = '$id'");
}
}
?>
JSON data in MYSQL :
{"0":"{"0":"{"0":"","assigned_to":"AAA","end_date":"2018-09-12","comments":"happy"}",
"assigned_to":"AAA","end_date":"2018-09-12","comments":"jolly"}",
"assigned_to":"AAA","end_date":"2018-09-12","comments":"xvbcvbdfghdfg"}
First of all, the answer to your question: you are loading an array of strings in $j, so the array_merge function won't work as expected:
$j[0] = 'some JSON string from DB';
$json = array_merge($j, $end_date);
the array_merge finds that the second argument is a sparse array, so it merges the keys as strings:
$json = [
'0' => 'the previous string',
'assigned_to' => ...
]
For your idea to work you probably need to store the new history item by appending to the array:
$j[] = $end_date;
$js = json_encode($j);
...
This would solve your issue.
But there is a very major issue here that you need to solve first. It's a OMG-like WTF-like issue. You are getting $id from user input (query parameters) and sending it to the DB without any fear. Suppose that the user sends
https://your.server/some/path?id=';TRUNCATE TABLE projects --'
(propery url-encoded of course). Now you are sending this to the database:
SELECT `history` FROM projects WHERE `no` = '';TRUNCATE TABLE projects --''
Bye bye projects. A user can do whatever to your database, change passwords, reassign foreign keys, set himself as administrator.
Please for the sake of whatever you believe in, use a proper ORM and never pass user input to the DB!!!
I know how to get a mysql-row and convert it to json:
$row = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM table WHERE id=1"));
echo json_encode($row); // it's an ajax-call
but:
the db-row has different types like int, float, string.
by converting it using json_encode() all results are strings.
Is there a better way to correct the types than this:
$row['floatvalue1'] = 0+$row['floatvalue1'];
$row['floatvalue2'] = 0+$row['floatvalue2'];
$row['intvalue1'] = 0+$row['intvalue1'];
I would like to loop through the keys and add 0 because:
first coding rule: DRY - dont repeat yourself
but i can't because:
row has also other types than numbers (string, date)
there are many columns
design is in dev, so columns-names often changes
Thanks in advance and excuse my bad english :-)
EDIT (to answer the comment-question from Casimir et Hippolyte):
I call this php-code using ajax to get dynamically sql-values. in my javascript-code i use the results like this:
result['intvalue1'] += 100;
lets say the json-result of intval1 is 50, the calculated result is:
"50100", not 150
The code below is just a proof of concept. It needs encapsulation in a function/method and some polishing before using it in production (f.e. call mysqli_fetch_field() in a loop and store the objects it returns before processing any row, not once for every row).
It uses the function mysqli_fetch_field() to get information about each column of the result set and converts to numbers those columns that have numeric types. The values of MYSQLI_TYPE_* constants can be found in the documentation page of Mysqli predefined constants.
// Get the data
$result = mysqli_query($db, "SELECT * FROM table WHERE id=1");
$row = mysqli_fetch_assoc($result);
// Fix the types
$fixed = array();
foreach ($row as $key => $value) {
$info = mysqli_fetch_field($result);
if (in_array($info->type, array(
MYSQLI_TYPE_TINY, MYSQLI_TYPE_SHORT, MYSQLI_TYPE_INT24,
MYSQLI_TYPE_LONG, MYSQLI_TYPE_LONGLONG,
MYSQLI_TYPE_DECIMAL,
MYSQLI_TYPE_FLOAT, MYSQLI_TYPE_DOUBLE
))) {
$fixed[$key] = 0 + $value;
} else {
$fixed[$key] = $value;
}
}
// Compare the results
echo('all strings: '.json_encode($row)."\n");
echo('fixed types: '.json_encode($fixed)."\n");
something like
$row['floatvalue1'] = reset( sscanf ( $row['floatvalue1'] , "%f" ));
$row['floatvalue2'] = reset( sscanf ( $row['floatvalue2'] , "%f" ));
$row['intvalue1'] = reset( sscanf ( $row['intvalue1'] , "%d" ));
json_encode($row);
If you're simply trying to make sure that your values are operable with respect to their type, you need to first cast their type correctly.
Unless you need them server-side, I would just pass-on the json directly to the front-end and do the work there.
In Javascript, you could make an attempt at casting the numbers like so:
function tryNumber(string){
return !isNaN( parseInt(string) ) ? parseInt(string) : string;
}
function tryDate(string){
return !isNaN( new Date(string).getTime() ) ? new Date(string) : string;
}
tryNumber('foo'); // "hello"
tryNumber('24'); // 24
tryDate('bar'); // "bar"
tryDate('December 17, 1995'); // "Sun Dec 17 1995 00:00:00 GMT+0000 (GMT)"
These two lines attempt to cast the values as a Date/Number. If they can't be cast, they will remain String's.
A MySQLi OO version based on #axiac's answer, that produces a JSON array ($jsnAll) containing all records. In this code snippet, the method FixSQLType is called to fix a row. Note, it should be wrapped in a try{}catch{} block and "objMySQLi" has already been instantiated:
$lcAllRows = array();
// Make an SQL SELECT statement
$SQL = "SELECT * FROM $lcName WHERE $lcWhere";
// Run the query
$this->sqlResult = $this->objMySQLi->query($SQL);
// Fetch the result
while( $row = $this->sqlResult->fetch_assoc()){
$lcCount = count($lcAllRows) ;
// Call to fix, row
$fixedRow = $this->FixSQLType($row);
$lcAllRows[$lcCount]= $fixedRow;
}
$jsnAll = json_encode($lcAllRows);
The FixSQLType method. This is almost identical to #axiac's answer, except for the call to $this->sqlResult->fetch_field_direct($i). "fetch_field" seemed to get itself lost, using "fetch_field_direct" overcame that problem.
private function FixSQLType($pRow){
// FROM https://stackoverflow.com/a/28261996/7571029
// Fix the types
$fixed = array();
$i = 0;
foreach ($pRow as $key => $value) {
$info = $this->sqlResult->fetch_field_direct($i);
$i++;
if (in_array($info->type, array(
MYSQLI_TYPE_TINY, MYSQLI_TYPE_SHORT, MYSQLI_TYPE_INT24,
MYSQLI_TYPE_LONG, MYSQLI_TYPE_LONGLONG,
MYSQLI_TYPE_DECIMAL,
MYSQLI_TYPE_FLOAT, MYSQLI_TYPE_DOUBLE
))) {
$fixed[$key] = 0 + $value;
} else {
$fixed[$key] = $value;
}
}
return $fixed;
}
I am pretty new to PHP, but have tried searching for other questions similar to mine and been unable to find anything that is close enough to my situation to help me solve this.
I am trying to code a web page that allows users to select as many or as few items as they would like to order. The item values are identical to their Primary Key in the Item table.
Once submitted, each different item value should be input into the same row of a database table based on the date{pk}. Within that row, there are numerous columns: Item1ID, Item2ID, Item3ID, etc.
So far, the value of each item selected is assigned to a new array. However, I cannot simply input the array values into a column -- I need each array index to be placed into a sequential column. The code is below:
$date = new DateTime();
$td = $date->format('Y-m-d');
$x = 1;
$checkedItems = $_POST['Item'];
$count = count($checkedItems);
echo $count;
$foodID = "Item".$x."ID";
While($x<=$count){
if(isset($_POST['Item'])){
if (is_array($_POST['Item'])) {
foreach($_POST['Item'] as $values){
$selectedFoods = substr($values,0,4);
$addFoodOrderQuery= sprintf("UPDATE WeeklyBasketFoodOrder SET '%s' = %s WHERE `foodOrderDate` = '%s'",
$foodID, $selectedFoods, $td);
$result= mysqli_query($db, $addFoodOrderQuery);
}
}
} else {
$values = $_POST['Item'];
echo "You have not selected any items to order.";
}
$x++;
}
If you need any further clarification, please let me know. After submitting the code, the database item#ID tables are different, but they are now empty instead of "NULL."
I have an application that looks like this:
As you can see, each row contains either a group heading (the rows where there is just an input), or a ingredient form (where there is a small input, then a select, then another larger input).
I use Javascript to add the new spans. I use the following PHP to group each ingredient span into an array, determine the order (because each span can be moved to a different order), and insert into my database.
foreach($_POST as $key => $value) {
$value = $this->input->post($key);
$ingredientQTY = $this->input->post('ingredientQTY');
$measurements = $this->input->post('measurements');
$ingredientNAME = $this->input->post('ingredientNAME');
$ingredientsROW[] = array($ingredientQTY, $measurements, $ingredientNAME);
for ($i = 0, $count = count($ingredientQTY); $i < $count; $i++) {
$rows[] = array(
'ingredientamount' => $ingredientQTY[$i],
'ingredientType' => $measurements[$i],
'ingredientname' => $ingredientNAME[$i],
'recipe_id' => $recipe_id,
'order' => $i + 1,
'user_id' => $user_id
);
$sql = "INSERT `ingredients` (`ingredientamount`,`ingredientType`,`ingredientname`, `recipe_id`, `order`, `user_id`) VALUES ";
$coma = '';
foreach ($rows as $oneRow) {
$sql .= $coma."('".implode("','",$oneRow)."')";
$coma = ', ';
}
}
$this->db->query($sql);
break;
}
This works wonders for inserting the ingredient rows. But I'm not sure how to insert group headings (which must be placed in the for loop to keep the order, the $i + 1, going).
I think I've figured out two solutions(though there may be others, and these might not even work):
Have the group heading input field have the same name value as one of the ingredient text fields, and send a hidden value along with it, saying its a group heading?
Send it as different input field with a different name value?
My question is: how can I do this with my current code, and are either of these efficient solutions, or is there an even better solution?
Thanks for all help! If you need more details, just ask!
You could use an empty heading like <input type="hidden" name="groupheading[]" value="product" /> and the open one like <input type="text" name="groupheading[]" value="" />. The first one should be inside the product-span.
This way, you can continue your loop just the way you are doing now. And $_POST['groupheading'][$key] either returns a groupheading or the phrase 'product'. So, in your script it would be:
if($_POST['groupheading'][$key] == "product") {
// insert product
} else {
// insert group heading
}
I think I helped you this morning or yesterday with an answer.. it's still a bit a weird way you are using to get the effect you need. It can be achieved much easier.
I previously designed the website I'm working on so that I'd just query the database for the information I needed per-page, but after implementing a feature that required every cell from every table on every page (oh boy), I realized for optimization purposes I should combine it into a single large database query and throw each table into an array, thus cutting down on SQL calls.
The problem comes in where I want this array to include skipped IDs (primary key) in the database. I'll try and avoid having missing rows/IDs of course, but I won't be managing this data and I want the system to be smart enough to account for any problems like this.
My method starts off simple enough:
//Run query
$localityResult = mysql_query("SELECT id,name FROM localities");
$localityMax = mysql_fetch_array(mysql_query("SELECT max(id) FROM localities"));
$localityMax = $localityMax[0];
//Assign table to array
for ($i=1;$i<$localityMax+1;$i++)
{
$row = mysql_fetch_assoc($localityResult);
$localityData["id"][$i] = $row["id"];
$localityData["name"][$i] = $row["name"];
}
//Output
for ($i=1;$i<$localityMax+1;$i++)
{
echo $i.". ";
echo $localityData["id"][$i]." - ";
echo $localityData["name"][$i];
echo "<br />\n";
}
Two notes:
Yes, I should probably move that $localityMax check to a PHP loop.
I'm intentionally skipping the first array key.
The problem here is that any missed key in the database isn't accounted for, so it ends up outputting like this (sample table):
1 - Tok
2 - Juneau
3 - Anchorage
4 - Nashville
7 - Chattanooga
8 - Memphis
-
-
I want to write "Error" or NULL or something when the row isn't found, then continue on without interrupting things. I've found I can check if $i is less than $row[$i] to see if the row was skipped, but I'm not sure how to correct it at that point.
I can provide more information or a sample database dump if needed. I've just been stuck on this problem for hours and hours, nothing I've tried is working. I would really appreciate your assistance, and general feedback if I'm making any terrible mistakes. Thank you!
Edit: I've solved it! First, iterate through the array to set a NULL value or "Error" message. Then, in the assignations, set $i to $row["id"] right after the mysql_fetch_assoc() call. The full code looks like this:
//Run query
$localityResult = mysql_query("SELECT id,name FROM localities");
$localityMax = mysql_fetch_array(mysql_query("SELECT max(id) FROM localities"));
$localityMax = $localityMax[0];
//Reset
for ($i=1;$i<$localityMax+1;$i++)
{
$localityData["id"][$i] = NULL;
$localityData["name"][$i] = "Error";
}
//Assign table to array
for ($i=1;$i<$localityMax+1;$i++)
{
$row = mysql_fetch_assoc($localityResult);
$i = $row["id"];
$localityData["id"][$i] = $row["id"];
$localityData["name"][$i] = $row["name"];
}
//Output
for ($i=1;$i<$localityMax+1;$i++)
{
echo $i.". ";
echo $localityData["id"][$i]." - ";
echo $localityData["name"][$i];
echo "<br />\n";
}
Thanks for the help all!
Primary keys must be unique in MySQL, so you would get a maximum of one possible blank ID since MySQL would not allow duplicate data to be inserted.
If you were working with a column that is not a primary or unique key, your query would need to be the only thing that would change:
SELECT id, name FROM localities WHERE id != "";
or
SELECT id, name FROM localities WHERE NOT ISNULL(id);
EDIT: Created a new answer based on clarification from OP.
If you have a numeric sequence that you want to keep unbroken, and there may be missing rows from the database table, you can use the following (simple) code to give you what you need. Using the same method, your $i = ... could actually be set to the first ID in the sequence from the DB if you don't want to start at ID: 1.
$result = mysql_query('SELECT id, name FROM localities ORDER BY id');
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[(int) $row['id']] = array(
'id' => $row['id'],
'name' => $row['name'],
);
}
// This saves a query to the database and a second for loop.
end($data); // move the internal pointer to the end of the array
$max = key($data); // fetch the key of the item the internal pointer is set to
for ($i = 1; $i < $max + 1; $i++) {
if (!isset($data[$i])) {
$data[$i] = array(
'id' => NULL,
'name' => 'Erorr: Missing',
);
}
echo "$i. {$data[$id]['id']} - {$data[$id]['name']}<br />\n";
}
After you've gotten your $localityResult, you could put all of the id's in an array, then before you echo $localityDataStuff, check to see
if(in_array($i, $your_locality_id_array)) {
// do your echoing
} else {
// echo your not found message
}
To make $your_locality_id_array:
$locality_id_array = array();
foreach($localityResult as $locality) {
$locality_id_array[] = $locality['id'];
}