PDO prepared statement isn't working - php

I'm finding that my PDO MySQL insertion isn't working
The basic format of it is:
INSERT INTO `my_table` (id, email_hash, dob, 1, 6, 10) VALUES (?, ?, ?, ?, ?, ?)
It actually comes like this:
$InsertQuery = $db->prepare("INSERT INTO `my_table` (id, email_hash, dob, $NumbersString) VALUES (?, ?, ?, $QuestionMarkString)");
$InsertQuery->execute(array("$ID, $hashed_email, $dob, $YesNoString"));
The variable $QuestionMarkString fills in (correctly) the number of question mark placeholders.
The variable $YesNoString is a string of "1"s of appropriate length to act as markers in the database.
So even when I can see that the first part of the query successfully becomes formed as:
INSERT INTO `my_table` (id, email_hash, dob, 1, 6, 10) VALUES (?, ?, ?, ?, ?, ?)
... and the content of the execute array successfully becomes:
52, $2y$10$h9yXWUd8edQVMTSwZrX7T.pJ/C1pLDE9b081OtGmG6nbAtXr7lASK, 29062016, 1, 1, 1
.. the insert still doesn't happen. I get a PHP error saying:
PHP Warning: PDO::prepare(): SQLSTATE[42000]: 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 '1, 6, 10) VALUES (?, ?, ?, ?, ?, ?)' at line [etc]

It should be:
$InsertQuery->execute(array($ID, $hashed_email, $dob, $YesNoString));
Also, you cannot have columns that only contain digits:
Identifiers may begin with a digit but unless quoted may not consist solely of digits.
Therefore you need to wrap your columns in backticks `

my_table
doesn't contain the columns in $NumbersString (1,6,10)
or you need to add backticks to the column names
(`1`,`6`,`10`)

Try putting backticks (`) around the numeric column names:
INSERT INTO `my_table` (id, email_hash, dob, `1`, `6`, `10`) VALUES (?, ?, ?, ?, ?, ?);

Related

SQL return multiple tables

I am using PHP and MySQL
Let's say i have a query like
SELECT * FROM tablename WHERE smth=?
And i need to perform 10 of this queries on the same table, each with different 'smth' value.
Can i make SQL return multiple tables in one run, each for it's 'smth' value?
Use IN:
SELECT *
FROM tablename
WHERE smth IN (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
You can pass all ten values in as parameters.

PHP Prepared Statement SQL with where value

I am trying to run this query on an existing row in sql table:
if($stmt = $mysqli->prepare("INSERT INTO 4rounds (player2_name, player2_army1_name, player2_army2_name, player2_army3_name, player2_army4_name, player2_identifier, player2_stage, player2_army1_position, player2_army2_position, player2_army3_position, player2_army4_position) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) WHERE pairing_id = ?")) {
but it returns the error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE pairing_id = ?' at line 1
The query works without the WHERE clause. I think there is a problem with binding the parameter in this matter and I should use VALUE as well to bind it later but I can't seem to find anything online about binding a param in this manner.
These are the binds I am trying with:
$stmt->bind_param("ssssssssssss", $player2_name, $player2_army1_name, $player2_army2_name, $player2_army3_name, $player2_army4_name, $player2_identifier, $player2_stage, $player2_army1_position, $player2_army2_position, $player2_army3_position, $player2_army4_position, $pairing_id);
INSERT statements don't have WHERE clauses, and I'm not sure why you would want such a thing... Those only exist in SELECT and UPDATE queries, typically.

Codeigniter Insert with Select Query

Is there a way to make this Query work in MySQL Codeigniter
Basically is make a select inside a Insert to avoid double Query
I want to make an INSERT a row in a table called recibos_nomina but the field recibos_nomina.id_usuario is one a table called usuarios i have usuarios.rfc and i want to nest SELECT id FROM usuarios WHERE rfc = XXX to get the id and insert in recibos_nomina.id_usuario with one Query only, this is possible with MySQL but i don't know how to make it with codeigniter.
$this->db->trans_begin();
$this->db->query('insert into recibos_nomina(id_empresa, id_usuario, fecha, folio, total, uuid, url_xml, temporal, folio_fiscal, fechahora_certificado, csd_sat, sello_cfd, sello_sat, sello)
values(?, (SELECT id FROM usuarios WHERE rfc = ?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', array(
2,
//intval($this->post('id_empleado')),
$recibo->usuario->rfc,
date("Y-m-d"),
$recibo->folio,
$recibo->total,
$recibo->uuid,
$recibo->url_xml,
1,
$recibo->uuid,
//str_replace("T", " ", $recibo->fecha),
$recibo->fecha,
$recibo->csd_sat,
$recibo->sello_cfd,
$recibo->sello_sat,
$recibo->sello_cfd
));
$id_recibo = $this->db->insert_id();

Update all values except auto-increment field using PHP / MySql / PDO

I have a quick question...I am updating all values in a row using a prepared statement and an array.
When initially inserting, my statement looks like this (and works perfect)
$sql="INSERT INTO $dbtable VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
The first and last values are NULL as the first is an auto increment ID field and last is a timestamp field.
Is there a way to keep my UPDATE statement as simple as my INSERT statement like this...
$sql="UPDATE $dbtable SET (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) WHERE `announcements`.`id` = $id LIMIT 1";
I realize this does not work as is due to the first value being an auto increment field, is there a value I could put into my array to 'skip' this field?
This may not be the best way to describe my question but if you need more info, please let me know!
Thank you in advance!
UPDATE has no "implicit columns" syntax like INSERT does. You have to name all the columns that you want to change.
One alternative you can use in MySQL is REPLACE:
REPLACE INTO $dbtable VALUES (?, ?, ?, ?, ?, ...)
That way you can pass the current value for your primary key, and change the values of other columns.
Read more about REPLACE here: https://dev.mysql.com/doc/refman/5.6/en/replace.html
Note that this is internally very similar to #Devon's suggestion of using two statements, a DELETE followed by an INSERT. For example, when you run REPLACE, if you have triggers, both the ON DELETE triggers are activated, and then the ON INSERT triggers. It also has side-effects on foreign keys.
The solution I can think of doesn't involve an UPDATE at all.
DELETE FROM $dbtable WHERE id = $id;
INSERT INTO $dbtable VALUES ($id, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
Since you don't want to use the UPDATE syntax, this would delete the row and add a new row with the same id, essentially updating it. I would recommend wrapping it in a transaction so you don't lose your previous row if the insert fails for any reason.

PHP PDO prepared statement string length limit

I have a problem where the resulting prepared string is being limited in length:
My SQL statement goes like this:
INSERT INTO `empresa`
(`nombre`, `calle`, `colonia`, `ciudad`, `estado`, `pais` `codigo_postal`, `telefono`, `email`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
And it doesn't matter if I bind the values using bindParam(), bindValue() or even at the execute(), it's always trimmed at a certain lenght and I get this error:
Syntax error or access violation: 1064
And it complains about…
the right syntax to use near 'codigo_postal, telefono, email) VALUES ('algo', '1', '7', 'b', 'ha' at line 2'
If I reduce the parameters in length, say, to make 'algo' only 'al', the error is the same but 'ha' is shown up to 'hasd', if I specify only one or two colums so the complete statement is shorter it's executed correctly. What can I do? A workaround is performing an INSERT and then updating its fields with another statements, but that's just silly.
`pais` `codigo_postal`
You forgot comma.
Try this:
INSERT INTO `empresa`
(`nombre`, `calle`, `colonia`, `ciudad`, `estado`, `pais`, `codigo_postal`, `telefono`, `email`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)

Categories