Get database row after insert in one query - php

At the moment I have a script where I add data to the database.
Once the data is entered I would like to get the get the row straight away.
For example if I have a query like this where I have two seperate:
$sql = "INSERT INTO table SET columnA '".$this->db->escape($columnA)."'";
$query = $this->db->query($sql);
$sql = "SELECT * FROM table";
$query = $this->db->query($sql);
return $query->db->row;
I want to be able to make get that database row instantly after inserting it. Will I have to make a whole new query or is there a quicker way? I am using OpenCarts API if that helps.
Thanks
Peter

INSERT INTO table (a,b,c) VALUES ('a','b','c');
SELECT * FROM table WHERE your_table_primary_key = LAST_INSERT_ID();
PHP:
$sql = "INSERT INTO table SET columnA '".$this->db->escape($columnA)."';";
$sql .= "SELECT * FROM table WHERE your_table_primary_key = LAST_INSERT_ID();"
$query = $this->db->query($sql);
return $query->db->row;

Related

Only get one row from the query

Hello i have a posts_comments table in my phpmyadmin,
and i can see that when i loop out the comments and send the notifications to users who commented then am getting the repeated details which is sending duplicate comments instead of one comment per user_id.
$sql = "SELECT * FROM posts_comments WHERE id=?";
$stmt = $this->connect()->prepare($sql);
$stmt->execute([$_GET['id']);
$rows = $stmt->fetchAll();
foreach($rows as $row){
$commenter_id = $row['user_id'];
//Inserting a notifation to all users who comments
$insert = "INSERT INTO notifications(message,user_id)VALUES(?,?)";
$stmt = $this->connect()->prepare($insert);
$stmt->execute('some has commented on a post you are following', $logged_user);
}
Please help me send only one notification per user in posts_comments
Try using distinct keyword. It will eliminate all the duplicate records and fetching only unique records.
SELECT DISTINCT column1, column2,.....columnN
FROM table_name
WHERE [condition]

moving rows to another table and also inserting additional values

Im currently moving rows from "mycart" table to "itemorders" table.
$query = "INSERT into orders
(email,address,postalcode,contactNo,orderdate,status) values
('".$email."','".$address."','".$postalcode."','".$contactNo."','".$orderdate."','".$status."');";
$query .= "INSERT into itemorders (itemID,itemName,itemSize,itemPrice,quantity) SELECT itemID,itemName,itemSize,itemPrice,quantity FROM mycart WHERE email='".$email."' ";
$result = mysqli_multi_query($conn,$query);
$ordersID = mysqli_insert_id($conn);
Currently, i have an additional field called ordersID in "itemorders" table, the first query also Auto increments a ordersID. I want to insert the $ordersID value that i have used in the first query into the second query. How can i do that?
Use the LAST_INSERT_ID() function in MySQL. It gets the last auto-increment ID, just as mysqli_insert_id() does.
$query .= "INSERT into itemorders (itemID,itemName,itemSize,itemPrice,quantity,orderSID)
SELECT itemID,itemName,itemSize,itemPrice,quantity, LAST_INSERT_ID()
FROM mycart
WHERE email='".$email."' ";

Conditional PDO Delete statement probably not working

The portion that is trying to delete duplicate entries in the database seems incorrect. So I suppose I am asking what would be the correct way to do that in this example. I am not totally new to PHP , but this is beyond me. If you could please tell me what is wrong and how to fix that would be greatly appreciated.
Now on to what I am trying to accomplish. I have a multidimensional array filled with values that is generated by a function. What I am trying to do is if there is a value in the array that already exists in the database delete it. Code:
enter code here
if(is_array($items)){
$values = array();
foreach($items as $row => $value){
$rsn = mysqli_real_escape_string($connect, $value[0]);
$rank = mysqli_real_escape_string($connect, $value[1]);
$values[] = "('', '$rsn', '$rank', '')";
$sql = "SELECT id FROM users WHERE rsn = :rsn";
$query = $conn->prepare($sql);
$query->execute(array(":rsn" => $value[0]));
$results = $query->rowCount();
while($deleted = $query->fetch(PDO::FETCH_ASSOC)){
$sql = "DELETE FROM users WHERE id = :id";
$query = $conn->prepare($sql);
foreach($deleted as $delete){
$query->execute(array(':id' => $delete));
}
}
}
//user_exists_delete($conn, $rsn);
$sql = "INSERT INTO users(id, rsn, rank, points) VALUES ";
$sql .= implode(', ', $values);
if(!empty($rank)&& !empty($rsn)){
if(mysqli_query($connect, $sql)){
echo "success";
}else{
die(mysqli_error($connect));
}
}
}
EDIT: I have got it partially working now, just need it to delete all dupes instead of only one. I edited code to reflect changes.
There are a couple problems, if you didn't strip much of your original code and if you don't need to do more than just what you shown why not just send a delete instruction to your database instead of checking validity first?
You have
//Retrieve ID according to rsn.
$sql = "SELECT id FROM users WHERE rsn = :rsn ";
//Then retrieve rsn using rsn??? Useless
$sql = "SELECT rsn FROM users WHERE rsn = :rsn ";
//Then delete using ID, retrieved by rsn.
$sql = "DELETE FROM users WHERE id = :id";
All those could simply be done with a delete using rsn...
$sql = "DELETE FROM users WHERE rsn = :rsn";
The row won't be deleted if there are no rows to delete, you don't need to check in advance. If you need to do stuff after, then you might need to fetch information before, but if not, you can use that while still checking the affected rows to see if something got deleted.
Now, we could even simplify the script by using only one query instead of one per user... We could get all rsn in an array and then pass it to the DELETE.
$sql = "DELETE FROM users WHERE rsn in :rsn";
//Sorry not exactly sure how to do that in PDO, been a while.
I fixed it I just omitted the WHERE clause in the delete statement so all records are being deleted before that insert gets ran again.

PHP insert into database query

I am trying to insert values into a database table, a row is inserted but blank no values are inserted. Only the order_id which is the primary key with auto increment increase.
php code:
<?php
$user_get = mysql_query("SELECT * FROM users");
while($row_user = mysql_fetch_assoc($user_get)){
if($row_user['username'] == $_SESSION['username']){
$row_user['first_name'] = $res1;
$row_user['last_name'] = $res2;
$store_order ="INSERT INTO oko (user, product) VALUES ('$res1', '$res2')";
mysql_query($store_order);
}
}
?>
Your assignments are backwards. I think you meant to:
$res1 = $row_user['first_name'];
$res2 = $row_user['last_name'];
Don't you mean:
$res1 = $row_user['first_name'];
$res2 = $row_user['last_name'];
You could also update the SELECT to have a WHERE clause that checks $_SESSION['username'].
You could also just do an INSERT/SELECT:
INSERT INTO oko (user, product)
SELECT
first_name, last_name
FROM
users
WHERE
username = '$_SESSION["username"]'
Your code is vulnerable to injection. You should use properly parameterized queries with PDO/mysqli

time() function gives a less value then first time calling time()

Having this code:
$query = "INSERT INTO table1 SET posted='".mysql_real_escape_string(time())."'";
#mysql_query($query);
....
$q = "UPDATE table2 SET activated='".mysql_real_escape_string(time())."'";
#mysql_query($q);
Then, when I look in the database, the posted value in table2 is less than the posted value in table1.
How could this possible or am I doing something wrong?
this query is wrong
$query = "INSERT INTO table1 SET posted='".mysql_real_escape_string(time())."'";
#mysql_query($query);
it should be
$query = "update table1 SET posted='".mysql_real_escape_string(time())."'";
#mysql_query($query);
and try to store the time in variable and use it in query..

Categories