MySQL Insert Select - mysql

Ran into a bit of trouble when trying to insert records into my DB from my forum
What it does when you create a thread is make an entry into 2 tables. First the forum_threads table with information on the thread title, description, poster, post time, etc. It will use thread_id with AUTO_INTEGER to generate the threads ID.
I then need to get that thread_id from the forum_threads and then put that as the thread_id in the forum_posts table.
I'm not sure if theres anyway I can select a row based on its ID after I just inserted it. Would I just have to select the most recent ID? Would that leave a margin of error? Other thought I had was to select based on user name and post time.
Thoughts?
<?php
if (isset($_POST['submit'])) {
$thread_sql = "
INSERT INTO forum_threads (
user_id,
forum_id,
thread_postdate,
thread_title,
thread_description,
thread_icon
) VALUES (
'$_SESSION[user_id]',
'$_GET[f]',
'$date',
'$_POST[topictitle]',
'$_POST[topicdescription]',
'$_POST[posticon]'
)
";
$thread_query = #mysqli_query ($db_connect, $thread_sql);
$post_sql = "
INSERT INTO forum_posts (
user_id,
thread_id,
post_message,
post_date
) VALUES (
'$_SESSION[user_id]',
'',
'$_POST[content]',
'$date'
)
";
$post_query = #mysqli_query ($db_connect, $post_sql);
}
?>

To first answer your question directly, the function mysql_insert_id() will return the ID that was assigned to the most recently inserted row. There's no guesswork involved; MySQL will happily tell you (through its own built-in LAST_INSERT_ID() function) what ID it assigned.
On a separate note, I see that you're directly inserting values from $_POST into your SQL statement. Never, ever, EVER do that. This exposes your application to SQL injection attacks.
Either use the mysql_real_escape_string() function to properly escape the values for use in a SQL statement, or, since you're already using mysqli_ functions, use placeholders (? values) to create a prepared statement.

MySqli_Insert_Id () will return the last auto generated ID. Call this function immediately after you insert your new thread.

INSERT
INTO forum_threads (…)
VALUES (…)
INSERT
INTO forum_posts (thread_id, …)
VALUES (LAST_INSERT_ID(), …)

You can just use the last_insert_id to get the ID of the row you just inserted; don't worry about anybody else inserting a row just after, the last_insert_id is per-connection, so unless they used your connection, you're safe.
There is an API-level call to retrieve this so you don't need to ask the server specifically.
Oh yes, also, do not use the # operator in PHP, ever, google for it if you want to know why it's bad.

Use MySQL's last_insert_id() function in sql code or the php wrapper for it mysql_insert_id() in a php script. These will give you the last auto_increment number generated in your connection. So it's thread safe.

Related

MYSQL duplicates when using ->insert_id

I was happy when I got this to work but it submits the order twice unless I comment out the last two lines. Is there a better way to write it so that I don't get duplicates?
$sql = "INSERT INTO orders (weight, shipper, shipacct) VALUES ('$weight', '$shipper', '$shipacct')";
$conn->query($sql);
$recordid = $conn->insert_id;
I did this this way because I'm trying to use the record ID as the order ID. I echo this order ID back to the customer on the purchase receipt.
updated code:
$sql = "INSERT INTO orders (weight, shipper, shipacct) VALUES ('$weight', '$shipper', '$shipacct')";
$recordid = mysql_insert_id();
no duplicates, but does not return the record ID.
Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in the future.
Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more information.
Alternatives to this function include:
mysqli_insert_id()
PDO::lastInsertId()
Try the following:
$sql = "INSERT INTO orders (weight, shipper, shipacct) VALUES ('$weight', '$shipper', '$shipacct')";
$conn->query($sql);
$recordid = mysql_insert_id();
Note:
Because mysql_insert_id() acts on the last performed query, be sure to call mysql_insert_id() immediately after the query that generates the value.
Hopefully, this and this will help...

Insert Select Query

