Python 3 MySQL using question mark placeholders - mysql

I am looking for a way to drop values from a list into a prepared SQL string which has question marks as placeholders. I have used this before in PyQT, but there I use the bindValue function. Using pymysql there looks to be no such function.
Here's an example of the type of SQL string I have prepared:
INSERT INTO my_table (`Column1Name`, `Column2Name`, `Column3Name`) VALUES (?,?,?);
I then have a list of values I am looking to insert into (or link to) the question mark placeholders.
my_values_list['string_1', '3', 'anothervalue']
Like I say, I have used this method before in PyQT, so I know this '?' placeholder method works, but without the bindValue function I can't see how to get it to work using pymysql.
Here's how I got it to work using PyQT's QSqlQuery bindValues function if it helps, where query.exec_() executes the SQL string:
if my_values_list:
[self.query.bindValue(i, my_values_list[i]) for i in range(len(my_values_list))]
self.query.exec_()

Here is an example of how to do this with PyMySQL:
query = 'INSERT INTO my_table (Column1Name, Column2Name, Column3Name) VALUES (%s, %s, %s);'
cur.execute(query, ('string_1', '3', 'anothervalue', ))
? is not a valid placeholder here, but %s is valid.

Maybe this post helps you, it's old but it's still mostly valid AFAIU, and I found it gave me a great overview:
What does a question mark represent in SQL queries?

Related

Writing prepared mysql queries with node mysql?

I am new to node.js I don't know whether this is a correct way to write prepared statements in node.js I am using this package https://github.com/mysqljs/mysql I know there are lots of question in stackoverflow covering this but no one suggested this way my colleague suggesting me to do this now I am doubting him..
let query = "INSERT INTO ??(??, ??, ??, ??) VALUES (?, ?, ?, ?)";
let inserts = [`user_active`, `UID`, `rep`, `point`, `status`, `${UID}`, rep, `${point}`, status];
query = mysql.format(query, inserts);
console.log(query) //Spits out the query
You can use ES6 templet string to form the query.
You are already using ES6 templet string in insert statement you can use that to form entire string
let query = ‘INSERT INTO user_active(UID, rep, point, status) VALUES(${UID}, ${rep}, ${point}, ${status})’;
Not able to get perfect syntax for ES6 templet string as I am answering from mobile, google proper syntax for ES6 templet string. Only thing wrong in my syntax is opening and closing quotes for string.

PHP Registration to MYSQL Database

I have a problem here..
Im currently building a website(blog) where I want people to be able to register. And I want that information to be sent to my MYSQL
This is some of the code:
<?php
$query="INSERT INTO Medlemmar(namn, epost)
VALUES("$_GET[namn]", "$_GET[epost]")";
if (!mysqli_query($mysql_pekare,$query))
{
die("Error: " . mysqli_error($mysql_pekare));
}
echo "Du har lagt till kunden I databasen";
?>
But for some reason i get error on the "VALUES" part.. That im missing a syntax.. WTF am i missing?! Been stuck with this for 1+ hours.. Just had to turn here, usually a quick response! Thanks!
edit: "Parse error: syntax error, unexpected T_VARIABLE"
There are syntax errors all over the place... This needs some work.
<?php
$query = "INSERT INTO Medlemmar(name, epost) VALUES(\"".$_GET['namn']."\", \"".$_GET['epost']."\")";
That should fix the query... You need to learn how to escape \" double quotes so they can be used in the actual query.
try
VALUES ('".$_GET[a]."', '".$_GET[b]."')
or ' and " exchanged.
You are forgetting the single quotation marks around each value
The way you're managing registration is extremely insecure. If you were to set the namn and epost value to a sql query (like SELECT FIRST (username) FROM user_table) then it would execute that as behalf of the original sql query.
if you set username to SELECT FIRST (username) FROM user_table then it would return the first username in the user_table
To avoid this from happening you can use prepared statements which means that you specifically assign a sql query with a placeholder value and then you apply a value to the placeholder.
This would mean that you force the sql query to only execute what you've told it to do.
E.g. You want to JUST INSERT into a table and only do that and nothing else, no SELECT and no table DROP well in that case you create the prepared INSERT query with a placeholder value like this.
$db = new PDO('mysql:host=localhost;dbname=database_name', 'database_user', 'database_user_password');
// Create the register statement for inserting.
// Question mark represent a placeholder for a value
$register = $db->prepare('INSERT INTO users_table (username, password) values (?, ?)');
// Execute the register statement and give it values
// The values need to be parsed over in a array
$register->execute(array("test_user", "test_password"));
I'm not the best at explaining but if you want to understand what EXACTLY is going on here then this is a pretty good article which explains it in more detail.

