PDO Insert unknown sql errors - sql

I am trying to insert into my database, and the only problem I can find is the sql not being correct somehow. I tried searching up the errors, but they are confusing at to what they are.
$pdo = new PDO("mysql:host=$dbhost;dbname=$dbvideos;", $dbusername, $dbpassword);
$sql = "INSERT INTO Video ('Channel ID', 'Name', 'VideoDescription', 'VideoLocation') VALUES (:chanID, :vidName, :vDesc, :vLoc)";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(":chanID"=>$_POST['selectedChannel'], ":vidName"=>$_POST['videoName'], ":vDesc"=>$_POST['viddesc'], ":vLoc"=> $VideoLocation));
print_r($stmt->errorInfo());
With error output:
Array ( [0] => 42000 [1] => 1064 [2] => 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 'ID, Name, VideoDescription,VideoLocation) VALUES ('1', 'Testing Video', 'This is' at line 1 )
I pre-checked the variables (types match database, and they exist and with validation on previous page). The connection works fine. So SQL is the only error I can find.

I understand having no space in names- that one slipped my mind (I am usually on top of that, even when saving files). Some how removing the space and removing ' quotes made it work. (I originally used ' quoted because I saw some people use it so I though it would fix the problem).
Thank You Ryan Vincent.

Related

How to delete multiple entities using Doctrine QueryBuilder

I am working on a Symfony 2.8 based project to manage contact. The user can select from a list any number of contacts and should be able to delete all selected contacts at once. How can this be done in a single Query Builder statement?
// Contact entity uses a GUID as ID
$guids = array(...);
try {
$this->getEntityManager()->getConnection()->beginTransaction();
$qb = $this->getEntityManager()->getConnection()->createQueryBuilder()
->delete('AppBundle:Contact', 'c')
->where('c.guid in (:guids)')
->setParameter(':guids', array($guids, Connection::PARAM_STR_ARRAY));
log($qb->getSql());
$qb->execute();
$this->getEntityManager()->flush();
$this->getEntityManager()->getConnection()->commit();
} catch (\Exception $ex) {
// Rollback the transaction
$this->getEntityManager()->getConnection()->rollback();
}
1. Problem
Addressing the entity with AppBundle:Contact (which works without any problem when building a SELECT statement) does not work. This is the log output:
Query: DELETE FROM AppBundle:Contact c WHERE c.guid in (:guids)
Exception: Doctrine\DBAL\SQLParserUtilsException: Value for :Contact not found in params array. Params array key should be "Contact" in
2. Problem
Using the table name instead (->delete('contact', 'c')) does not work as well:
Query: DELETE FROM contact c WHERE c.guid in (:guids)
Exception: Syntax error or access violation: 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 'c WHERE c.guid in ('Array')'
3. Problem
Deleting a single entity does not work either:
->delete('contact', 'c')
->where('c.guid = (:guid)')
->setParameter(':guid', $guids[0]);
Query: DELETE FROM contact c WHERE c.guid = :guid
Exception: Syntax error or access violation: 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 'c WHERE c.guid = 'E7516B91-0549-4FFB-85F2-4BD03DC3FFC1''
What might be wrong her?
1st. Problem. Change setParameter line to the following, you don't need to use : in name of param.
->setParameter('guids', $guids);
Second problem - you should not use real table name if you're dealing with queryBuilder.
Third problem - your logic is not correct. If you want to delete single then
$qb = $this->getEntityManager()->createQueryBuilder()
->delete('AppBundle:Contact', 'c')
->where('c.guid = :guid')
->setParameter('guid', $guids[0]);
Additionally
I don't really know what doctrine version you're using, but
$this->getEntityManager()->getConnection()->createQueryBuilder() - seems wrong, because usually you're getting connection if you want to execute RAW SQL.
Try to change to
$qb = $this->getEntityManager()->createQueryBuilder()
And you need to use brackets around the variable only if it's array. Check code below
$queryBuilder->andWhere('r.id IN (:ids)')
->setParameter('ids', $ids);
Unless you want to execute raw SQL, you don't have to use your entity manager's connection, so you can replace $this->getEntityManager()->getConnection()->createQueryBuilder() by
$em->createQueryBuilder()
You could do something like
$qb = $this->createQueryBuilder()
->delete('AppBundle:Contact', 'c')
->where('c.guid in (:guids)')
->setParameter(':guids', $guids);
And if you want to log/execute it
$query = $qb->getQuery();
log($query->getSql());
$query->execute();
You also don't need to add the beginTransaction and rollback, if the query fails and an exception is thrown, doctrine will rollback automatically.

Create PostgreSQL table comment using a prepared statement

