Getting last inserted index mysql - php

I am using ADODB to connect to my database.
After I submit the query I want to get the ID of the last inserted row (from the query just inserted).
ADODB has an Insert_ID() function that should retrieve this is but it is not...
db->Insert_ID()
is not working, neither is
db->Insert_ID($table, $key)
They both just return empty values.
I doubled checked my table and the insert statement is indeed working, a new row is being put in, and the key is auto_increment. Am I using the Insert_ID wrong or is there a better way to retrieve the key of the last row inserted?
Thanks
Edit: Adding code
$result = \PSU::db->Execute( $updateSQL, $values_array );
$id = \PSU::db->Insert_ID();
// $id = \PSU::db->Insert_ID( $table, $key );
\PSU::db is our ADODB implementation class, taking care of things like connecting, disconnecting, etc.

Is it possible that you are disconnecting and reconnecting to mysql between the query and the insert_id()?

Try this:
$result = \PSU::db->Execute( $updateSQL, $values_array );
return \PSU::db->_connectionID->insert_id ;
_connectionID must be fixed as is.
Hope it helps!

Related

How exactly does mysqli(a,b,c,d)->query(sql)->fetch_assoc() work?

I am new to php and mysqli and have been going through and trying to understand how a lot of these built in functions work. I have read the documentation and many tutorials/examples.
I have something like:
$conn = new mysqli(vars); <br />
$sql = "Select * from Users where name ='$name'";
$result = $conn->query($sql);
$pass = result->fetch_assoc()['Pass'];
//check password stuff
that works fine, however if I then try to use $result->fetch_assoc()['ID'] it returns null. If I swap the order of ID and Pass then the id returns and pass comes back null.
I don't understand why this is the case. What I think (which is clearly wrong) is that result should store the whole row (which it does) and then when i fetch assoc I should just be pulling data from the row. However it seems to be overwriting result when I fetch assoc. What's up with that?
My work around is to call the query multiple times for each data point i need to start a session and store variables, and I know I can use prepared statements, but I feel like there's a better way and I'm missing it.
Can someone please explain?
Every time you call fetch_assoc(), it fetches the next row. There'll presumably only be one user with a specific name, so the result of the second fetch_assoc() call will be null.
Store the value of $result->fetch_assoc() and you can do what you want with it afterwards.
$user = $result->fetch_assoc();
echo $user['ID'];
echo $user['Pass'];

Execute 2 mysql Queries with the second being based on the first

Hi I have two tables that I need to insert into.
the issue is that the first table has an ID field that is automatically generated and I need this field in the second query
members (table1):
|id|name|eyeColour|
assignedMembers (table 2):
|id|memberID|groupID|
I am currently using the below:
$addMember = $dbHandle->prepare("INSERT INTO members(name,date) VALUES(?,?)");
$addMember->bind_param("ss",$name,$eyeColour);
$addMember->execute();
$getID = $dbHandle->("SELECT id from members where name = ? LIMIT 1");
$getID->bind_param("s",$name);
$getID->execute();
$getID->bind_param($MID);
$assignMember= $dbHandle->prepare("INSERT INTO assignedMembers memberID,groupID) VALUES(?,4)");
$assignMember->bind_param("i",$MID);
$assignMember->execute();
This fails at the $assignMember->bind_param(); after troubleshooting I noticed that the $MID variable is empty.
it seems as though the row from the first INSERT is not added before the execution of the next statement is there a way to force this?
Thank you for taking the time to read this post, any help would be greatly appreciated
mysqli:$insert_id is what you are looking for.
$addMember = $dbHandle->prepare("INSERT INTO members(name,date) VALUES(?,?)");
$addMember->bind_param("ss",$name,$eyeColour);
$addMember->execute();
$id = $dbHandle->insert_id;
I think you should use
$getID->bind_result($MID);
$getID->fetch();
instead of
$getID->bind_param($MID);
Due to usage of '...->bind_param' I assume, you use MySQLi.
Check out: mysqli_insert_id — Get the ID generated in the last query

Returning a select statment from a mssql stored proc using PHP (bool(false))

I am using php to consume a mssql stored procedure, my code works with other stored procs but when I try returning something from this one it just returns bool(false) and not the selected value.
$para = array(array($this->Forename), array($this->Surname), );
$result = mssqldb::query("{call usp_NewCustToOrderRemote(?,?)}", $para);
$userid = sqlsrv_fetch_array($result); var_dump($userid);
The stored proc basically just inserts the parameters and then selects the new row id
set #newID = ##IDENTITY
select #newID
I have no control over the stored procedures so I can't add a return value.
When I run the stored proc in management tools it runs fine, when I run in php the row is created.
Oh my db connector class is not using mssql but sqlsrv it's just named incorrectly.
I am I missing something really obvious?
As my stored procedure updated a row and then returned the 'select' I had to use go to the next result as the first result was the row updated.
sqlsrv_next_result($result);
$id = sqlsrv_fetch_array($result)[0];
I did add validation as well :)

only retrieving 1 row of data from MYSQL database

I am trying to input multiple pieces of data through a form and all the data will be separated by (,). I plan to use this data to find the corresponding id for further processing through an sql query.
Below is the code I use.
$key_code = explode(",", $keyword);
//$key_count = count($key_code);
$list = "'". implode("','", $key_code) ."'";
//$row_count = '';
$sql4= "SELECT key_id FROM keyword WHERE key_code IN (".$list.")";
if(!$result4 = mysql_query($sql4, $connect)) {
mysql_close($connect);
$error = true;
}else{
//$i = 0;
while($row = mysql_fetch_array($result4)) {
$keyword_id[] = $row['key_id'];
//$i++;
}
//return $keyword_id;
}
The problem i see is that keyword_id[0] is the only element that contains any data (the data is accurate). Even if I input multiple values through the aforementioned form.
I thought it might be an error in the sql but I echo'ed it and it looks like:
SELECT key_id FROM keyword WHERE key_code IN ('WED','WATER','WASTE')
The values in the brackets are exactly what I inputted.
I even tried to figure out how many rows are being returned by the query and it shows only 1. I assume something is wrong with my query but I cannot figure where.
Any help will be greatly appreciated.
Edit: Alright Solved the problem. Thanks to suggestions made I copied and pasted the $sql_query I had echo'ed on the website into mysql console; which resulted in only 1 row being retrieved. After taking a closer look I realized that there was a whitespace between ' and the second word. I believe the problem starts when I input the key_code as:
WED, WATER, WASTE
Instead inputting it as
WED,WATER,WASTE
fixes the problem. I think I should make it so that it works both ways though.
Anyway, thank you for the help.
I am pretty sure that the query is ok. How many rows do you get with just
SELECT key_id FROM keyword
I think that there is just one line that matches your WHERE.
Check the query directly in the database(with phpmyadmin, or in the mysql console), however this query seems to be working as you may assumed. If it returns only 1 row when you use it directly in the db, then maybe there is only one row in your table wich matches this query.

Incrementing a Table Column, and Getting the New Value using ActiveRecord in CodeIgniter?

I have something similar to the following:
$this->db->set('val', 'val+1', FALSE);
$this->db->where('id', $id);
$query = $this->db->update(TABLE_NAME);
How can I then go, and get the new value of 'val'? Do I have to do another select, or can I get it off of $query?
I've some experience with CodeIgniter and as far as I know you have to requery again.
The update only returns the number of rows affected.
the update query doesnt return anything. if you want to get the value of $val you'll have to run another query
you could run it before running this one, pass the value of val as a parameter to your query next to $id and then return that value + 1.

Categories