How to pass array in laravel where condition? - php

$table='user';
$conditions=array(
'uname' => 'test',
'pwd' => '123'); //uname and pwd are the column names
DB::table($table)->where($conditions)->get();
while excuting above code its showing following error
ErrorException
strtolower() expects parameter 1 to be string, array given
Can any one help me pls.

I don't know which classes you are using but your php compilator said that you passed array instead of string, so maybe try pass conditions in string format:
$conditions = "uname='test'&pwd='123'";
UPDATE
As you can see in docs (http://laravel.com/docs/queries#selects), you can only pass strings to where method so you have to do sth like that:
$select = DB::table($table);
foreach($conditions as $column=>$value){
$select->where($column,'=',$value);
}
$result = $select->get();

Related

JSON encode_decode weird behave PHP

I have array input in HTML Form as below
<select name="age[]" id="ageFrom">..Age Options..</select>
<select name="age[]" id="ageTo">..Age Options..</select>
Upon submission, I am saving data in mysql database as json_encoded value like ["20","25"]
foreach($request->request as $key => $value) {
ProfileSettings::create([
'uid' => $curMID,
'code' => 'preference',
'key' => $key,
'value' => json_encode($value),
'serialized' => 1
]);
});
Now, when it get this value from DB and try to decode it as
$val = json_decode(["20", "25"]) OR json_decode(["20", "25"], true)
My DB returns value like
Then i get an error like
htmlspecialchars() expects parameter 1 to be string, array given
Kindly help me to get 20 and 25 as $val[0] and $val[1]
Thing is, you're calling json_decode on a php array [ ].
It expects a string, which it'll convert to an array.
Perhaps you wanted to use json_encode instead? If so, change your code to:
$val = json_encode(["20", "25"]) OR json_encode(["20", "25"], true)
The problem is that the value coming from the data base is ["20", "25"] and when is inserted in the json_decode() function is interpreted as an array.
To solve the problem insert the value in between double quotes.
$val = json_decode("$result") or $val = json_decode('["20", "25"]')

At a loss with JSON, PHP, AS3: Cannot trace correct value

I have used JSON objects before and they work perfectly but the JSON objects that I made before have been from a result of fetched MySQL entries. Now, I am trying to make my own JSON object through an array in PHP and it shows correctly in the database but I cannot access any of the values like before.
$chatArray = array(
array(
'chatusername' => 'Troy',
'chatuserid' => '123',
'chatmessage' => 'Hello World'
),
array(
'chatusername' => 'Nick',
'chatuserid' => '124',
'chatmessage' => 'Testing'
));
$inputArray = json_encode($chatArray);
That is what I input into my database and like I said it works good. Then I call for it in a separate .php and get this
{"chat":"[{\"chatuserid\": \"123\", \"chatmessage\": \"Hello World\", \"chatusername\": \"Troy\"}, {\"chatuserid\": \"124\", \"chatmessage\": \"Testing\", \"chatusername\": \"Nick\"}]"}
It throws the "chat" out front which is the column name in my database which I am not sure why.
When I trace it I can only seem to trace it by
var messageArray:Object = JSON.parse(event.target.data);
trace(messageArray.chat);
Any time I try to reference say messageArray.chat.chatusername it returns an error.
I'm sorry I know it is probably a simple solution but I have been searching and working at it for a few hours now.
Any help is much appreciated! Thank you!
From the PHP code that generates your JSON output:
$stmt = $conn->prepare("SELECT chat FROM markerinfo WHERE markerid='$chatid'");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($result);
Keep in mind that the chat column in your database contains a JSON-string.
This code is not decoding the JSON-string in your database, so $result will be an array containing a JSON-string as well:
$result = [
'chat' => '[{"chatusername":"Troy","chatuserid":"123","chatmessage":"Hello World"},{"chatusername":"Nick","chatuserid":"124","chatmessage":"Testing"}]'
];
By passing that array through json_encode(), you're double-encoding your JSON-string.
For your purposes, you can probably get away with:
echo $result['chat'];
But, if you want the chat column name to be included in your output, you will have to decode the stored JSON first:
$result['chat'] = json_decode($result['chat']);
echo json_encode($result);
Probably this is related to the php side when it encodes your array, it will escape it with slashes, and this confuses the JSON parsing in your JS side. Try to add the JSON_UNESCAPED_SLASHES option to your json_encode function like this:
$inputArray = json_encode($chatArray, JSON_UNESCAPED_SLASHES);
Check the json_encode function documentation for more details:
http://php.net/manual/en/function.json-encode.php

Zend_Db_Adapter fetchOne returns OCI-Lob object instead of string

