I'm trying to insert an item into a table using both posted variables and something from another table. I'm not quite sure where I am going wrong because nothing is being added to the table. I'm super confused. Here is my code:
$stmt = $conn->prepare("INSERT INTO Student_Choices (Username,T1_Choice,T2_Choice,T3_Choice,Current_DB)
VALUES (:username,:t1choice,:t2choice,:t3choice, db.DB)
SELECT DB FROM Current_DB as db
");
$stmt->bindParam(':username', $_SESSION['username']);
$stmt->bindParam(':t1choice', $_POST["term1sport"]);
$stmt->bindParam(':t2choice', $_POST["term2sport"]);
$stmt->bindParam(':t3choice', $_POST["term3sport"]);
$stmt->execute();
The SELECT DB FROM Current_DB as db is not valid inside the INSERT sentence. Just execute this query first, then get the DB value into a variable, and finally use it with bindParam() as you do with the other parameters: Something like this:
/* Get the database name. */
$stmt = $conn->prepare("SELECT DB FROM DB_Year");
$stmt->execute();
$res = $stmt->fetchAll();
$db = $res[0]['DB'];
/* Execute the insert statement. */
$stmt = $conn->prepare(
"INSERT INTO Student_Choices (Username, T1_Choice, T2_Choice, T3_Choice, Current_DB)
VALUES (:username, :t1choice, :t2choice, :t3choice, :db)"
);
$stmt->bindParam(':username', $_SESSION['username']);
$stmt->bindParam(':t1choice', $_POST["term1sport"]);
$stmt->bindParam(':t2choice', $_POST["term2sport"]);
$stmt->bindParam(':t3choice', $_POST["term3sport"]);
$stmt->bindParam(':db', $db);
$stmt->execute();
To design this INSERT query, start by using SELECT to create the result set you want to insert.
SELECT :username AS Username,
:t1choice AS t1choice,
:t2choice AS t2choice,
:t3choice AS t3Choice,
DB
FROM Current_DB
Then use that result set as the data source for your insert.
INSERT INTO Student_Choices
(Username,T1_Choice,T2_Choice,T3_Choice,Current_DB)
SELECT :username AS Username,
:t1choice AS t1choice,
:t2choice AS t2choice,
:t3choice AS t3Choice,
DB
FROM Current_DB
Notice how the SELECT operation replaces the VALUES() clause.
(Careful, unless you put an appropriate WHERE clause on the SELECT, you may get lots of rows inserted, one for each row in Current_DB.)
Related
I am trying to update mysql table MYTABLE using two value. One is STAR column which should be incremented by one on each query, and the second one is COMMENT column which should be concatenated with existing one on each time and separated by comma.
Below is the command I used, but not working.
$query = "update MYTABLE set STAR=STAR+1,COMMENT= CONCAT(COMMENT, ','.$comment) where ID='$id'";
$query = "update MYTABLE set STAR=STAR+1,COMMENT = CONCAT(COMMENT, ',', '$comment') where ID=$id";
where ID='$id'
is incorrect because $id might be a number, so, delete the "'".
Have you escaped the $comment variable ?
Otherwise you may use prepared statements with PDO :)
I hope you're using PDO...
you should but string in '' and update your query, it has error syntax :
$query = "update MYTABLE set STAR=STAR+1,COMMENT= CONCAT(COMMENT, '$comment') where ID='$id'";
To make it more secure, just use following code...
$query = "update MYTABLE
set `STAR` = `STAR`+1,
`COMMENT`= CONCAT(COMMENT, '$comment')
where `ID`='$id'";
Happy Coding...
I have a problem regarding SQL Query. I have 3 Insert queries in my code.
the first query is with auto-increment ID.
INSERT INTO master_tbl
The second Insert will get the ID from 1st query using LAST_INSERT_ID()function.
INSERT INTO process (id_ref, process_id, hot_cold, temp)
VALUES (LAST_INSERT_ID(), '4', '-', '12')
My problem is, I have third query which needed to use the ID generated in the 1st query as its id_ref also.
When I use the LAST_INSERT_ID(), the ID it gets was the ID of the second query.
Any suggestions on how can I still get the ID in the 1st query to use on 3rd?
You can declare the variable and store the first queries id in that variable and then use it wherever you want.
After first query as you mentioned you are using the separate queries you can try using select to set the `Last insert id` into the variable and then use that variable as below,
select #valuetoUse := LAST_INSERT_ID()
Or Other way is use select the to get the value in your code and then pass that value to insert as all other values. For getting value you can directly fire select
SELECT LAST_INSERT_ID()
then in second query
INSERT INTO process (id_ref, process_id, hot_cold, temp)
VALUES (valuetoUse , '4', '-', '12')
then again in the third query
INSERT INTO thirdtable (id_ref, process_id, hot_cold, temp)
VALUES (valuetoUse , '4', '-', '12')
For more info on how to use user defined variables see here.
Functionality is same as told by #Coder of Code But with PHP
Try This
Create Connection
$conn = new mysqli($servername, $username, $password, $dbname);
First Insert into Table 1
INSERT INTO master_tbl
Then do
$sql = "SELECT MAX(id) as id from master_tbl";
$result = $conn->query($sql);
$row = $result->fetch_array(MYSQLI_NUM);
$latest_id=$row[0];
$sql = "INSERT INTO process (id_ref, process_id, hot_cold, temp)
VALUES ($latest_id,'4','-','12')";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
}
$sql = "INSERT INTO table3 (id_ref , columns list)
VALUES ($latest_id,other fields)";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
}
How can I execute insert queries while retrieving data from database?
I mean that after running a select query where I am retrieving data using a while loop, I also want to insert some fields into another table.
I want to execute inserts forcefully in PHP code.
I tried:
$firstview=mysql_query("insert into kadam_firstview(jobtype,jobname,admin_id,date,datetime)values('".$trial."','".$jobname."','".$adminid."','".$time."','".$date."')");
$firstview.execute();
But it doesn't work.
i want to run upper query inside select query as i am getting data from select query at that same time i want to save those data inside another table but query giving error which is mentioned above
I think your question is more for php developer then for dba.
Anyway if I understand you correctly you would like to select a record set from a table and insert this values (or modified one) into another table?
<?php
$db = new mysqli("host", "username", "password", "databasename");
$result = $db->query("SELECT * FROM table_name");
while ($row = $result->fetch_object()) {
$trail = $row->trail;
$jobname = $row->jobname;
$adminid = 25;
$time = $row->time;
$date = $row->date;
$query = "insert into kadam_firstview(jobtype,jobname,admin_id,date,datetime) values('".$db->escape_string($trial)."','".$db->escape_string($jobname)."','".$db->escape_string($adminid)."','".$db->escape_string($time)."','".$db->escape_string($date)."')";
$db->query($query);
}
this will copy the rows from the table "table_name" into the table "kadam_firstview" and set the adminid to 25.
http://php.itronic.at/manual/en/class.mysqli.php
In my table I have an userID that is auto-incremented. In the same row I have an idHash. Is it possible to generate the idHash (simply an MD5 sum) from it directly with the same INSERT statement so that I don't have to SELECT the id, and then UPDATE the idHash again?
Problem is: I do not know the userID before it is being generated (auto-incremented) by MySQL.
Thanks
Frank
PS: I'm using PHP.
PPS: This question is all about a SINGLE INSERT. I know that I can use PHP or other languages to manually select the data and then update it.
I don't believe you can do it within a single INSERT statement.
What you probably could do is use an INSERT trigger, that both determines the new ID, hashes it, and then updates the record.
One solution I can recommend is using the last insert ID instead of re-querying the table. Here is a simplified example:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "INSERT INTO users VALUES (....)";
$mysqli->query($query);
$newUserID = $mysqli->insert_id;
$query = "UPDATE users SET idHash = MD5(userID) WHERE userID = $newUserID";
$mysqli->query($query);
/* close connection */
$mysqli->close();
?>
AFAIK there's no "secure" way for doing this in the same query if you're using auto_increment.
However, if rows are never deleted in your table, you can use this little trick :
insert into mytable (col1, col2, col3, idhash)
values ('', '', '', md5(select max(id) from mytable))
I don't understand why you need to hash the id though, why not use the id directly ?
This seems to work for me:
CREATE TABLE tbl (id INT PRIMARY KEY AUTO_INCREMENT, idHash TEXT);
INSERT INTO tbl (idHash) VALUES (MD5(LAST_INSERT_ID() + 1));
SELECT *, MD5(id) FROM tbl;
Note this will only work on single-row inserts as LAST_INSERT_ID returns the insert ID of the first row inserted.
Performing MD5(column_name) on an auto_increment value does not work as the value has not been generated yet, so it is essentially calling MD5(0).
PHP snippet
<?
$tablename = "tablename";
$next_increment = 0;
$qShowStatus = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult = mysql_query($qShowStatus) or die ( "Query failed: " . mysql_error() . "<br/>" . $qShowStatus );
$row = mysql_fetch_assoc($qShowStatusResult);
$next_increment = $row['Auto_increment'];
echo "next increment number: [$next_increment]";
?>
This will get you the next auto-increment and then you can use this in your insert.
Note: This is not perfect (Your method is imperfect as you will effectively have 2 primary keys)
From: http://blog.jamiedoris.com/geek/560/
I have two tables with identical structure except for one column... Table 2 has an additional column in which I would insert the CURRENT_DATE()
I would like to copy all the values from table1 to table2.
If I use
INSERT INTO dues_storage SELECT * FROM dues WHERE id=5;
it throws an error pointing to the difference in the number of columns.
I have two questions:
How do I get around this?
How do I add the value for the additional date column (CURRENT_DATE()) in table2 within this same statement?
To refine the answer from Zed, and to answer your comment:
INSERT INTO dues_storage
SELECT d.*, CURRENT_DATE()
FROM dues d
WHERE id = 5;
See T.J. Crowder's comment
The safest way to do it is to fully specify the columns both for insertion and extraction. There's no guarantee (to the application) that either of these will be the order you think they may be.
insert into dues_storage (f1, f2, f3, cd)
select f1, f2, f3, current_date() from dues where id = 5;
If you're worried about having to change many multiple PHP pages that do this (as you seem to indicate in the comment to another answer), this is ripe for a stored procedure. That way, all your PHP pages simply call the stored procedure with (for example) just the ID to copy and it controls the actual copy process. That way, there's only one place where you need to maintain the code, and, in my opinion, the DBMS is the right place to do it.
INSERT INTO dues_storage
SELECT field1, field2, ..., fieldN, CURRENT_DATE()
FROM dues
WHERE id = 5;
Hope this will help someone... Here's a little PHP script I wrote in case you need to copy some columns but not others, and/or the columns are not in the same order on both tables. As long as the columns are named the same, this will work. So if table A has [userid, handle, something] and tableB has [userID, handle, timestamp], then you'd "SELECT userID, handle, NOW() as timestamp FROM tableA", then get the result of that, and pass the result as the first parameter to this function ($z). $toTable is a string name for the table you're copying to, and $link_identifier is the db you're copying to. This is relatively fast for small sets of data. Not suggested that you try to move more than a few thousand rows at a time this way in a production setting. I use this primarily to back up data collected during a session when a user logs out, and then immediately clear the data from the live db to keep it slim.
function mysql_multirow_copy($z,$toTable,$link_identifier) {
$fields = "";
for ($i=0;$i<mysql_num_fields($z);$i++) {
if ($i>0) {
$fields .= ",";
}
$fields .= mysql_field_name($z,$i);
}
$q = "INSERT INTO $toTable ($fields) VALUES";
$c = 0;
mysql_data_seek($z,0); //critical reset in case $z has been parsed beforehand. !
while ($a = mysql_fetch_assoc($z)) {
foreach ($a as $key=>$as) {
$a[$key] = addslashes($as);
next ($a);
}
if ($c>0) {
$q .= ",";
}
$q .= "('".implode(array_values($a),"','")."')";
$c++;
}
$q .= ";";
$z = mysql_query($q,$link_identifier);
return ($q);
}
Alternatively, you can use Inner Queries to do so.
SQL> INSERT INTO <NEW_TABLE> SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM <OLD_TABLE>);
Hope this helps!
SET #sql =
CONCAT( 'INSERT INTO <table_name> (',
(
SELECT GROUP_CONCAT( CONCAT('`',COLUMN_NAME,'`') )
FROM information_schema.columns
WHERE table_schema = <database_name>
AND table_name = <table_name>
AND column_name NOT IN ('id')
), ') SELECT ',
(
SELECT GROUP_CONCAT(CONCAT('`',COLUMN_NAME,'`'))
FROM information_schema.columns
WHERE table_schema = <database_name>
AND table_name = <table_source_name>
AND column_name NOT IN ('id')
),' from <table_source_name> WHERE <testcolumn> = <testvalue>' );
PREPARE stmt1 FROM #sql;
execute stmt1;
Of course replace <> values with real values, and watch your quotes.
Just wanted to add this little snippet which works beautifully for me.
INSERT INTO your_target_table
SELECT *
FROM your_rescource_table
WHERE id = 18;
And while I'm at it give a big shout out to Sequel Pro, if you're not using it I highly recommend downloading it...makes life so much easier