Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access the id of the object inserted after a prepared statement in PHP using MYSQLi

Tags:

php

mysqli

I need the id of the last inserted object. I use prepared statements to avoid sql injection. But i'm not sure how to obtain the id.

$sql = "INSERT IGNORE INTO faculty (id, term, role, prefix, first_name, 
               middle_name, last_name, suffix) VALUES (?,?,?,?,?,?,?,?)";

        if (!($stmt = $mysqli->prepare($sql)))
            echo "Faculty Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;

        $stmt->bind_param('sissssss', 
                $faculty['id'], 
                $faculty['term'], 
                $faculty['role'],
                $faculty->name->prefix,
                $faculty->name->first,
                $faculty->name->middle,
                $faculty->name->last,
                $faculty->name->suffix
        );

        if (!$stmt->execute())
            echo "Faculty Execute failed: (" . $mysqli->errno . ") " . $mysqli->error;

        $result = $stmt->insert_id;
        echo "\n Result:" . $result;    
        $stmt->close();             

The result is 0 always despite there being an entry in the database

Solution The element was being inserted into the database. The problem was when I had created the table id wasn't an integer it was a varchar which represented an employee id. To fix this, i added the employee id as an additional column in the table and used the default id int auto_increment primary key and it worked.

like image 856
user1165788 Avatar asked Feb 09 '12 00:02

user1165788


People also ask

Which function is used in MySQLi with prepared statements?

There's also a function to simply free the memory associated with the MySQLi result and prepared statement, respectively: $result->free() and $stmt->free() .

How can I get last inserted record in mysql using PHP?

If you use php to connect to mysql you can use mysql_insert_id() to point to last inserted id.

Can we use prepared statement for select query in PHP?

You must always use prepared statements for any SQL query that would contain a PHP variable. To do so, always follow the below steps: Create a correct SQL SELECT statement. Test it in mysql console/phpmyadmin if needed.

What is $STMT in PHP MySQLi?

" $stmt " obviously (I think) stands for "statement". As a variable name it's arbitrary, you can name that variable anything you want. $stmt is just rather idiomatic. A prepared statement as such is a database feature.


Video Answer


1 Answers

Try changing $result = $stmt->get_result(); to $result = $stmt->insert_id;

get_result() is more for SELECT queries, rather than INSERTs.

http://php.net/manual/en/mysqli-stmt.get-result.php

http://php.net/manual/en/mysqli-stmt.insert-id.php

like image 151
Joe Avatar answered Oct 09 '22 17:10

Joe