I have 2 tables articles and users.
I want to insert title, content and name into the article table.
I have the the users id stored in a session, is there a way using an insert select query to add title, content and name to the article table whilst getting the name from the users table using the id.
Something like:
INSERT INTO article (title, content, name) VALUES ($post['title'], $post['content'], name) SELECT name FROM users WHERE id = mySessionId
use INSERT INTO..SELECT statement,
$title = $post['title'];
$content = $post['content'];
$insertStatement = "INSERT INTO article (title, content, name)
SELECT '$title', '$content', name
FROM users
WHERE id = mySessionId";
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?

MySQL INSERT-SELECT a non-mandatory field with JOIN

I have a table (netStream), that has 2 foreign keys: (logSessions_logSessionID) and (accountSessions_accountSessionID).
The (logSessions_logSessionID) is mandatory the (accountSessions_accountSessionID) is NOT mandatory.
Here is the part of the block-scheme that shows the connections and the non-mandatory status:
(The background: logSessions are the sessions that every visitor have, accountSessions are the login sessions. Everybody has a logSession (since everybody is a visitor), but not everybody is logged in, so they do not have accountSession)
I want to insert a row into (netStream), in every case there is a (logSession), but it is not the same with (accountSession). So, when there is an (accountSession), I want to insert that ID too, if there is no (accountSession), then just leave that field in (netStream) NULL.
The hash values are stored in Binary(x), this is why I use UNHEX().
This is the MySQL I wrote, there is no error message, but it does not work. What is the problem?
INSERT INTO `test-db`.`netStream` (`netStreamHash`, `logSessions_logSessionID`, `accountSessions_accountSessionID`)
SELECT UNHEX("1faab"), `logSessions`.`logSessionID`, NULL FROM `logSessions` CROSS JOIN `accountSessions`
WHERE `logSessions`.`logSessionHash` = UNHEX("aac") AND
`accountSessions`.`accountSessionHash` = UNHEX("2fb");
If understand you correctly you are probably looking for something like this
INSERT INTO `test-db`.`netStream` (
`netStreamHash`,
`logSessions_logSessionID`,
`accountSessions_accountSessionID`)
SELECT UNHEX("1faab"),
(SELECT `logSessionID` FROM `logSessions`
WHERE `logSessionHash` = UNHEX("aac")),
(SELECT `accountSessionID` FROM `accountSessions`
WHERE `accountSessionHash` = UNHEX("2fb"));
If there is no matching row in accountSessions then you'll get NULL inserted in accountSessions_accountSessionID in netStream table

mysql - satisfy composite primary key while using 'insert into xxx select'