Is it possible to prepare a Postgres 'COMMENT ON' statement?
I have a program that allows users to create tables. I'd like to give them the option to add a description of the table's contents. As this data is coming from users, I'd like to use prepared statements.
Using Ruby and the 'pg' gem, I use the below to setup a Postgres connection and example data:
table_name = "test_shakespeare"
description = "Shakespeare's sonnets"
con = PG.connect(
:dbname => "poefy",
:user => "poefy",
:password => "poefy"
)
sql = "CREATE TABLE #{table_name} (example TEXT);"
con.exec(sql)
Here are my failed approaches, together with the errors they throw.
# ERROR: syntax error at or near "$1" (PG::SyntaxError)
sql = "COMMENT ON TABLE #{table_name} IS $1;"
con.exec(sql, [*description])
# ERROR: syntax error at or near "$1" (PG::SyntaxError)
sql = "COMMENT ON TABLE #{table_name} IS $1;"
con.prepare("comment", sql)
con.exec_prepared("comment", [*description])
# ERROR: could not determine data type of parameter $1 (PG::IndeterminateDatatype)
sql = "COMMENT ON TABLE #{table_name} IS '$1';"
con.exec(sql, [*description])
# ERROR: bind message supplies 1 parameters, but prepared statement "comment" requires 0 (PG::ProtocolViolation)
sql = "COMMENT ON TABLE #{table_name} IS '$1';"
con.prepare("comment", sql)
con.exec_prepared("comment", [*description])
It seems that preparation is not possible for this type of statement, and I should resort to SQL string manipulation. That being the case, what is the best way to go about this? The data is not sensitive or critical, and I am only really concerned with correctly represented quote marks and apostrophes.
Thanks in advance.
I assume ruby supports same statements as postgres, which does it for
Any SELECT, INSERT, UPDATE, DELETE, or VALUES statement
not COMMENT IS
It does appear that this is not possible.
So I went with the old "double all the single quotes" method.
safe_desc = description.gsub("'", "''")
con.exec "COMMENT ON TABLE #{table_name} IS '#{safe_desc}';"
This feels really hacky. But for now I'm marking it as the answer.
If there's a safer way, please let me know.

NS_ERROR_FAILURE in SQLite insert

I just bought a Kobo eReader which forces me to register at their website before the eReader functions. Seeing that I'm quite a privacy fundamentalist I refuse to register to read a couple books, so I went searching for an alternative. This brought me to this blogpost, which suggests to open the SQLite DB on the eReader and manually inserting a user with the following insert (formatted for readability):
INSERT INTO user (
UserID
,UserKey
,UserDisplayName
,UserEmail
,___DeviceID
,HasMadePurchase
)
VALUES (
‘5b8b0d65-b50f-4460-b6df-aca5e64f4882’
,’626d73ed-8382-4c1d-9750-cfe741c6e773’
,’a_name’
,’an_email_address’
,’01:23:45:67:89:ab’
,’TRUE’
);
So I found the sqlite database and I ran the query, but I get the following error message
SQLiteManager: Likely SQL syntax error: INSERT INTO user(UserID,UserKey,UserDisplayName,UserEmail,___DeviceID,HasMadePurchase) VALUES(‘5b8b0d65-b50f-4460-b6df-aca5e64f4882’,’626d73ed-8382-4c1d-9750-cfe741c6e773’,’a_name’,’an_email_address’,’01:23:45:67:89:ab’,’TRUE’);
[ unrecognized token: "4c1d" ]
Exception Name: NS_ERROR_FAILURE
Exception Message: Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [mozIStorageConnection.createStatement]
I looked at the structure of the user table, which is (as you can see below), slightly different from the the query.
CREATE TABLE user (
UserID TEXT NOT NULL
,UserKey TEXT NOT NULL
,UserDisplayName TEXT
,UserEmail TEXT
,___DeviceID TEXT
,FacebookAuthToken TEXT <= missing from query
,HasMadePurchase BIT DEFAULT FALSE
,IsOneStoreAccount BIT DEFAULT FALSE <= missing from query
,IsChildAccount BIT DEFAULT FALSE <= missing from query
,PRIMARY KEY (UserID)
)
As you can see there are three columns in the db which are not in the query. I don't think that this is the source of the error though.
Does anybody know what the error means and how I can solve the error? All tips are welcome!
Change the single quotes on the VALUES section to double quotes - the error references the middle portion of your string.
In addition to that, surround the column values in backticks and then everything works.

Can't figure out sql syntax error

I am trying to enter registration info into a mysql db through php, but the sql statement seems wrong. Can anyone please tell me what am I doing wrong?
INSERT INTO user(id,username,password,email,security_question,security_answer,face_photo,body_photo,user_salutation,user_firstname,user_middlename,user_lastname,parent_salutation,parent_firstname,parent_middlename,parent_lastname,gender,date_of_birth,address1,address2,country,state,city,pincode,country_code1,area_code1,phone1,country_code2,area_code2,phone2,alt_email,website,travel_within,passport,travel_companion,formal_education,other_qualification,known_languages,hobbies,about_you) VALUES('',some username,abcabc,abc#test.com,What is your first pet\'s name?,I don\'t know,'','',Mr.,sam,,fisher,Mr.,,,,Male,05/12/2009,test address1,,10,1073,16713,000000,00,00,00000000,,,,bcd#test.com,bcd#test.com,Within Country,on,on,none,none,spanish,none,none )
You don't have quotes around any of your string values:
..... ) VALUES('', 'some username', 'abcabc', 'abc#test.com'..... etc...

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!