Get PDO lastInsertId() after method called - php

In my code I use methods to insert data to MySQL database. The method then return either true or false.
If the method return true I would like to use lastInsertId() to run a second method.
Like
if($db->insertMethod($data)){
$lastId = $db->lastInsertId();
$db->secondInsertMethod($lastId, $data2)
}
db.class.php
public function insertMethod($data) {
$db = new DB();
$insert = //Run SQL insert
if($insert > 0 ) {
return true;
}else{
return false;
}
}
public function lastInsertId() {
return $this->pdo->lastInsertId();
}
In this case $db->lastInsertId(); will return 0. One workaround would be to have insertMethod to return this instead of just true but there must another way as well?

Edited!
the solution is correct
The data2 is linked to the data ?
you can also make :
public function insertMethod($data, $data2) {
$db = new DB();
$insert = //Run SQL insert
if($insert > 0 ) {
$this->insertMethod(this->lastInsertId(), $data2);
return true;
} else {
return false;
}
}
or if data2 is linked to the data
public function insertMethod($data) {
$db = new DB();
$insert = //Run SQL insert
if($insert > 0 ) {
$data2 = // get data2
$this->insertMethod(this->lastInsertId(), $data2);
return true;
} else {
return false;
}
}
public function insertMethod($id, $data) {
// your code...
}
or
public function insertMethod($data, $id = null) {
$db = new DB();
if($id == null)
// code to insert without id
else {
$insert = //Run SQL insert
if($insert > 0 ) {
$data2 = // get data2
$this->insertMethod($data2, this->lastInsertId());
}
}
}
The solutions are correct. For you to see who you think is the most appropriate in your situation.

Related

PHP - Uncaught Error: Call to a member function *() on boolean

I have a sql request in PHP, the result of this query is put in class variable
But when tis request return no result, I would like have a null value in variable, for the moment I have a false boolean returned.
Could you help me ?
Thank you
<?php
class test
{
const table_name = 'test_table';
protected $Id;
protected $Nom;
public static function byId($id)
{
$values = array
(
':Id' => $id,
);
$sql = 'SELECT *FROM '.self::table_name.' WHERE Id=:Id';
$QueryPrep = self::getInstance()->prepare($sql);
if(empty($param))
{
$resultQuery = $QueryPrep->execute();
}
else
{
$resultQuery = $QueryPrep->execute($values);
}
if ($resultQuery !=false)
{
$res = $resultQuery->fetchObject(__CLASS__);
return $res;
}
else
{
return false;
}
}
public function get_Id()
{
return $this->Id;
}
}
$cmd_device_id = null;
$cmdDeviceObject = new test();
$cmd_device = $cmdDeviceObject->byId(999);
$cmd_device_id = $cmd_device->get_Id();
echo "cmd_device_id = ".var_dump($cmd_device_id);
?>
This return null if the $res has no result.
if ($resultQuery !=false)
{
$res = $resultQuery->fetchObject(__CLASS__);
return $res ?? null;
}

can't update data to database(codeigniter)

i have this code in my update function, when i try other value the table updates but when i used that value($field8) the table don't update.
public function edit_lead() {
$id = "3";
$field8 ="http://38.102.225.87/RECORDINGS/MP3/20170201-094849_7188352209-all.mp3";
$this->db->set('field8', $field8);
$this->db->where('id', $id);
$query = $this->db->update('table');
if($query) {
return true;
} else {
return false;
}
}
Simply send the id of the user as a parameter of this function..
public function edit_lead($ID) {
}

Load specific data from array