I am importing data to a table structured: content_id|user_id|count - all integers all comprise the composite primary key
The table I want to select it from is structured: content_id|user_id
For reasons quite specific to my use case, I will need to fire quite a lot of data into this regularly enough to want a pure MySQL solution
insert into new_db.table
select content_id,user_id,xxx from old_db.table
I want each row to go in with xxx set to 0, unless this would create a duplicate key, in which case I wish to increment the number, for the current user_id/content_id combination
Not being a MySQL expert, I tried a few options like trying to populate xxx by selecting from the target table during insert, with no luck. Also tried using ON DUPLICATE KEY to increment counters instead of the usual UPDATE. But it all seemed a bit daft so I thought I would come here!
Any ideas anyone? I have a backup option of wrapping this in PHP, but it would drastically raise the overall running time of the script in which this would be the only non-pure MySQL part
Any help really appreciated. thanks in advance!
--edit
this may sound really awful in principle. but id settle for a way to do it in an update after entering random numbers (i have sent in random numbers to allow me to continue other work at the moment) - and this is a purely dev setup
--edit again
12|234
51|45
51|45
51|45
23|67
would ideally insert
12|234|0
51|45|0
51|45|1
51|45|2
23|67|0
INSERT INTO new_db.table (content_id, user_id, cnt)
SELECT old.content_id, old.user_id, COUNT(old.*) - 1 FROM old_db.table old
GROUP BY old.content_id, old.user_id
this would be the way I would go, so if 1 entry it would put 0 on cnt, for more it would just put 1-2-3 etc.
Edit:
Your correct answer would be somewhat complicated but I tested it and it works:
INSERT INTO newtable(user_id,content_id,cnt)
SELECT o1.user_id, o1.content_id,
CASE
WHEN COALESCE(#rownum, 0) = 0
THEN #rownum:=c-1
ELSE #rownum:=#rownum-1
END as cnt
FROM
(SELECT user_id, content_id, COUNT(*) as c FROM oldtable
GROUP BY user_id, content_id ) as grpd
LEFT JOIN
(SELECT oldtable.* FROM oldtable) o1 ON
(o1.user_id = grpd.user_id AND o1.content_id = grpd.content_id)
;
Assuming that in the old db table (source), you will not have the same (content_id, user_id) combination, then you can import using this query
insert newdbtable
select o.content_id, o.user_id, ifnull(max(n.`count`),-1)+1
from olddbtable o
left join newdbtable n on n.content_id=o.content_id and n.user_id=o.user_id
group by o.content_id, o.user_id;

MySql - Best way to do this kind of query

I need to return a single row with some datas taken from some tables not related each others.
So, for example, my actual queries are these (I done it trought a PHP script) :
$query=mysql_query("SELECT trackid FROM tracklist WHERE usersub='".$_SESSION['nickname']."'",$mydb);
echo mysql_num_rows($query);
$query=mysql_query("SELECT trackid FROM comments WHERE usercom='".$_SESSION['nickname']."'",$mydb);
echo mysql_num_rows($query);
$query=mysql_query("SELECT vote FROM vote WHERE uservote='".$_SESSION['nickname']."'",$mydb);
echo mysql_num_rows($query);
$query = mysql_query("SELECT datereg FROM users WHERE nickname='".$_SESSION['nickname']."'",$mydb);
echo mysql_result($query,0,'datereg');
But this will call the MySql server 4 times.
Whats your suggestion to better this situation?
If the tables are not related then you will have to make 4 seperate calls
If the tables COULD be related by foreign keys then you could join them in some way and possibly cut down your sql calls
Ultimately though if you need all of the data then you'll have to request it from the database
You could use a UNION. And, btw, mysql_result is poor. And FFS don't forget to sanitize your inputs!
<?php
$nickname = mysql_escape_string($_SESSION['nickname']);
$sql = "
SELECT COUNT(trackid) AS n FROM tracklist WHERE usersub='{$nickname}'
UNION
SELECT COUNT(trackid) FROM comments WHERE usercom='{$nickname}'
UNION
SELECT COUNT(vote) FROM vote WHERE uservote='{$nickname}'
UNION
SELECT datereg FROM users WHERE nickname='{$nickname}'
";
$result = mysql_query($sql, $db);
while ($row = mysql_fetch_assoc($result)) {
echo $row['n'];
}
?>
I wouldn't really recommend this as it's a bit of a mess combining "count" values with a date in the same column, but you can do it. It's the direct answer to your question.
Well, you could create a fifth table and use it as an index.
If all the values { trackid, vote, datareg } are integers, the index table could contain three columns - nickname, value, and table. When you add records to one of the other tables, add a corresponding record to the index table.
For example,
INSERT INTO vote (vote, uservote, ...) VALUES (123, 'abc', ...);
INSERT INTO myindex (nickname, nvalue, ntable) VALUES ('abc', 123, 'vote');
(I wouldn't actually store the table name as a string but as a numeric value, but you get the idea)
Then on a query, you just SELECT nvalue, ntable FROM myindex WHERE nickname = 'abc';
You will possibly get more than one row.
I think that this is a lot of work and you are better off sticking with the four original queries.
Have you tried combining the select statement together like
SELECT .. Actually.
Maybe you should normalise your database and set up links between your tables...
Edit :: And i'm not sure how you're preparing yourself against mysql injection, but be careful with where your $_SESSION[] comes from
If all the selects return a single row:
$query=mysql_query("
(SELECT trackid FROM tracklist WHERE usersub='".$_SESSION['nickname']."'") as tracklist,
(SELECT trackid FROM comments WHERE usercom='".$_SESSION['nickname']."'") as trackid,
(SELECT vote FROM vote WHERE uservote='".$_SESSION['nickname']."'") as vote,
(SELECT datereg FROM users WHERE nickname='".$_SESSION['nickname']."'") as datereg
"