web.py db.insert() doesn't work - sql

I use db.insert() to insert data to database, the code is something like this,
db.insert('categories', name=cate_name, description=desc, _test=True)
but it doesn't work, the data can't not be found in table 'categories' after the code is execute, and no exceptions by the way.
Anybody know why this happened?

_Test variable stands for debug purposes.
It lets you get SQL statement instead of executing one.
It means that your command
result = db.insert('categories', name=cate_name, description=desc, _test=True)
will not execute anything on your DB. It will only return a string:
"INSERT INTO categories (name, description) VALUES ('cate_name value', 'desc value')"
If you want to make a real query, you need to remove it:
db.insert('categories', name=cate_name, description=desc)
It should work.

remove _test=True or set _test=False

Related

Using the " ' " mark as part of the data

I am trying to create an insert statements that will allow the " ' " mark to be used as data, and having problems finding a reference to it. My current statement:
$sql = "INSERT INTO turnover(tail, discription, date) values ('$tail', '$discription', '$date')";
How ever when i put though this sample data i get:
INSERT INTO turnover(tail, discription, date) values ('173AB', 'No Dying MEL's tonight.', '05-14-2018')
If i remove the ' then it works fine. It seems i saw something a long time ago on it, but cannot find it.
Thanks in advance for any information that anyone can offer.
Best practice: Use prepared statements. Asuming you are using PHP: http://php.net/manual/en/pdo.prepared-statements.php
Alternatively you would apply some sort of escaping, like mysqli_real_escape_string().
Take care not to mix PDO and MySQLi functions, and do not in any case use mysql_*() functions.
INSERT INTO turnover(tail, discription, date) values ('173AB', 'No Dying MEL''s tonight.', '05-14-2018')

In statement with parameters in Crystal Report Command object

I am trying to modify the code of an exsisting SQL report. This report uses a command object. Currently the SQl codes says the following:
WHERE **dept.definition_id ={?Measure}**
AND (({?Period Interval}=2
AND dept_qd_later.sum_facts_id IS NULL
AND dept_qd.DENOMINATOR_QUARTER IS NOT NULL)
OR ({?Period Interval}=3
AND dept_md_later.sum_facts_id IS NULL
AND dept_md.DENOMINATOR_MONTH IS NOT NULL))
LAST
I would like to modify the "Measure Parameter" to accept multiple values. I have updated the command parameter box to accept multiple values. I have tried to modify the SQL to the below in statement:
WHERE **dept.definition_id in({?Measure})**
AND (({?Period Interval}=2
AND dept_qd_later.sum_facts_id IS NULL
AND dept_qd.DENOMINATOR_QUARTER IS NOT NULL)
OR ({?Period Interval}=3
AND dept_md_later.sum_facts_id IS NULL
AND dept_md.DENOMINATOR_MONTH IS NOT NULL)))
LAST
However, when I try to insert multiple measure IDs, the report does not run. Can someone help me figure out what I am doing wrong? I am a Crystal novice so please respond in plain language. Thanks!
I think David is right. I tried something similar with a command object and it works when entering a comma separated list into the parameter prompt. Which means that you don't need to set the "allow multiple values" option on the parameter.
If the field were a string, you would have to enter the values with quotes as if they were part of the SQL statement.

Php mysql statement with set and select

I have a weird problem, when i use the query on phpmyadmin, it works. but when i use using a php script it returns an error.
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in
I tried to troubleshoot and discovered that the problem lies with the set statement.
this is my example code.
$sql = 'set #rank=0; select * from user;';
Please help somebody.
First Run
$sql = set #rank=0;
it will store value of rank
then run:
select * from user;
In sort you need to run both queries separately .
set statement stores values. that can be used by next executing query,
like code below :
$sql ="SET #id:=0";
$Executives=$DB->exec($sql);
$sql = "SELECT #id:=#id+1 as id,pes.* FROM profile_executive_summary as pes where profile_id=".$pid;
$Executives=$DB->fetchAssoc($sql);
See what mysql_error returns after you run mysql_query('...'). That might help. In general, mysql_query only permits one query. You can't separate them by newlines or semicolons. mysqli will do it for you though.

CodeIgniter - continue on SQL error?

Basically I have a table with a couple of columns marked Unique. I have a script that dumps a bunch of values into the table with a command like this:
$this->db->query("INSERT INTO `table` (`col1`, `col2`, `col3`) VALUES (`val1`, `val2`, `val3`)");
Every so often my script will try to insert a row which would violate the uniqueness of one of the columns. However, instead of causing the script to abort with a database error, I'd like it to continue, possible outputting a little message. Basically I'm looking for the codeigniter equivalent of
mysql_query("INSERT blah blah blah") or print("fail");
Thanks!
Mala
Yeah, took me a while too and annoyed the hell out of me:
$db['default']['db_debug'] = FALSE;
... in config/database.php - disables the error page.
After a query ran, use this to check for an error:
if (!empty($this->db->_error_message())) {
echo "FAIL";
}
I know you already have a solution, but thought this might be useful for others viewing this question as well.
Let the database do the work for you:
$this->db->query("INSERT IGNORE INTO `table` (`col1`, `col2`, `col3`) VALUES (`val1`, `val2`, `val3`)");
When you use INSERT IGNORE, things like duplicate key errors become warnings instead of errors, which let your queries run without interrupting the flow of your script.
You could then do a
SHOW WARNINGS;
after all the queries have run to see what warnings occurred.
http://dev.mysql.com/doc/refman/5.1/en/insert.html