So i have this class for loading data from my MySQL database :
class Db {
protected static $connection;
public function connect() {
if(!isset(static::$connection)) {
$config = parse_ini_file('config.ini');
static::$connection = new mysqli('localhost',$config['username'],$config['password'],$config['dbname']);
}
if(static::$connection === false) {
return false;
}
return static::$connection;
}
public function query($query) {
return $this->connect()->query($query);
}
public function select($query) {
$rows = array();
$result = $this->query($query);
if($result === false) {
return false;
}
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
public function error() {
return $this->connect()->error;
}
public function quote($value) {
return "'" . $this->connect()->real_escape_string($value) . "'";
}
}
I use that class like this :
$db = new Db();
$rows = $db -> select("SELECT name, shortlink FROM `test` WHERE id=3");
It gives me an array with the data.
The problem is that i want to pull out specific data, for example the shortlink field.
How do i do that? I have tried echo $rows['shortlink'], but that gives me the following error :
Undefined index: shortlink
So how do I print specific data?
Your returned $rows columns is an array of associative arrays, to pull out shortlink data returned from the query you have to do something like this:
foreach($rows as $row) {
echo $row['shortlink'];
}

php function not returning class object

I have a DB class that I've created several functions in to return various values. One of the functions returns (or is supposed to) a "user" class object that represents a logged in user for the application.
class user {
public $guid = '';
public $fname = '';
public $lname = '';
public function __construct() {}
public function print_option() {
return "<option value='$this->guid'>$this->name</option>";
}
}
In the DB class I have the following 2 functions:
public function get_user($uid) {
$sql = '';
$usr = new user();
$sql = "SELECT guid, fname, lname FROM ms.users WHERE guid=?";
if($sth = $this->conn->prepare($sql)) {
$sth->bind_param('s', $uid);
if($sth->execute()) {
$sth->bind_result($usr->guid, $usr->fname, $usr->lname);
$sth->fetch();
print_r($usr); // PRINTS OUT CORRECTLY
return $usr;
}
else {return null;}
}
else {return null;}
}
public function get_practice_user_list($pguid) {
$ret = '';
$sql = "SELECT user_guid FROM ms.perm WHERE p_guid=?";
if($sth = $this->conn->prepare($sql)) {
$sth->bind_param('s', $pguid);
if($sth->execute()) {
$usr = new user();
$guid = '';
$sth->bind_result($guid);
while($sth->fetch()) {
print_r($guid); // PRINTS GUID correctly
$usr = $this->get_user($guid);
print_r($usr); // PRINTS NOTHING object is null so prints "error" two lines later.
if($usr != null) $ret .= $usr->print_option();
else print "error";
}
return $ret;
}
else {return null;}
}
else {return null;}
}
I'm just not understanding why the "user" object is not returning in this instance. Others calls to the get_user function work just fine and return the user class object pertaining to that user.
TIA
I guess you guid may be an integer so
$sth->bind_param('s', $uid);
bind_param's first param should be 'i' not 's';
http://www.php.net/manual/en/mysqli-stmt.bind-param.php
The problem was with the query. Since the code was just looping through one query (get_practice_user_list), then calling the get_user function and attempting a second query MySQL came back with an error of out of sync message. When I looked that up, I was able to fix it by doing a fetch_all on the first query then looping through that array to get the users.

PDO lastInsertId() not working for MS SQL

I am running an insert query using PDO and then getting the newly created Id with lastInsertId(). This is all working on my localhost environment.
When I move the exact same code onto a server, the lastInsertId() is always returning blank, even though the insert statement works and inserts the new row into the database. Would this be a setting in my configuration? Any help is appreciated.
$insertstmt = $dbinsert->prepare($insertsql);
// bindParams ...
$insertstmt->execute();
// always blank
$id = $dbinsert->lastInsertId();
$dbinsert = null;
I ended up replacing lastInsertId() by using this method: http://php.net/manual/en/pdo.lastinsertid.php#105580
$temp = $sth->fetch(PDO::FETCH_ASSOC);
I've describe a solution for this problem on my blog. I couldn't directly modify sql queries in the code, so I extended the PDO class in this way
class BetterPDO extends \PDO
{
protected $stmt;
protected $withIdentitySelect;
public function prepare($statement, $driver_options = null)
{
$this->$withIdentitySelect = false;
if (preg_match('/^insert/i', $statement)) {
$statement = "{$statement}; select SCOPE_IDENTITY() AS 'Identity';";
$this->$withIdentitySelect = true;
}
$this->stmt = parent::prepare($statement, is_array($driver_options) ? $driver_options : []);
return $this->stmt;
}
public function query($statement)
{
$this->$withIdentitySelect = false;
if (preg_match('/^insert/i', $statement)) {
$statement = "{$statement}; select SCOPE_IDENTITY() AS 'Identity';";
$this->$withIdentitySelect = true;
}
$this->stmt = parent::query($statement);
return $this->stmt;
}
public function lastInsertId($name = null)
{
$lastIndex = 0;
if (($this->$withIdentitySelect) && ($this->stmt->columnCount() > 0)) {
$lastIndex = $this->stmt->fetchColumn(0);
$this->stmt->closeCursor();
}
return $lastIndex;
}
}

Categories