Notice: Array to string conversion -json response with doctrine - arrays

I want to put a response json after decoding it in database,
my controller code is as follows:
$jsondata = "{\"employees\":[
{ \"lastName\":\"Doe\"},
{ \"lastName\":\"Smith\"},
{\"lastName\":\"Jones\"}
]}";
$data = json_decode($jsondata, true);
// var_dump($data['employees']);
$machinetags = $data['employees'];
if ($machinetags) {
$machinetags = $em->getRepository('VCycleMachineTagsBundle:MachineTag')->findOrCreateByTitles($machinetags);
}
foreach($machinetags as $machinetag) {
$photo->addMachineTag($machinetag);
}
$em->persist($photo);
$em->flush();
But when i run it, it gives me this error:
{
"code": 500,
"message": "An exception occurred while executing 'SELECT t0.id AS id_1, t0.title AS title_2, t0.created_at AS created_at_3 FROM machinetag t0 WHERE t0.title IN (?, ?, ?)' with params [[\"Doe\"], [\"Smith\"], [\"Jones\"]]:\n\nNotice: Array to string conversion"
}
hw to fix it please, such as $machinetags is an array
The function addMachine tag is as follows :
public function addMachineTag(MachineTag $machinetag)
{
$photoMachineTag = new PhotoMachineTag();
$photoMachineTag->setMachineTag($machinetag);
$photoMachineTag->setPhoto($this);
$this->photoMachineTags->add($photoMachineTag);
}

Related

Caused By : SQL(query) error or missing database. - In Flutter/Dart

I was trying to build an app that takes in the Title, Date, Link, Priority level and then displays them using Flutter and SQLite.
I originally built it without 'link' and it was working perfectly, but when I added the filed 'link' it gives me this error:
E/flutter ( 8491): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: DatabaseException(table task_table has no column named link (code 1): , while compiling: INSERT INTO task_table (title, date, link, priority, status) VALUES (?, ?, ?, ?, ?)
E/flutter ( 8491): #################################################################
E/flutter ( 8491): Error Code : 1 (SQLITE_ERROR)
E/flutter ( 8491): Caused By : SQL(query) error or missing database.
E/flutter ( 8491): (table task_table has no column named link (code 1): , while compiling: INSERT INTO task_table (title, date, link, priority, status) VALUES (?, ?, ?, ?, ?))
E/flutter ( 8491): #################################################################) sql 'INSERT INTO task_table (title, date, link, priority, status) VALUES (?, ?, ?, ?, ?)' args [math, 2021-04-28T00:00:00.000, google, Medium, 0]}
The code associated with this is distributed in two files: a database helper file that basically stores all the functions for database management
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:todo/models/task_model.dart';
class DatabaseHelper {
static final DatabaseHelper instance = DatabaseHelper._instance();
static Database _db;
DatabaseHelper._instance();
String taskTable = 'task_table';
String colId = 'id';
String colTitle = 'title';
String colDate = 'date';
String colLink = 'link';
String colPriority = 'priority';
String colStatus = 'status';
// task tables
// Id | Title | Date | Link | Priority | Status
// 0 '' '' '' ''
// 2 '' '' '' ''
// 3 '' '' '' ''
Future<Database> get db async {
if (_db == null) {
_db = await _initDb();
}
return _db;
}
Future<Database> _initDb() async {
Directory dir = await getApplicationDocumentsDirectory();
String path = dir.path + 'todo_list.db';
final todoListDb =
await openDatabase(path, version: 1, onCreate: _createDb);
return todoListDb;
}
void _createDb(Database db, int version) async {
await db.execute(
'CREATE TABLE $taskTable($colId INTEGER PRIMARY KEY AUTOINCREMENT, $colTitle TEXT, $colDate TEXT, $colLink TEXT, $colPriority TEXT, $colStatus INTEGER)');
}
Future<List<Map<String, dynamic>>> getTaskMapList() async {
Database db = await this.db;
final List<Map<String, dynamic>> result = await db.query(taskTable);
return result;
}
Future<List<Task>> getTaskList() async {
final List<Map<String, dynamic>> taskMapList = await getTaskMapList();
final List<Task> taskList = [];
taskMapList.forEach((taskMap) {
taskList.add(Task.fromMap(taskMap));
});
taskList.sort((taskA, taskB) => taskA.date.compareTo(taskB.date));
return taskList;
}
Future<int> insertTask(Task task) async {
Database db = await this.db;
final int result = await db.insert(taskTable, task.toMap());
return result;
}
Future<int> updateTask(Task task) async {
Database db = await this.db;
final int result = await db.update(taskTable, task.toMap(),
where: '$colId = ?', whereArgs: [task.id]);
return result;
}
Future<int> deleteTask(int id) async {
Database db = await this.db;
final int result =
await db.delete(taskTable, where: '$colId = ?', whereArgs: [id]);
return result;
}
}
And the second file is a database model file, which contains the database creation etc. :
class Task {
int id;
String title;
DateTime date;
String link;
String priority;
int status; // 0 - complete, 1- complete
Task({
this.title,
this.date,
this.link,
this.priority,
this.status,
});
Task.withId({
this.id,
this.title,
this.date,
this.link,
this.priority,
this.status,
});
Map<String, dynamic> toMap() {
final map = Map<String, dynamic>();
if (id != null) {
map['id'] = id;
}
map['title'] = title;
map['date'] = date.toIso8601String();
map['link'] = link;
map['priority'] = priority;
map['status'] = status;
return map;
}
factory Task.fromMap(Map<String, dynamic> map) {
return Task.withId(
id: map['id'],
title: map['title'],
date: DateTime.parse(map['date']),
link: map['link'],
priority: map['priority'],
status: map['status']);
}
}
This is my first time working with databases in flutter so any feedback would be greatly appreciated. Thank you
The error says that you don't have the column available in the table. The problem is that the db is not created every time you start the app. There are two solutions to your problem here:
For debug purposes, just delete the app and re-run the code, this will regenerate the database with the correct columns. WARNING: this is just for debug only, not for production.
For production, when you add changes on database, you have to increase the database version, in your case from 1 to let's say 2. Next, the openDatabase method has a parameter onUpgrade that will be called when the database version is upgraded, in your case from 1 to 2, here you'll have to run additional sql commands to update your table. Something like this:
await openDatabase(path, version: 1, onCreate: _createDb, onUpgrade: (db, old, newVersion) async {
if(old < 2) {
await db.execute("ALTER TABLE task_table ADD link TEXT");
}
});
Also do not forget to update your create table statement to add your new column there.
One scenario would be that you don't want to save the link in the db, in this case you'll have to remove it from json serialization (your toMap method) .

i see "405: Method Not Allowed" when trying following code on Python 3.8.3

https://tutorialedge.net/python/create-rest-api-python-aiohttp/
from aiohttp import web
import json
async def handle(request):
response_obj = { 'status' : 'success' }
return web.Response(text=json.dumps(response_obj))
async def new_user(request):
try:
print("AT Epoint" )
## happy path where name is set
user = request.query['name']
## Process our new user
print("Creating new user with name: " , user)
response_obj = { 'status' : 'success' }
## return a success json response with status code 200 i.e. 'OK'
return web.Response(text=json.dumps(response_obj), status=200)
except Exception as e:
print("AT EXCEPTION" )
## Bad path where name is not set
response_obj = { 'status' : 'failed', 'reason': str(e) }
## return failed with a status code of 500 i.e. 'Server Error'
return web.Response(text=json.dumps(response_obj), status=500)
Once you have implemented the listener function, register it with the aiohttp instance.
app.router.add_post('/user', new_user)
Source: TutorialEdge

How to resolve MetadataAPI giving 'System.CalloutException: IO Exception: Read timed out' error on setting recordType to lookupfield value

I am using metadata API to add picklist value('custom') in a field.I have a record type (AAM_T) created which has to be associated with value I have added to picklist, but as on running :
service.updateMetadata( new MetadataService.Metadata[] { recordType });
causing an error 'System.CalloutException: IO Exception: Read timed out'.
MetadataService.PickListValue objPickListValue = new MetadataService.PickListValue();
objPickListValue.fullName = 'custom';
objPickListValue.default_x = false;
MetadataService.RecordType recordType = (MetadataService.RecordType)
service.readMetadata('RecordType',
new String[] { 'Account.AAM_T'}).getRecords()[0];
MetadataService.RecordTypePicklistValue[] recordPickListType = recordType.picklistValues;
if(recordPickListType.size() > 0){
for(MetadataService.RecordTypePicklistValue rpk : recordPickListType) {
if(rpk.picklist == picklistToUpdate){
rpk.values.add(objPickListValue);
break;
}
}
try{
service.updateMetadata( new MetadataService.Metadata[] { recordType });
} catch(Exception ex){
system.debug('###getStackTraceString : '+ex.getStackTraceString());
//Result: System.CalloutException: IO Exception: Read timed out -- null
system.debug('###getMessage : '+ex.getTypeName()
+ ': ' + ex.getMessage() + ' -- ' + ex.getCause());
}
}
You can try this like any other webservice. worked to me
MetadataService.MetadataPort service = new MetadataService.MetadataPort();
service.timeout_x=120000;

How can I access sqlite database on a webserver in codename one

Pls How can I access sqlite database on the webserver in codename one? I can only use database API to access database on the device. In order to access this on the webserver I think is quite different thing. Pls I need a snippet code on this. Thanks
Use the code below, not tested and you may have to adjust it to suite your need. Leave a comment if there's an issue:
ConnectionRequest req = new ConnectionRequest() {
#Override
protected void handleException(Exception ex) {
//handle error
}
};
req.setUrl(YourURL);
req.setPost(true);
req.setHttpMethod("POST"); //Change to GET if necessary
req.setDuplicateSupported(true);
req.addArgument("argumentToSendThroughPostOrGet1", "value1");
req.addArgument("argumentToSendThroughPostOrGet2", "value2");
NetworkManager.getInstance().addToQueueAndWait(req);
if (req.getResponseCode() == 200) {
Map<String, Object> out = new HashMap<>();
Display.getInstance().invokeAndBlock(() -> {
JSONParser p = new JSONParser();
try (InputStreamReader r = new InputStreamReader(new ByteArrayInputStream(req.getResponseData()))) {
out.putAll(p.parseJSON(r));
} catch (IOException ex) {
//handle error
}
});
if (!out.isEmpty()) {
List<Map<String, Object>> responses = (List<Map<String, Object>>) out.get("response");
for (Object response : responses) {
Map res = (Map) response;
System.out.println(res.get("key"));
}
} else {
//handle error
}
} else {
//handle error
}
TEST JSON RESPONSE:
{
"response": [
{
"key": "I was returned",
}
]
}
EDIT:
To pass data from TextField:
req.addArgument("argumentToSendThroughPostOrGet1", myTextField.getText());
Based on your comment, you can read those arguments in PHP as simple as below:
$var1 = $_POST["argumentToSendThroughPostOrGet1"];
$var1 = $_GET["argumentToSendThroughPostOrGet1"]; // if GET method is used in Codename One
//Or use $_REQUEST which supports both methods but not advisable to be used for production
...
And you can use those variables in your php code normally.
Example of Usage with MySql Query:
class Connection {
function connect() {
$mysqli = mysqli_init();
$mysqli->real_connect("localhost", "username", "password", "databaseName") or die('Could not connect to database!');
$mysqli->query("SET NAMES 'UTF8'");
return $mysqli;
}
function close() {
mysqli_close($this->connect);
}
}
$connection = new Connection();
$mysqli = $connection->connect();
$mysqli->query("SELECT * FROM MyTable WHERE ColumnName LIKE '%$var1%' ORDER BY PrimaryKeyId ASC LIMIT 100");

Count result array to string conversion error in codeigniter

I am using this method in my model to get a count result from my database:
function members($group_id)
{
$this->db->where('group_id',$group_id);
$query = $this->db->query('SELECT COUNT(group_id) FROM member');
return $query;
}
And in my controller there is this method:
function total_members ()
{
$group_id = $this->input->post('group_id');
$this->load->model('Member_model');
$members = $this->Member_model->members($group_id);
echo $members;
}
And am getting this weird error which says:
Severity: 4096
Message: Object of class CI_DB_mysqli_result could not be converted to string
Filename: controllers/Payment.php
You need to return a result set which requires another call. In this case I suggest row(). Try these revised functions.
function members($group_id)
{
$this->db->where('group_id', $group_id);
$query = $this->db->query('SELECT COUNT(group_id) as count FROM member');
return $query->row();
}
function total_members()
{
$group_id = $this->input->post('group_id');
$this->load->model('Member_model');
$members = $this->Member_model->members($group_id);
if(isset($members))
{
echo $members->count;
}
}
Learn about the different kinds of result sets here
Try this
Model
function members($group_id) {
return $this->db->get_where('member', array('group_id' => $group_id))->num_rows();
}
Controller
function total_members() {
$group_id = $this->input->post('group_id');
$this->load->model('member_model');
$members = $this->member_model->members($group_id);
print_r($members);
}
In codeigniter there is num_rows() to count the rows. For more information check the documentation .

Resources