INSERT INTO.....SELECT FROM - php

i want to put calory as the first value of fruits, i couldn't do it, can anyone help?
$sql = 'INSERT INTO fruits VALUES('', ?, ?, ?)'
SELECT calory
FROM diet
WHERE fruit = ?
';
$this->db->query($sql, array($a, $b, $c, $d));

The correct syntax is :
INSERT INTO "table1" ("column1", "column2", ...)
SELECT "column3", "column4", ...
FROM "table2"
in your case this should be :
INSERT INTO fruits (calory)
SELECT calory
FROM diet
WHERE fruit = ?
(if "calory" is the name of the column in the table "fruits")

You can't mix up INSERT ... SELECT and INSERT ... VALUES in one query. Just select the other values as constants in your SELECT statement and you'll be fine:
INSERT INTO fruits
SELECT calory, ?, ?, ?
FROM diet
WHERE fruit = ?

This
INSERT INTO fruits SELECT calory, ?, ?, ? FROM diet WHERE fruit = ?
should do it...

When you use placeholders for values, (in your case the question marks) you need to use ->prepare() and not ->query(). Also your SQL syntax is completely wrong.
At a guess I think your query should read something like...
$sql = "INSERT INTO fruits VALUES('', ?, ?, ?) WHERE fruit = ?"; // Create query string.
$sth = $this->db->prepare($sql); // Prepare the query.
$sth->bindValue(1,$a); // Bind question marks to values
$sth->bindValue(2,$b); // (I am assuming that a,b,c,d are in
$sth->bindValue(3,$c); // the correct order...
$sth->bindValue(4,$d);
$sth->execute(); // Execute the query to insert the data.

You mean you need to put the answer of select query into insert query ,please try this
$sql = 'INSERT INTO fruits VALUES('(SELECT calory
FROM diet
WHERE fruit = ?)', ?, ?, ?)'
';

Related

WHERE NOT EXISTS

I have a simple table with two columns "referralID" & "studentID"
I can add like this
$stmt = $pdo->prepare('INSERT INTO referralStudents (referralID,studentID) VALUES (?, ?)');
$stmt->execute([$myID,$studentID]);
I'm trying to get the WHERE NOT EXISTS statement to work. If there is already a row with both "referralID" & "studentID" don't add.
Both of these don't work can you show me where I'm going wrong?
$stmt = $pdo->prepare('INSERT INTO referralStudents (referralID,studentID) VALUES (?, ?) WHERE NOT EXISTS (SELECT * FROM referralStudents WHERE referralID = ? and studentID = ?")');
$stmt->execute([$myID,$studentID,$myID,$studentID]);
$stmt = $pdo->prepare('INSERT INTO referralStudents (referralID,studentID) VALUES (?, ?) WHERE NOT EXISTS (referralID,studentID) VALUES (?, ?)');
$stmt->execute([$myID,$studentID,$myID,$studentID]);
You need a SELECT statement and not VALUES to apply the conditions of the WHERE clause:
INSERT INTO referralStudents (referralID,studentID)
SELECT ?, ?
FROM dual
WHERE NOT EXISTS (SELECT * FROM referralStudents WHERE referralID = ? and studentID = ?)
You may remove FROM dual if your version of MySql is 8.0+.
See a simplified demo.
If the fields are empty i bet they are NULL. A field filled with NULL is existing but its content is NULL (NULL doesnt mean empty or non existing). Maybe this is what you need:
INSERT INTO refferalStudents (refferalID, studentID) VALUES (?,?) WHERE refferalID IS NULL AND studentID IS NULL

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();

How to return ID of existing row if there is a duplicate row during MySQL INSERT?

