php, pdo mysql can't insert with inner join - php

So I'm a little stuck with the following. I have two tables, projects and change.
Projects:
- id
- title
- description
- datecreated
Change:
- id
- title
- description
- projectid FOREIGN KEY
- datecreated
i can't figure out how to
insert into change (name, description, projectid) value (:name, :description, :projectid)
select id from project
where name = $name
important - the name and description in the insert are provided by php variables using a form.
important - must use PDO
Actual Code:
$sql = "INSERT INTO change (title, description, project_id) SELECT :title, :description, id FROM project WHERE title = :project_title";
$query = $db->prepare($sql);
$query->execute(array(":title" => $title, ":description" => $description, ":project_title" => $created));
This is what I did in the end but Barmar gets the point for help on this and another question.
$sql = "INSERT INTO `change` (`title`, `description`, `project_id`) SELECT :title, :description, id FROM project WHERE title = :project_title";
$query = $db->prepare($sql);
$query->execute(array(":title" => $title, ":description" => $description, ":project_title" => $created));

When you insert, you either use a values clause or you use select to specify the source of the data. You can't use both.
You want:
INSERT INTO `change` (`title`, `description`, `projectid`)
SELECT :title, :description, id
FROM project
WHERE title = :project_title

Related

Why deos PDO SELECT Work but BASIC INSERT fails?

I have connected to the db and able to update a record.
I have a variable named "action" that is either "update" or "add".
I use it in a switch statement to set my query to either "SELECT" or "INSERT".
SELECT statement works.
INSERT statement does not.
I get this error on $pdo->execute($data).
PHP Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in ...
PDOStatement->execute(Array)
The error is thrown by the PDOStatement
Here is what I have tried, seems pretty straight-forward, but i'm struggling with it.
$data = [
'firstName'=> $firstName,
'lastName'=> $lastName,
'badge'=> $badge,
'department'=> $department,
'image'=> $image,
'active'=> $active,
'stars'=> $stars,
'email'=> $email,
'primary_key'=> $primaryKey,
];
$sql = "INSERT INTO `team`
(`primary_key`,`firstName`, `lastName`, `badge`, `department`, `image`, `active`, `stars`, `email`)
VALUES
(NULL, :firstName, :lastName, :badge, :department, :image, :active, :stars, :email)";
$pdo->prepare($sql);
$pdo->execute($data); <- error is here
When I simply echo my $data array to see if there is something odd. I don't see anything based off all the sites, I've read.
//$data array DATA
primary_key =
firstName = test
lastName = test
badge = 9000
department = marketing
image = 9000.jpg
active = 1
stars = 0
email = tester#test.com
primary_key in db is auto-increment
primary_key is $_post[] on update query and NULL insert query (auto increment db column)
Any errors that would prevent this INSERT query from working that you can see? I'm stuck. I know it the array has 9 variables, there are 9 fields to insert, and 9 values listed.
I know it the array has 9 variables, there are 9 fields to insert, and 9 values listed.
Count the parameters. There are 8 of them. The array includes a value called primary_key for which there is no parameter in the query.
primary_key in db is auto-increment
Then don't insert a value for it:
$sql = "INSERT INTO `team`
(`firstName`, `lastName`, `badge`, `department`, `image`, `active`, `stars`, `email`)
VALUES
(:firstName, :lastName, :badge, :department, :image, :active, :stars, :email)";
And remove primary_key from the $data array.

Retrieve first insert Id from a query and insert into multi query is not working [duplicate]

This question already has answers here:
Retrieve id of each INSERT statement in multi query
(5 answers)
Closed 3 years ago.
I've been working with this project, now am stuck where i have to insert the id of the first query of which it identifies the relations of that table to others, i want the id of the first query to be saved as a variable and then be inserted into the following queries
I've tried to set value to be used but its not working, as i want all these to work in one multi-query, down here are some code of the queries
$query = "INSERT INTO guests (
user_id,
first_name,
last_name,
nationality,
status,
sign_up)
VALUES (
'$user_id',
'$first_name',
'$last_name',
'$nationality',
'$status',
NOW());";
$query = "SELECT #last_id := LAST_INSERT_ID();"
$query .= "INSERT INTO bookings (
user_id,
guest_id,
coming_from,
going_to,
date_in,
date_out,
sign_up)
VALUES (
'$user_id',
#last_id,
'$coming_from',
'$going_to',
'$date_in',
'$date_out',
NOW());";
$query .= "INSERT INTO preference (
guest_id,
prefer,
alergy,
sign_up)
VALUES (
#last_id,
'$prefer',
'$alergy',
NOW());";
$query .= "INSERT INTO rooms (
user_id,
guest_id,
room_number,
room_type,
room_price,
sign_up)
VALUES (
'$user_id',
#last_id,
'$room_number',
'$room_type',
'$room_price',
NOW())";
if(mysqli_multi_query($conn, $query))
{
echo "Guest Received successfully!";
} else {
echo "Failed! Data input error!";
}
}
i expected it to fetch the first query guest id and insert it into #last_id column, Kindly any ideas?
On occasion, I've had to use this:
SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES WHERE table_name = 'tablename'
or
SELECT AUTO_INCREMENT FROM information_schema.tables WHERE table_name = your_tablename' AND table_schema = DATABASE( ) ;
Perhaps that will work for you
References:
https://dev.mysql.com/doc/refman/8.0/en/show-table-status.html
https://php.net/manual/en/mysqli.insert-id.php

