Django raw sql insert: 'str' object has no attribute 'items' - sql

I have the following model:
class test_data_urls(models.Model):
url = models.CharField(max_length=200, db_index=True)
I want to insert a value into mysql:
cursor = connection.cursor()
url = "hiya"
cursor.execute("insert into my_table(url) values (%s)", (url))
I get an error:
'str' object has no attribute 'items'
This works:
cursor.execute("insert into my_table(url) values ('test')")
but I want to do it with %s. To me, it looks exactly like how I have always done this, so what am I missing?

Try using [ and ] instead of ( and ):
cursor = connection.cursor()
url = "hiya"
cursor.execute("insert into my_table(url) values (%s)", [url])
The reason that (url) does not work is because it's not a tuple, it's a single string. (url,) would be a tuple.

Related

knex json object WHERE condition

I have sql jsonb column in db named 'car' with structure
[{'brand':'audi', 'year':'2001'}] --> how to filter WHERE brand=audi?
this doesn't seem to be right:
return await db(db_table)
.select('*')
.whereRaw('car->>$.?? = ?', ['brand', 'audi']);
#felixmosh
Since your object is an array of objects, your suggested code won't work.
Try something like this:
return await db(db_table)
.select('*')
.whereRaw('car->>$[0].?? = ?', ['brand', 'audi']);
// ----------------^ this selects the first element of the array

PostgreSQL verify an empty array on json

I have the following row on select
jsonData
[]
[{"descricao":"falha na porta"}, {"descricao":"falha no ip"}]
[]
I have to Identify empty jsons, then manually add a value to it (eg row 1 and 3 ), I tried the following :
case when jsonData is null then cast('[{"descricao":"no error"}]' AS json) else jsonData end as opts
But the "is null" verification fails for this type of data (array of json), how to identify '[]' values in this case?
Note: I only have select permission on this db
You can use json_array_length()
when json_array_length(jsondata) = 0 then ...
Casting the json to text before comparison worked for this case :
" case when jsondata::text = '[]' "
Try this condition:
jsondata = JSON '[]'

Getting Trying to get property * of non-object when using get_results in WordPress

I have two tables that have a one-to-one relationship. one of them is wp_posts and wp_books Now I want to get post that related to specif book with this code:
function column_default($item, $column_name) {
global $wpdb;
switch ($column_name) {
case 'post':
$post_query = "SELECT * FROM $wpdb->posts WHERE id = {$item->post_id}
AND post_type='books' LIMIT 1 ";
$post = $wpdb->get_results($post_query, OBJECT);
return $post->post_title;
default:
return $item;
}
}
But I get this error:
Trying to get property 'post_title' of non-object
What's wrong? How can I fix this?
The problem is that get_results actually returns an array (see https://developer.wordpress.org/reference/classes/wpdb/get_results/) therefore you are trying to read 'post_title' from an array which doesn't have that property and in fact it is an array, not an object.
You should use https://developer.wordpress.org/reference/classes/wpdb/#select-a-row "get_row" for that

LastInserID from other table insert to table [duplicate]

I have a query, and I want to get the last ID inserted. The field ID is the primary key and auto incrementing.
I know that I have to use this statement:
LAST_INSERT_ID()
That statement works with a query like this:
$query = "INSERT INTO `cell-place` (ID) VALUES (LAST_INSERT_ID())";
But if I want to get the ID using this statement:
$ID = LAST_INSERT_ID();
I get this error:
Fatal error: Call to undefined function LAST_INSERT_ID()
What am I doing wrong?
That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().
Like:
$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();
If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:
$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();
lastInsertId() only work after the INSERT query.
Correct:
$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass)
VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();
Incorrect:
$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0
You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).
Like this $lid = $conn->lastInsertId();
Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php

how to get last inserted id - zend

I'm trying to get latest inserted id from a table using this code:
$id = $tbl->fetchAll (array('public=1'), 'id desc');
but it's always returning "1"
any ideas?
update: I've just discovered toArray();, which retrieves all the data from fetchAll. The problem is, I only need the ID. My current code looks like this:
$rowsetArray = $id->toArray();
$rowCount = 1;
foreach ($rowsetArray as $rowArray) {
foreach ($rowArray as $column => $value) {
if ($column="id") {$myid[$brr] = $value;}
//echo"\n$myid[$brr]";
}
++$rowCount;
++$brr;
}
Obviously, I've got the if ($column="id") {$myid[$brr] = $value;} thing wrong.
Can anyone point me in the right direction?
An aternative would be to filter ID's from fetchAll. Is that possible?
Think you can use:
$id = $tbl->lastInsertId();
Aren't you trying to get last INSERT id from SELECT query?
Use lastInsertId() or the value returned by insert: $id = $db->insert();
Why are you using fetchAll() to retrieve the last inserted ID? fetchAll() will return a rowset of results (multiple records) as an object (not an array, but can be converted into an array using the toArray() method). However, if you are trying to reuse a rowset you already have, and you know the last record is the first record in the rowset, you can do this:
$select = $table->select()
->where('public = 1')
->order('id DESC');
$rows = $table->fetchAll($select);
$firstRow = $rows->current();
$lastId = $firstRow->id;
If you were to use fetchRow(), it would return a single row, so you wouldn't have to call current() on the result:
$select = $table->select()
->where('public = 1')
->order('id DESC');
$row = $table->fetchRow($select);
$lastId = $row->id;
It sounds like it's returning true rather than the actual value. Check the return value for the function fetchAll