php misinterpretation of mysql query - php

I have a database with a "Text" col which contains a javascript object like this:
{
"description" : "",
"title" : " diagramm1",
"xlabel" : "Zeit",
"ylabel" : "",
"ylabel1" : "Anzahl Stabis aufgelegt",
"ylabel2" : "Anzahli.O.",
"tablename" : "edmat1",
"xvaluecol" : "timestamp",
"y1valuecol" : "EDMAT1Q001",
"y2valuecol" : "EDMAT1Q002",
"showRangeSelector" : true,
"divid" : "diagramm1",
"refreshtime" : 30000
}
If I get this out of the database with php it is interpreted as a php array. What can I do to force php to treat this like a string? Afterwards I want to give this javascript object to javascript.
Tried json_encode on php side and JSON.parse at Javascript side, there must be a other solution.
EDIT:
$db=mysql_connect("localhost","root","");
mysql_select_db("visualization");
$anfrage="SELECT options FROM mat1 WHERE id=1";
$a=mysql_query($anfrage);
$b=mysql_fetch_row($a);
echo $b;
only have on row!

If I get this out of the database with php it is interpreted as a php array. What can I do to force php to treat this like a string?
If you store it as a string, then it will stay a string. Even in JavaScript you have to parse it to have an object or an array.
You use mysql_fetch_row, that means you will have your row with your result in an indexed array.
As yoy selected only one column, your array will contain only one column too.
So your solution is (as said in comments) $your_result = $db[0];
Moreover, acording to the php doc I advise you to switch your mysql_ function to mysqli_ functions that are newer, more performant and which support newer version of Mysql SGBD.

Related

PHP and JSON datatype in MySQL

Despite of recent implementation of JSON datatype to MySQL I can't find any word on it in the related PHP documentation.
My question is: will PHP automatically convert cells of JSON column to the actual values - arrays or literals - or will it provide just json-encoded strings. Like:
$sql_query = "SELECT JSON_ARRAY(1,2,3)";
$result = mysqli_query($sql_query);
$value = mysqli_fetch_row($result)[0];
// what is a $value? Array(1,2,3) or a string "[1,2,3]"
// do I have to use json_decode() to get an actual array here?
(Don't have MySQL 5.7 at hand right now, so can't check it myself.)
i think with serialize and unserialize you get whatever you want.
so just store all values using serialize and you can get that values with unserialize.
so just check serialize and unserialize.

Select condition within a hash column using Doctrine mongoDB ODM query builder

I have the following structure within a mongoDB collection:
{
"_id" : ObjectId("5301d337fa46346a048b4567"),
"delivery_attempts" : {
"0" : {
"live_feed_id" : 107,
"remaining_attempts" : 2,
"delivered" : false,
"determined_status" : null,
"date" : 1392628536
}
}
}
// > db.lead.find({}, {delivery_attempts:1}).pretty();
I'm trying to select any data from that collection where remaining_attempts are greater than 0 and a live_feed_id is equal to 107. Note that the "delivery_attempts" field is of a type hash.
I've tried using an addAnd within an elemMatch (not sure if this is the correct way to achieve this).
$qb = $this->dm->createQueryBuilder($this->getDocumentName());
$qb->expr()->field('delivery_attempts')
->elemMatch(
$qb->expr()
->field('remaining_attempts')->gt(0)
->addAnd($qb->expr()->field('live_feed_id')->equals(107))
);
I do appear to be getting the record detailed above. However, changing the greater than
test to 3
->field('remaining_attempts')->gt(3)
still returns the record (which is incorrect). Is there a way to achieve this?
EDIT: I've updated the delivery_attempts field type from a "Hash" to a "Collection". This shows the data being stored as an array rather than an object:
"delivery_attempts" : [
{
"live_feed_id" : 107,
"remaining_attempts" : 2,
"delivered" : false,
"determined_status" : null,
"date" : 1392648433
}
]
However, the original issue still applies.
You can use a dot notation to reference elements within a collection.
$qb->field('delivery_attempts.remaining_attempts')->gt(0)
->field('delivery_attempts.live_feed_id')->equals(107);
It works fine for me if I run the query on mongo.
db.testQ.find({"delivery_attempts.remaining_attempts" : {"$gt" : 0}, "delivery_attempts.live_feed_id" : 107}).pretty()
so it seems something wrong with your PHP query, I suggest running profiler to see which query is actually run against mongo
db.setProfilingLevel(2)
This will log all operation since you enable profiling. Then you can query the log to see which the actual queries
db.system.profile.find().pretty()
This might help you to find the culprit.
It sounds like your solved your first problem, which was using the Hash type mapping (instead for storing BSON objects, or associative arrays in PHP) instead of the Collection mapping (intended for real arrays); however, the query criteria in the answer you submitted still seems incorrect.
$qb->field('delivery_attempts.remaining_attempts')->gt(0)
->field('delivery_attempts.live_feed_id')->equals(107);
You said in your original question:
I'm trying to select any data from that collection where remaining_attempts are greater than 0 and a live_feed_id is equal to 107.
I assume you'd like that criteria to be satisfied by a single element within the delivery_attempts array. If that's correct, the criteria you specified above may match more than you expect, since delivery_attempts.remaining_attempts can refer to any element in the array, as can the live_feed_id criteria. You'll want to use $elemMatch to restrict the field criteria to a single array element.
I see you were using elemMatch() in your original question, but the syntax looked a bit odd. There should be no need to use addAnd() (i.e. an $and operator) unless you were attempting to apply two query operators to the same field name. Simply add extra field() calls to the same query expression you're using for the elemMatch() method. One example of this from ODM's test suite is QueryTest::testElemMatch(). You can also use the debug() method on the query to see the raw MongoDB query object created by ODM's query builder.