I have two tables: movies and genres, and a junction table movieOfGenre for many-to-many relationships between the movies and genres tables. Now, when I am using transactions to insert movies and genres into my database using PHP, genres were being created twice even if there was a duplicate. Then I updated the code with ...ON DUPLICATE KEY UPDATE... and now if there is an existing genre with the same name, the auto_increment ID of the existing genre is being updated when I use this transaction query:
mysqli_autocommit($connect, false);
$query_success = true;
$stmt = $connect->prepare("INSERT INTO movies (id, title, plot, rating, releaseDate, duration, language, country, posterUrl, trailerUrl) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssssssss", $defaultId, $title, $plot, $rating, $releaseDate, $duration, $language, $country, $poster, $trailer);
if (!$stmt->execute()) {
$query_success = false;
}
$movieId = mysqli_insert_id($connect);
$stmt->close();
foreach ($genres as $genre) {
$stmt = $connect->prepare("INSERT INTO genres (id, name) VALUES (?, ?) ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID()");
$stmt->bind_param("ss", $defaultId, $genre);
if (!$stmt->execute()) {
$query_success = false;
}
$genreId = mysqli_insert_id($connect);
$stmt->close();
$stmt = $connect->prepare("INSERT INTO movieofgenre (movieId, genreId) VALUES (?, ?)");
$stmt->bind_param("ii", $movieId, $genreId);
if (!$stmt->execute()) {
$query_success = false;
}
$stmt->close();
}
if ($query_success) {
mysqli_commit($connect);
} else { ?>
alert('Error adding movie.');
<?php mysqli_rollback($connect);
}
How do I write the query so that if during insertion there is an existing row with the same genre.name, it returns the ID of the existing row without updating it?
Thanks in advance.
genres.name should be a unique column:
CREATE TABLE genres
...
UNIQUE KEY name
use IGNORE - duplicate exception will not be thrown
INSERT IGNORE INTO genres (name) VALUES (?)
get the id by name:
SELECT id FROM genres WHERE name = ?
I'm not sure this help but you may want to check example below. Lazy to do php coding this days, But I have similar issue with MYSQL last time if I understand your issue correctly :P
INSERT INTO sample_table (unique_id, code) VALUES ('$unique_id', '$code')
ON DUPLICATE KEY UPDATE code= '$code'
Hope this resolve your problem

MySQLi prepared statements: insert increment of a value

Is it possible in any way to insert an increment of a certain column value ?
$stmt->$this->mysqli->prepare('INSERT INTO `users` ( `email`,`date_added`,`playCount`) VALUES ( ?, NOW(), ? )');
$stmt -> bind_param('si',$email, WHAT); // playCount++ somehow ...
$stmt -> execute();
I know I can use UPDATE to do that, but then I need to check if user exists first and then do INSERT and afterward UPDATE just for one column? There should be a better approach I think?
EDIT: UPDATE also won't work (won't prepare successfully-returns false: any ideas what might be wrong?)
$stmt = $this->mysqli->prepare('UPDATE `users` SET `newsletter` = ?, `date_last` = NOW(), points=points+?, WHERE `email` = ?');
(reference)
"INSERT INTO users ( `email`,`date_added`,`playCount`)
VALUES ( ?, NOW(), (SELECT MAX(playCount) from users)+1 );"

select and insert mysql

I would like to select one column from other table and insert it into another one.
I have column named image in table2 and want to select that and insert along with the below data to table1. is that possible?
$stmt = $mysqli->prepare("insert into table1 (username, firstname, lastname, image) ")
$stmt->bind_param('sss', $username, $fname, $lname);
$stmt->execute();
Yes, it's possible:
$stmt = $mysqli->prepare("
insert into table1 (username, firstname, lastname, image)
select ?,?,?,image from table2
");
...but I hope table2 has only one row!
You could do a INSERT ... SELECT query - http://dev.mysql.com/doc/refman/5.1/en/insert-select.html
INSERT INTO table1 (username, firstname, lastname, image)
SELECT ?, ?, ?, image FROM table2 t2 WHERE t2.image_id = ?
The first 3 ? are your bound params - $username, $fname, $lname
t2.image_id = ? represents the id/unique field of your desired img.

Categories