How can I get a null field from the Twitter API to play nice with my database?

Forgive me if I could have any sort of fundamental error here. I'd imagine there's something simple I'm missing. I'm looking to store Twitter updates in a database with only a few fields: an auto-increment index, the time posted, the actual status update & the user id the update is in reply to.
I'm simply storing this last field so I can provide a method of filtering out replies.
But it appears that my SQL code is throwing an error. As of this writing, the SQL properly inserts the two most recent updates, which are both replies to another user and, therefore, have data in the in_reply_to_user_id field. But on the third update, which is not in reply to anyone, I get the following error:
Error Number: 1064
You have an error in your SQL syntax;
check the manual that corresponds to
your MySQL server version for the
right syntax to use near ')' at line 1
INSERT IGNORE INTO updates (time,
status, postid, reply) VALUES
(1260070319, 'I guess Johnny Cash knew
what he was talking about in that \"A
Boy Named Suh\" song. That guy is both
fast and mean.', '6389320556', )
Twitter's API states no default value for this parameter. I tried the same query with the "favorited" parameter, and it correctly labeled each row with "false" in my database. So I'm assuming my problem is with inserting an empty string.
For what it's worth, here is my CodeIgniter method:
function insert_tweet($tweet){
foreach($tweet as $t) {
$when = strtotime($t->created_at);
$status = $t->text;
$postid = $t->id;
$reply = $t->in_reply_to_user_id;
$sql = 'INSERT IGNORE INTO updates (time, status, postid, reply) VALUES (?, ?, ?, ?)';
$this->db->query($sql, array($when, $status, $postid, $reply));
}
}
Any help you could give would be great! I hope I've provided enough information!
More info: I should also note that CodeIgniter is throwing the following error:
A PHP Error was encountered
Severity: 4096
Message: Object of class stdClass
could not be converted to string
Filename: database/DB_driver.php
Line Number: 598
In the off chance that this proves some sort of CI idiosyncrasy to be at fault.
I don't know php but in asp.net style pseudo code i would do this...
$this->db->query($sql, array($when, $status, $postid, string.IsNullOrEmpty($reply) ? null : $reply));
Hopefully you can adapt, just need to deal with the empty parameter.
I don't speak codeigniter, but I can tell you how to fix your problem.
You have two options
Check is the string empty, if so, instead of having a blank value, put in the null keyword.
Check is the value empty, if so, leave that column out of the insert statement's cloumns and values.
Hope this helps
I'm not sure about codeigniter (never used it) but I know that you will need to get the null value to appear as NULL
function insert_tweet($tweet){
foreach($tweet as $t) {
$when = strtotime($t->created_at);
$status = $t->text;
$postid = $t->id;
$reply = (is_null($t->in_reply_to_user_id) ? 'NULL' : $t->in_reply_to_user_id);
$sql = 'INSERT IGNORE INTO updates (time, status, postid, reply) VALUES (?, ?, ?, ?)';
$this->db->query($sql, array($when, $status, $postid, $reply));
}
}
I'm not sure if that will produce the desired SQL:
INSERT IGNORE INTO updates (time, status, postid, reply) VALUES (1260070319, 'I guess Johnny Cash knew what he was talking about in that \"A Boy Named Suh\" song. That guy is both fast and mean.', '6389320556', NULL)
edit Also make sure that the field in the database can be null.
Hope this helps..
Why not alter the last column and make it default to NULL?
When you want to insert some record without this field you just ignore it in the 'INSERT' statement.
And be sure not to put a pending comma between the last column value and the right parenthisis.
:)
You're coming from the CodeIgniter forums right? I think the issue is coming from your Twitter library. Can you post that code? For somereason, it's returning a NULL status as an Object, which it shouldn't do.
Hey guys, the answers here seemed to be close, but no cigar. I got some help from the great folks on the CodeIgniter forums, and here's what I came up with:
$reply = (is_null($t->in_reply_to_user_id) || is_object($t->in_reply_to_user_id) ? ‘NULL’ : $t->in_reply_to_user_id);
Essentially, like Zack said, it is returning the empty field from the Twitter API as an empty object instead of null. So I needed to check if this is either null or an object, then return NULL. And if not, return the user_id string.
Thanks a ton for your help!