I am using Zend Framework and Oracle and I am trying to receive single value from database like this:
$userId = (int) $this->_getParam('userId');
// CREATE TABLE MEMBERS (
// "MEMEBER_ID" NUMBER,
// "FIRSTNAME" VARCHAR2(20 CHAR),
// "LASTNAME" VARCHAR2(20 CHAR),
// "EMAIL" VARCHAR2(40 CHAR),
// "ABOUT" CLOB
// )
$sql = 'SELECT about FROM members WHERE id = :userId';
$binds = array (
'userId' => $userId
);
$about = Zend_Registry::get('db')->fetchOne($sql, $binds);
According to manual, fetchOne() should return string, but when I dump returned value, it looks like this:
object(OCI-Lob)#1161 (1) {
["descriptor"] => resource(209) of type (oci8 descriptor)
}
As you can see, object is returned, which is against the manual - "it returns only a single scalar value, not an array or an object."
How can I convert this to string?
Problem is in CLOB data type used in column about. Answer fot this is given in notes for Oracle adapter, especially:
By default, LOB fields are returned as OCI-Lob objects. You could retrieve them as string for all requests by using driver options 'lob_as_string' or for particular request by using setLobAsString(boolean) on adapter or on statement.
So the solution is really simple, just call setLobAsString(true) before fetchOne() like this:
$about = Zend_Registry::get('db')->setLobAsString(true)->fetchOne($sql, $binds);
echo $about; // string
You can overcome of this problem by adding 1 line in your application.ini
please add
resources.db.params.driver_options.lob_as_string=true
this will convert lob to string automatically. you don't have to write anything else in Zend.

How to use mongodb _id to find record

I am doing project with mongodb and php. so I am trying to find record using it _id. here I post json value like this way
{"_id": {"$id": "513ea9d4a00b2ade09000001"}}
then I get this value and decode it and use to find like this way
$obj = json_decode( $json, true);
$result = $collection->find($obj);
but above code give error because in the json their is a key like $id. so how I solve above problem please help me.
Please follow this example:
// This is only a string, this is NOT a MongoId
$mongoid = '4cb4ab6d7addf98506010000';
// You will not find anything by searching by string alone
$nothing = $collection->find(array('_id' => $mongoid));
echo $nothing->count(); // This should echo 0
// THIS is how you find something by MongoId
$realmongoid = new MongoId($mongoid);
// Pass the actual instance of the MongoId object to the query
$something = $collection->find(array('_id' => $realmongoid));
echo $something->count(); // This should echo 1
You could find more info here.
From a JSON string it is slightly different to all the examples shown currently.
Since you now have an object of an assoc array which looks like:
array(
'_id' => array(
'$id' => "513ea9d4a00b2ade09000001"
)
)
You must extract that $id property and cast it to a MongoId like so:
$db->collection->find(new MongoId($obj['$id']));
That will find your record.
To find document using '_id' you have to typecast it to MongoId Object. This can be done by passing array('_id' => new MongoId($valOf_id) ) in the find query.
I did not write a verbose answer as I am sure this is enough for you to get the point right :-)

What kind of php array is this and how do I edit it?

I am working with a project that is coded in php OOP. I have created a form that post back to itself and gets those values and puts them into a predefined array format. I say predefined because this is the way the previous coder has done it:
$plane->add(array('{"name":"Chris","age":"22"}','{"name":"Joyce","age":"45"}'));
So when I get my values from the $_POST array, I thought it would be simple, so I tried
$plane->add(array("{'name':$customerName,'age':$customerAge}"));
This is triggering an error though, it seems it's passing the actual name of the variable in as a string instead of it's value. So how do I pass those values in to that function. While we are on it, can someone explain what kind of array that is, I thought arrays were always $key=>value set, not $key:$value.
As other comments and answers have pointed out, the data is being serialized in a format known as JSON. I suggest reading up on json_encode() and json_decode()
To make your example work, you would have to do:
$data = array("name" => $customerName, "age" => $customerAge);
$plane->add(array(json_encode($data));
That looks like json:
http://sandbox.onlinephpfunctions.com/code/e1f358d408a53a8133d3d2e5876ef46876dff8c6
Code:
$array = json_decode('{"name":"Chris","age":"22"}');
print_r( $array );
And you can convert an array to json with:
$array = array("Customer" => "John");
$arrayJson = json_encode( $array);
So to put it in your context:
$array = array("Name"=>"Chris", "age" => 22);
$array2 = array("Name"=>"John", "age" => 26);
$plane->add(array( json_encode( $array),json_encode( $array2) );
It looks like it could be JSON, but might not be.
Be careful to quote everything like they have done, you didn't have any quotes around the name or age.
I've added the same sort of quotes, and used the backslashes so that PHP doesn't use them to end the string:
$plane->add(array("{\"name\":\"$customerName\",\"age\":\"$customerAge\"}"));
Be wary of user data, if $customerName and $customerAge come from POST data, you need to properly escape them using a well tested escaping function, not something you just hack together ;)
It looks like your array is an array of JSON encoded arrays. Try using:
$plane->add(array('{"name":"' . $nameVar . '","age":"' . $ageVar . '"}', ...));
If you use the following:
echo json_encode(array('name' => 'Me', 'age' => '75'), array('name' => 'You', 'age' => '30'));
You will get the following string:
[{"name":"Me","age":"75"},{"name":"You","age":"30"}]
I believe you are getting an error because what you are trying to pass to the function is not JSON while (It looks like ) the function expects an array json strings, Manually trying to write the string might not be a good idea as certain characters and type encode differently. Best to use json_encode to get you json string.
$plane->add(array(json_encode(array('name'=>$customerName,'age'=>$customerAge))));

Categories