INSERT INTO table VALUES - mysql_query to PDO

trying to insert values from an old mysql_query using the new PDO and can't seem to get it. Here's the old code that works with the old method:
$query = mysql_query("INSERT INTO videos VALUES ('','$title',time(),'0','$length','','$name','$cat','$reciter','$genre')");
I've tried variations of the following code taken from another question on stack, but nothing that works for me.
$query = "UPDATE people
SET price=?,
contact=?,
fname=?,
lname=?
WHERE id=? AND
username=?";
$stmt = $dbh->prepare($query);
$stmt->bindParam(1, $price);
$stmt->bindParam(2, $contact);
$stmt->bindParam(3, $fname);
$stmt->bindParam(4, $lname);
$stmt->bindParam(5, $id);
$stmt->bindParam(6, $username);
$stmt->execute();
the first value to be inserted is an auto increment value in the db. I am at a loss as to how to write that with the new PDO. Then the third is an attempt at a timestamp. All others are values that exist in the script already.
So this is more along the lines of what I'm looking for.. Its what I have now, but doesn't work.
$sql = "INSERT INTO videos (id, title, timestamp, views, length, image, vid_url, cetegory, reciter, genre)
VALUES (:id, :title, :timestamp, :views, :length, :image, :vid_url, :category, :reciter, :genre)";
$query = $DBH->prepare($sql);
$results = $query->execute(array(
":id" => '',
":title" => $title,
":timestamp" => time(),
":views" => '0',
":length" => $length,
":image" => '',
":vid_url" => $name,
":category" => $cat,
":reciter" => $reciter,
":genre" => $genre
));
If id is an autoincrement, don't pass it to your query. If you specify a value to be inserted to an autoincrement table, sql will attempt to insert that value. so don't include it in the query, let SQL do that.
Secondly, if the third field is a timestamp, set the default to
CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
SQL will update the timestamp automatically on update or insert (if you only want it on insert just put CURRENT_TIMESTAMP. then you also can drop that row.
You can also drop the images row if you aren't inserting anything there either, no point to put something in the query if you're not using it!
Also, the key PDO looks for doesn't have the colon (:) so if your item is :title, the array key will be just 'title'. So, your code should look something like:
$sql = "INSERT INTO videos ( title, views, length,, vid_url, cetegory, reciter, genre)
VALUES (:title, :views, :length, :vid_url, :category, :reciter, :genre)";
$query = $DBH->prepare($sql);
$results = $query->execute(array(
"title" => $title,
"views" => '0',
"length" => $length,
"vid_url" => $name,
"category" => $cat,
"reciter" => $reciter,
"genre" => $genre
));

php-mysql-pdo: execute not working after prepare when inserting

I have following lines:
$sql = "INSERT INTO news (title, content) VALUES :title, :content";
$pre = $this->prepare($sql);
$pre->bindValue(":title", "xxx");
$pre->bindValue(":content", "yyy");
$pre->execute();
I get no error, but the query is also not executed (i checked the query log).
I tried following changes desperately:
$t="xxx" and $pre->bindValue(":title", $t); (the same also for y)
$sql = "INSERT INTO `news` (`title`, `content`) VALUES :title, :content";
$sql = "INSERT INTO `news` (`title`, `content`) VALUES ':title', ':content'";
Nothing changes. Funny thing is i get no response, no warning, no error just nothing.
But the query is not executed.
I found similar posts but non of them solved my problem.
(about $this ... The code is in a class extended from PDO class.)
try this, your values should be wrapped inside the values()
"INSERT INTO news (title, content) VALUES (:title, :content)";
instead of
"INSERT INTO news (title, content) VALUES :title, :content";
Try: "INSERT INTO news (title, content) VALUES (:title, :content)";
You must surround the insert values with parentheses. 

mysql insert into and select in prepared statement

how do I combine the mysql insert and select statement into a prepared statement?? Will this part of the code help me to duplicate information into a database when I hit the "copy" button?
Thanks.
INSERT INTO assignment_speeches_copy (id, subject, body, tags, image)
SELECT * FROM assignment_speeches
WHERE id = $id";
$stmt = $mysqli->prepare("INSERT INTO assignment_speeches_copy VALUES (?,?,?,?,?)"); (how do I continue?)
You don't have to combine anything. INSERT ... SELECT is a simple statement....
$stmt = $mysqli->prepare(
"INSERT INTO assignment_speeches_copy (id, subject, body, tags, image)
SELECT (id, subject, body, tags, image)
FROM assignment_speeches
WHERE id = ?"
);

Categories