I have a function getMaxID, which queries a database (messages) and gets the maximum id
I want to change the value name of the only row in the returned PDO statement to max_id
Q: How would I do this?
Here is the code
function getMaxID() { $result = $db->query("SELECT * FROM messages ORDER BY id DESC LIMIT 1"); //here is where I want to edit $result's name field return result } $maxID = getMaxID() $row = $maxID->fetch(PDO::FETCH_ASSOC); echo "id: " . $row["id"]. " - Name: " . $row["name"] . "<br>";
I want to get
id: (whatever maximum id is) – Name: max_id
Instead of (what above example would produce)
id: (whatever maximum id is) – Name: (whatever name of maximum id row is)
What I have
I actually have a working way of doing this which is
-use update to change name value in table to max_id
-select max id from table (this is what I return)
-use update to change name back to original value
However, this is incredibly clunky, and I am sure there is a better way to do this than modifying the database
My other best attempt at doing this is editing the row value in getMaxID()
So the new code would look like this
function getMaxID() { $result = $db->query("SELECT * FROM messages ORDER BY id DESC LIMIT 1"); $row = $result->fetch(PDO::FETCH_ASSOC); $row['name'] = 'max_id' //This returns an empty result PDO statement //Is it possible to add row back to PDO statement ($return)??? return result } $maxID = getMaxID() $row = $maxID->fetch(PDO::FETCH_ASSOC); echo "id: " . $row["id"]. " - Name: " . $row["name"] . "<br>";
This solution almost works, but the issue is it returns an empty PDO statement
Since you are fetching the first row of PDO statement and the PDO statement is only has one row
Is there a way to add the row ($row) back into the PDO statement ($result)? (if so this solution would work)
Advertisement
Answer
If I’ve understood this you can use a query like this:
SELECT MAX(id) as id, 'max_id' as name from messages