I'm trying to add a few Primary Keys from different tables as Foreign Keys to one Main table in a Query in php.
So far I got:
$result=$mysqli->query("INSERT INTO m_main (M_Id, M_T_Id, M_U_Id, M_P_Id, M_S_Id, M_Sp_Id, M_Ra_Id, M_F_Id, M_Hp, M_Rss, M_Kommentar)"
. "VALUES (DEFAULT, 123, 123, '".$_SESSION['sId']."' , 123, '".$_SESSION['Sp_Id']."', '".$_POST['fragestellung']."', 123,"
. "'".$_POST['hp']."', $rss, '".$_POST['kommentar']."')");
Every "123" I want to replace with an existing Primary key from other tables from my database.
How is this possible ?
You can use the INSERT ... SELECT syntax.
Something like this where anotherTable is the other table you want to insert from.
$result=$mysqli->query("INSERT INTO m_main (M_Id, M_T_Id, M_U_Id, M_P_Id, M_S_Id, M_Sp_Id, M_Ra_Id, M_F_Id, M_Hp, M_Rss, M_Kommentar) "
. "SELECT (DEFAULT, anotherTable.id, anotherTable.id, '".$_SESSION['sId']."' , anotherTable.id, '".$_SESSION['Sp_Id']."', '".$_POST['fragestellung']."', anotherTable.id,"
. "'".$_POST['hp']."', $rss, '".$_POST['kommentar']."') FROM anotherTable");
If needed you can also limit the number of inserted rows into m_main with a WHERE clause in the SELECT statement.
A long time ago I asked this question. Finally I found some time to answer it in case anybody has the same problem. Don't know why I wanted to make it so complicated. Subquerys where the answer:
$result=$mysqli->query("INSERT INTO m_main (M_Id, M_T_Id, M_U_Id, M_P_Id, M_S_Id, M_Sp_Id, M_Ra_Id, M_F_Id, M_Hp, M_Rss, M_Kommentar)"
. "VALUES (DEFAULT, (SELECT MAX id FROM title), (((AND SO ON...)))
Related
I'm creating function (PHP) which has to run every few hours and update some DB table.
1. If row isn't exist - INSERT new row
2. If row exist - UPDATE the current row
I want to write it the easiest and simplest way cause I'll do it for several tables.
You use the insert . . . on duplicate key update statement:
insert into dbtable(cols, . . . )
select <values here >
on duplicate key update col2 = values(col2), col3 = values(col3);
It is documented here.
EDIT:
Assuming you have some unique key on animals, your query would look something like:
insert into animals(animal_id, animal_name)
select #animal_id, #animal_name
on duplicate key update animal_name = values(animal_name);
I can see that this question gets asked a lot and I've tried following some answers that people said that worked for them but still it is not working for me.
I want to insert into my DB a variable number of elements. Here is my code:
$actual_id = $db->insert_id;
$sql = array();
foreach( $relacionado as $row ) {
$sql[] = '('.$actual_id.', '.$row.')';
}
$query2 = 'INSERT INTO relaciones (id, relacionadocon) VALUES '.implode(', ', $sql);
echo $query2;
$result2 = $db->query($query2);
if($result2){
echo "<p>".$db->affected_rows."fields inserted</p>";
}else{
echo "<p>Error</p>";
}
The thing is it works when I give it only one element but returns an error when there are more elements. I tried adding ", " instead of "," between the elements but nothing happens...
May it be because of the configuration of MySQL? Because I can't think on anything else as it seems to work for other people...
THanks!
EDIT: This is the result for echo $query2: INSERT INTO relaciones (id, relacionadocon) VALUES (65, 12), (65, 26)
EDIT2: I created the table using phpmyadmin. There are 2 tables. The first one registers information and uses an autoincreasing ID. So, the colums are ID, Title and Comment. But every comment is related to 1 or more comments. That is why there is another table that has 2 colums: ID and RelatedTo. When, for example, comment number 5 is created, you can relate it with comments 1, 2 and 3. That is why the INSERT should pass: (5,1), (5,2), (5,3). Once again, if I only had (5,1), it would work. I didn't give a primary key to the ID of the second table, only to the first.
I'm thinking the ID field is the primary key and shouldn't be written to. Can you try and run INSERT INTO relaciones (id, relacionadocon) VALUES (65, 12), (65, 26) within phpmyadmin to see what the result is?
I am trying to merge contents of two tables into one (sortedArrivals) using the following code: I do not want the Primary Key id's (here called flightShed.id) to be inserted.
$sql = "INSERT INTO sortedArrivals
SELECT flightSched.id,
flightSched.timePeriod,
flightSched.depOrArriv,
flightSched.flightNo,
flightSched.airline,
flightSched.dest,
flightSched.origin,
flightSched.depature,
flightSched.don,
flightSched.arrivalTime,
flightSched.status
FROM flightSched ";
if (!$mysqli->query($sql))
{
echo $counter . "<br>" ;
die('Error: ' . $mysqli->error);
}
However I would like a incrementing Primary Key. When I try inserting the contents of the next table I get: the following error message:
Error: Duplicate entry '9' for key 'PRIMARY'
how do i achieve this?
Any help is appreciated.
Name the columns you want to insert into
INSERT INTO sortedArrivals (timePeriod, depOrArriv, flightNo, airline,
dest, origin, depature, don, arrivalTime, status)
SELECT timePeriod,
depOrArriv,
flightNo,
airline,
dest,
origin,
depature,
don,
arrivalTime,
status
FROM flightSched
I do not want the Primary Key id's (here called flightShed.id) to be inserted.
Well then don’t select them …
However I would like a incrementing Primary Key.
… but select just NULL instead in their place; a NULL value for an autoindex column will automatically increase the ai counter.
In my Document table I have:
id (auto int index),
user_id (P.key and links to other table),
Doc_Name,
abstract
When I use the code below, it just inserts another row so I have two user_id's the same when it should have updated. Obviously the id just carries on in number as it is auto int and I'm not sure if this has something do with why it won't work.
$the_query = sprintf("INSERT INTO `document` (`user_id`,`Doc_Name`,`abstract`)
VALUES ('%d','%s','%s')",'$user_id', '$Doc_Name', '$abstract')
ON DUPLICATE KEY UPDATE
user_id=user_id+'$user_id',
Doc_Name=Doc_Name+'$Doc_Name',
abstract=abstract+'$abstract' "
);
Cargo cult programming? Using sprintf() without any % placeholders is just.... WRONG. As well, why the addition on the updated fields?
MySQL uses concat() for concatenation. + is purely a mathematical operation. Doing 'a' + 'a' does NOT give you aa, you'll get 0.
if user_id is unique field in your table, your query should look like this:
$query = sprintf("
INSERT INTO
`document`(`user_id`, `Doc_Name`, `abstract`)
VALUES
('%s', '%s', '%s')
ON DUPLICATE KEY UPDATE
`Doc_Name` = VALUES(`Doc_Name`),
`abstract` = VALUES(`abstract`)
", $user_id, $Doc_Name, $abstract);
I am getting this error here is my code
if(isset($_POST['submit']))
{
$projTit=mysql_escape_string($_POST['projecttitle']);
$projCat=mysql_escape_string($_POST['projectcategory']);
$budget=intval(mysql_escape_string($_POST['budget']));
$description=mysql_escape_string($_POST['editor1']);
$query=sprintf("insert into projects value('%s','%s','%s',%d)",
$projTit,$description,$projCat,$budget);
if (!mysql_query($query)){
die('Error: ' . mysql_error());
}
echo '<p class="record">Your Record has been Added<p>';
}
?>
I have tried to write %d in '' but still not working.
Your table has five columns. However, you are not providing a value for the Project_Id column. This gives you the error you mentioned.
I understand that you're not providing a value since it's likely a PRIMARY KEY that autoincrements. To tell MySQL that you are intentionally not passing a value for that column, you should add NULL as the first value.
value(NULL, '%s','%s','%s',%d)
However, you really should specifically name which columns you are inserting into in case you add a new column at a future date.
INSERT INTO projects (col1, col2, col3, col4) value ('%s','%s','%s',%d)
You should really specify the column names or your app will break if you add a column later, even if it has a useable default value:
INSERT INTO projects
(Project_Title, Project_Description, Project_Category, Project_Budget)
VALUES
(...)
Especially since you have an auto_increment ID column it makes sense; otherwise you'd always have to specify it as NULL in your query.
The easiest (but also ugliest) fix would thus be:
$query=sprintf("insert into projects value (null, '%s','%s','%s',%d)",
$projTit,$description,$projCat,$budget);
The good fix would be this:
$query = sprintf("
INSERT INTO projects
(Project_Title, Project_Description, Project_Category, Project_Budget)
VALUES
('%s', '%s', '%s', %d)
", $projTit,$description,$projCat,$budget);
By the way, consider using PDO - then you can use something similar to a format string but don't have to deal with escaping.
try naming the columns you want to fill like
insert into projects (col1, col2, col3) values (...)