Can't read MySql String VALUES

Same code I used on Access.
Now I am using MySql on a server PC.
INSERT INTO doesn't work, but when SELECT statement only, check the commented code, it works, it displays what I am looking for, so what's wrong?
Your string values need quote marks like
VALUES ('Paderes','Jean', etc
Try this
VALUES ('Paderes', 'Jean', 'Fernandez', 'RND', 'Jean','1234')

Question mark in field name of SQL INSERT statement

This may be a futile question, but I will ask anyway. I have now learned that it is bad practice to use a question mark at the end of a field name, as is the case with the Paid? field in the following statement:
$sql = "INSERT INTO `tblAppeals`
(
`#`,
`Year`,
`Property#`,
`Paid?`,
`Outcome`,
`ResolvedBy`,
`AppealCategory`
)
VALUES (?,?,?,?,?,?,?)";
When I try to run the statement, I get an error because the question mark is not handled correctly. I haven't been able to find any workarounds to avoid having to go back and change the field name.
Is there any way I can keep the field name the same, Paid?, and still use it in the INSERT statement? Thanks.
It looks like its an issue with your query layer and not MySQL itself. That is, whatever is doing the bind params handling is eagerly looking for all ? in the SQL and not just whats in the VALUES part of the clause.
What database drive / query framework are you using?

SQL query fails to insert with same column count, works with fewer columns inserted

In the example here, NULL values are normally other variables I pass through. I tried to pass NULL to see if that was the problem as those are the only values that can be NULL, everything else is required.
mysql_query("INSERT INTO `imstillr_crm`.`customerinfo`
(`id`, `companyname`, `primarycontact`, `primaryemail`,
`prefphone`, `secondarycontact`, `secondaryemail`, `optionalphone`,
`department`, `website`)
VALUES
(NULL, '".$company."', '".$primarycontact."', '".$primaryemail."',
'".$prefphone."', 'NULL', 'NULL', 'NULL,
'".$department."', '".$website."')");
I just tried this with fewer variables and it worked. I'm kinda confused. I even inserted a record and copied the SQL string and added my variables.
I think you've made a mistake here:
'NULL, '".$department.
Presumably you intended
'NULL', ".$department."
BUT: this looks as though you are attempting to insert the literal text "NULL" into your database which I assume is not what you intend. NULL is a keyword so you can just use the bare word NULL wherever you are inserting a null value (so no quotes required around it).
There's more though, at the risk of distracting you from your current issue, you really should not execute SQL statements by composing a string as you are doing. This is how SQL injection attacks succeed. A better way is to use PDO with prepared statements. Here's a quick description of how to use it:
http://www.php.net/manual/en/pdo.prepared-statements.php
The main advantages are:
You remove the explicit dependency on Mysql created by the mysql_* functions
You can avoid SQL injection attacks.
Your code should be easier to read without the complex string composition
Just for completeness, here's how your code would look with PDO
$stmt = $dbh->prepare("INSERT INTO imstillr_crm.customerinfo (id, companyname, primarycontact, primaryemail, prefphone, secondarycontact, secondaryemail, optionalphone, department, website) VALUES (:id, :companyname, :primarycontact, :primaryemail, :prefphone, :secondarycontact, :secondaryemail, :optionalphone, :department, :website)");
$stmt->bindParam(":id", NULL);
$stmt->bindParam(":companyname", $company);
$stmt->bindParam(":primarycontact", $primarycontact);
...
$stmt->execute();
Notice how you don't need to put quotes around the values. They might contain various characters so as quotes, semi colons etc. and these won't cause any problems in your database (they may cause problems elsewhere in your app but that's another discussion).
I don't think you can put NULL in quotes. I think you need to remove the quotes around NULL otherwise MySQL (I'm guessing MySQL) will treat them as strings.
A ' is missing after the last NULL
Corrected code:
mysql_query("INSERT INTO `imstillr_crm`.`customerinfo` (`id`, `companyname`, `primarycontact`, `primaryemail`, `prefphone`, `secondarycontact`, `secondaryemail`, `optionalphone`, `department`, `website`) VALUES (NULL, '".$company."', '".$primarycontact."', '".$primaryemail."', '".$prefphone."', 'NULL', 'NULL', 'NULL', '".$department."', '".$website."')");
You have mixed up the ' and ,:
'NULL, '".$department."'
Should be:
'NULL', '".$department."'
Right before $department you have 'NULL, '" you probably want to move the quote in before the comma.