MYSQL duplicates when using ->insert_id - mysql

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...

Related

Sql logic insert from table to another table

My situation is that i have 2 tables in my db. The one is with alerts, the other is with devices. Alerts table has hostname, message, location, time_logged. In the alerts table I keep logs for all events happened. So the thing is that I want to take the alerts.message and for each log to update it in the devices.status (status will keep the message). So i have this sql for now:
$sql = 'SELECT alerter_db.alerts.hostname, message,time_logged, devices.hostname,status FROM
alerts,devices WHERE alerts.hostname = devices.hostname ORDER BY time_logged ASC';
and i have a
while($row = mysql_fetch_array($result) or die('error')){
$my_sql = "INSERT INTO alerter_db.devices (status) VALUE ('".$row['message']."') WHERE
devices.hostname = alerts.hostname";
mysql_query($my_sql);
But unfortunately I am little confused about the logic. So can anybody help me solve this problem ?

Can you select a table value in a MySql Query and edit it?

For my MySQL query, I need to select a specific value like:
$query = "Select * from playerdata where name = $name"
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
However, I want to take that grabbed specific table value (the * operator) and then edit that one like so:
$newquery = "insert into [I want to insert some values from the
old query's selection] [not the general table]"
I know how to use queries and how to execute them. It would be great if I could condense both the select and the insert into one query.
You can use the SQL INSERT INTO SELECT Statement
INSERT INTO table2
Select * from playerdata where name = 'Pedro';
To use this in your PHP script it would look something like this:
$nameSafe = mysql_real_escape_string($name);
$newquery = "INSERT INTO table2
Select * from playerdata where name = '$nameSafe';";
It's good to understand the aspects of security from early on and for that PHP Security Cheat Sheet is a good read.

updating mysql table using php gives no change

I'm trying to update a mySQL table using php. Basically I pass an ordernumber (int) and use it to find both isbn and quantityordered which I then use to update another table.
$orderID=$_POST["order_ent_number"];
$query="select ISBN from Orders where orderNumber='$orderID'";
$isbn = mysql_query($query) or die(mysql_error());
$query="select quantityOrdered from Orders where orderNumber='$orderID'";
$quantityordered = mysql_query($query) or die(mysql_error());
$query="UPDATE Books SET inStock='$quantityordered' WHERE inStock='0' AND isbn='$isbn'";
$result = mysql_query($query) or die(mysql_error());
So using the MySQL bench, the query works (if I replace all variables with numbers) and changes it. The problem is when I use the variables in PHP, the code does not work. I tried the mysql_escape_string but that didnt work either. I checked the results of both variables $isbn and $quantityordered and they are right. I get no errors when I run it on the server but there is no change to inStock in the database. After searching around, someone said my variables need to be turned into integers? Not sure if this is correct or not but that is all I came up with. Any suggestions?
Actually you can do it in a single UPDATE statement by joining the tables,
UPDATE Books a
INNER JOIN Orders b
ON a.ISBN = b.ISBN
SET a.instock = a.quantityOrdered
WHERE a.instock = 0 AND
b.OrderNUmber = '$orderID' AND
a.ISBN = '$isbn'
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?
maybe you can try
$query="select ISBN from Orders where orderNumber='".$orderID."'";
$query="select quantityOrdered from Orders where orderNumber='".$orderID."'";
$query="UPDATE Books SET inStock='".$quantityordered."' WHERE inStock='0' AND isbn='".$isbn."'";

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
"

MySQL Insert Select

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.