JSON Validation and parsing in PHP

I am parsing JSON using the following example php syntax
$carModel = strip_tags($_REQUEST['car']['model']);
The only problem is that some times the "model" array is missing from the provided JSON. When this is the case my php script shuts down when it reaches that line. Can any one recommend a way to check for the model array before parsing so that my php scrip will still run if "model" isn't present.
Just check to see if it's there. If not assign a default value to it:
$carModel = (isset($_REQUEST['car']['model'])) ? strip_tags($_REQUEST['car']['model']) : '';
I'm not sure how this is related to json, but if you want to check if a variable exists before you use it, you can do:
if (isset($_REQUEST['car']['model']))
{
$carModel = strip_tags($_REQUEST['car']['model']);
}

Problem with json_encode()

i have an simple array:
array
0 => string 'Kum' (length=3)
1 => string 'Kumpel' (length=6)
when I encode the array using json_encode(), i get following:
["Kum","Kumpel"]
My question is, what is the reason to get ["Kum","Kumpel"] instead of { "0" : "Kum", "1" : "Kumpel" }?
"{}" brackets specify an object and "[]" are used for arrays according to JSON specification. Arrays don't have enumeration, if you look at it from memory allocation perspective. It's just data followed by more data, objects from other hand have properties with names and the data is assigned to the properties, therefore to encode such object you must also pass the correct property names. But for array you don't need to specify the indexes, because they always will be 0..n, where n is the length of the array - 1, the only thing that matters is the order of data.
$array = array("a","b","c");
json_encode($array); // ["a","b","c"]
json_encode($array, JSON_FORCE_OBJECT); // {"0":"a", "1":"b","2":"c"}
The reason why JSON_FORCE_OBJECT foces it to use "0,1,2" is because to assign data to obeject you must assign it to a property, since no property names are given by developer (only the data) the encoder uses array indexes as property names, because those are the only names which would make sense.
Note: according to PHP manual the options parameters are only available from PHP 5.3.
For older PHP versions refer to chelmertz's answer for a way to make json_encode to use indexes.
As Gumbo said, on the JS-side it won't matter. To force PHP into it, try this:
$a = new stdClass();
$a->{0} = "Kum";
$a->{1} = "Kumpel";
echo json_encode($a);
Not that usable, I'd stick with the array notation.
Just cast as an object and it will work fine...the JSON_FORCE_OBJECT parameter does exactly the same thing.
json_encode((object)$array);
Don't forget to convert it back into a php array so you can access its values in php:
$array = (object)$array;
$array = (array)$array;
json_encode($array);
Since you’re having a PHP array with just numeric keys, there is no need to use a JavaScript object. But if you need one, try Maiku Mori’s suggestion.
I personally think this is a bug that needs to be fixed in PHP. JSON_FORCE_OBJECT is absolutely not an answer. If you try to do any sort of generic programming you get tripped up constantly. For example, the following is valid PHP:
array("0" => array(0,1,2,3), "1" => array(4,5,6,7));
And should be converted to
{"0": [0,1,2,3], "1": [4,5,6,7]}
Yet PHP expects me to either accept
[[0,1,2,3],[4,5,6,7]]
or
{"0":{"0":1,"1":1,"2":2,"3":3},"1":{"0":4,"1":5,"2":6,"3":7}}
Neither of which are right at all. How can I possibly decode an object like that? What possible reason is there to ever change something that is clearly using strings as indexes? It's like PHP was trying to be clever to help out idiotic people who can't differentiate strings from ints, but in the process messed up anyone legitimately using strings as indexes, regardless of what the value COULD be turned into.

How to encode 2 dimentional PHP array to Javascript Array?

Here's my problem, i have a php array like this:
$output = array(array(1,1,1,1),array(2,2,2,2),array(3,3,3,3));
after the array was encoded to json i got this:
$output = {"1":[1,1,1,1],"2":[2,2,2,2],"3":[3,3,3,3]}
all i want is to pass the PHP array to Javascript so that the JS looks like this:
var output = [[1,1,1,1],[2,2,2,2],[3,3,3,3,]];
Thanks in advance...
Which version of PHP are you using ?
With PHP 5.2.10, I get what you're asking for :
$output = array(array(1,1,1,1),array(2,2,2,2),array(3,3,3,3));
$json = json_encode($output);
echo $json . "\n";
Outputs :
$ php temp.php
[[1,1,1,1],[2,2,2,2],[3,3,3,3]]
At least, this is without the JSON_FORCE_OBJECT option -- that was added in PHP 5.3
Maybe you can find something interesting in the user notes on the json_encode manual page ?
For instance, simoncpu says :
A note of caution: If you are
wondering why json_encode() encodes
your PHP array as a JSON object
instead of a JSON array, you might
want to double check your array keys
because json_encode() assumes that you
array is an object if your keys are
not sequential.
And if you search for json_encode+array+object on PHP's bugtracker, maybe you'll get some interesting result ?
(For instance, something that says this was a bug, which has been corrected in recent versions of PHP ?)
Your original solution works for me:
adam#fsck:~:0$ php -r 'echo json_encode(array(array(1,1,1,1),array(2,2,2,2),array(3,3,3,3)));'
[[1,1,1,1],[2,2,2,2],[3,3,3,3]]

Categories