Method 'lastInsertId' not found in Opis\Database\Database - php

I get the error
Method 'lastInsertId' not found in Opis\Database\Database
How do I get the last inserted Record id in Opis Database?
it gives me a Database object but I can't find any method or property to get the last inserted record id
Here is my connection code
public function __construct()
{
$this->optimizerChain = OptimizerChainFactory::create();
try {
$conn = new PDO(DSN, DB_USERNAME, DB_PASSWORD);
$connection = Connection::fromPDO($conn);
self::$db = new Database($connection);
} catch (PDOException $ex) {
http_response_code(500);
echo json_encode($ex->getMessage());
die();
}
}
here is Insert record code :
// inserting records into database
try {
$result = $db->insert(array(
'name' => $request->name,
'description' => $request->description,
'images' => "https://picsum.photos/200",
))->into('category');
http_response_code(201);
// get last insert id
$last_id = $db->lastInsertId();
} catch (Exception $ex) {
echo json_encode($ex->getMessage());
die();
}
lastInsertId() its giving me an error that method not found
I have tried to get a connection using PDO but it's still not working
$conn = new PDO(DSN, DB_USERNAME, DB_PASSWORD);
$connection = Connection::fromPDO($conn);

Related

php PDO - How do I get last inserted Id?

i was trying to get parent_id which is the last_insert_id. I am using php PDO, i was trying to get lastinsertedId but it keeps gave me an error.
I am able to execute parentRegister but i cannot get the lastInsertId using PDO.
What's wrong on my code?
function connect() {
// connection template
// $pdo = new PDO('mysql:host=127.0.0.1;dbname=SocialNetwork;charset=utf8','root','');
global $host;
global $dbName;
global $dbusername;
global $dbpassword;
try {
$pdo = new PDO("mysql:host=".$host.";dbname=".$dbName."", $dbusername, $dbpassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); // fetch as associative
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); // fetch as object
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $pdo;
} catch (PDOException $e) {
// die('error message: '.$e->message().'<br>');
// die('Our system have some problems now. Please try again later');
return false;
}
}
function query($query, $params = array()) {
$stmt = connect()->prepare($query);
$stmt->execute($params);
if(explode(' ', $query)[0] == 'SELECT'){
$data = $stmt->fetchAll();
return $data;
}
}
// parents 7 column
$parentsData = array(
'role_id' => 2,
'email' => $submittedData['email'],
'parent_name' => $submittedData['parentName'],
'phone' => $submittedData['phone'],
'address' => $submittedData['address'],
'postcode' => $submittedData['postcode'],
'password' => $submittedData['password']
);
// swimmers 6 column
$swimmersData = array(
'role_id' => 3,
'username' => $submittedData['username'],
'password' => $submittedData['password'],
'fname' => $submittedData['fname'],
'lname' => $submittedData['lname'],
'dob' => $submittedData['dob']
);
$parentsRegister = query('INSERT INTO parents('.$parentsField.') VALUES ('.$parentsValue.')', $parentsData);
$swimmersRegister = query('INSERT INTO swimmers('.$swimmersField.',`parent_id`) VALUES ('.$swimmersValue.','.connect()->query("SELECT LAST_INSERT_ID()")->fetchColumn().')', $swimmersData);
I tried to use this code but keeps gave me 0
$stmt = connect()->lastInsertId();
echo $stmt;
just figured out $pdo need to be set as global variable.
// put pdo variable as global to handle last inserted id
$pdo;
function connect() {
global $host;
global $dbName;
global $dbusername;
global $dbpassword;
global $pdo;
try {
$pdo = new PDO("mysql:host=".$host.";dbname=".$dbName."", $dbusername, $dbpassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); // fetch as associative
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); // fetch as object
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $pdo;
} catch (PDOException $e) {
// die('error message: '.$e->message().'<br>');
// die('Our system have some problems now. Please try again later');
return false;
}
}
function query($query, $params = array()) {
$stmt = connect()->prepare($query);
$stmt->execute($params);
// if select
if(explode(' ', $query)[0] == 'SELECT'){
$data = $stmt->fetchAll();
return $data;
// otherwise (update, delete, insert)
} else {
return ($stmt) ? true : false;
}
}
// insert to database
$parentsRegister = query('INSERT INTO parents('.$parentsField.') VALUES ('.$parentsValue.')', $parentsData);
$swimmersRegister = query('INSERT INTO swimmers('.$swimmersField.',`parent_id`) VALUES ('.$swimmersValue.','.$pdo->lastInsertId().')', $swimmersData);

Call to a member function query() on a non-object error in PDO [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
This is my sql connection code
$config['db'] = array('host' => 'localhost', 'username' => 'root', 'password' => '', 'dbname' => 'reputize');
try
{
$db = new PDO('mysql:host='.$config['db']['host'].';dbname'.$config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
echo "Database connected successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
and this is the code i am using to fetch data from the table
$query = $db->query("select * from metaTags where filename='index'");
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
$ptitle=$row['MetaTitle'];
$desc=$row['MetaDisc'];
$kwords=$row['MetaKwd'];
}
but the error keeps on showing
Call to a member function query() on a non-object in C:\xampp\htdocs\template OOP\include\class\websiteClasses.php on line 14
I have tried many solutions here and on other sites as well but of no use.
Please help me out with this problem
you have an error here dbname'.$config['db']['dbname'] it should be dbname='.$config['db']['dbname']
You forget to add '=' after dbname.
Your config should look like below
dbname='.$config['db']['dbname']
From your comment, I understand that your '$db' variable must be declared accessible to other functions. Please check $db has valid database connection before query the database.
I usually use below code for connecting and getting data for my play projects.
function getDbConnection()
{
$pdo = null;
try
{
$pdo = new PDO("mysql:host=" . HOST . ";dbname=" . DBNAME,USERNAME,PWD);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $pe)
{
die("Sorry! Could not connect to database " . DBNAME. ": " . $pe->getMessage());
}
return $pdo;
}
function getData($qry)
{
$res = null;
try
{
if(!empty($qry))
{
$pdo = getDbConnection();
if(!empty($pdo))
{
$res = $pdo->query($qry);
}
}
}
catch(PDOException $pe)
{
throw $pe;
}
return $res;
}
Note: The above functions are not robust. But It works.

php pdo function connect to DB and do query

I am trying to be as efficient with code as possible. Unfortunately, I can't seem to figure out a good way of doing this. I have tried using Sammitch's code which does look cleaner but unfortunately it doesn't seem to work.
I would like a way to stop having to use prepare, execute, every time and a function to me makes the most sense. Using Simmitch's suggestion, I removed the initial connection to database to stop unnecessary overheads but the code still does not work. Showing a "SQLSTATE[HY093]: Invalid parameter number: parameter was not defined" error.
My code at present (some parts omitted as not necessary):
/*Function to talk to database*/
function doQuery($myDB, $myQuery, $myValues)
{
try
{
$st = $myDB->prepare($myQuery);
$st->execute($myValues);
//echo $success;
}
catch (PDOException $e)
{
echo "Failed because: " . $e->getMessage();
}
}
$db = new PDO('mysql:host=localhost;dbname='dbanme';charset=utf8', 'dbuser', 'dbpass');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Set error mode
$query = "INSERT INTO users(login,pass,email,county) VALUES(:username,:password,:email,:count)";
$values = array('username' => $_POST['username'],
'password' => $_POST['password1'],
'email' => $_POST['email'],
'county' => $_POST['county']
);
doQuery($db, $query, $values);
<?php
function doQuery($db, $query, $arguments) {
try {
//Prepare and execute an insert into DB
$st = $db->prepare($query);
$st->execute(array($values));
echo $success; // 4. use echo
// you should probably return something here...
} catch (PDOException $e) {
// 5. Fail ~descriptively~
echo "Failed because: " . $e->getMessage();
// you should probably return something here...
}
}
// 1. Don't create the database inside of the same function that does the queries,
// creation/destruction of the objects/connections will cause unnecessary overhead,
$myDb = new PDO('mysql:host=localhost;dbname=dbname;charset=utf8', 'dbuser', 'dbpassword');
$myDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Set error mode
$myQuery = "INSERT INTO users(login,pass,email,county) VALUES(:username,:password,:email,:count)";
// 2. You can't define an array like that.
// 3. You do not need to add colons to the array indexes.
$myValues = array(
'username' => $_POST['username'],
'password' => $_POST['password1'],
'email' => $_POST['email'],
'county' => $_POST['county']
);
doquery($myDb, $myQuery, $myValues)
Don't forget to include " : " in your parameters array ?
/*Function to talk to database*/
function doQuery($myDB, $myQuery, $myValues)
{
try
{
$st = $myDB->prepare($myQuery);
$st->execute(array($myValues));
//echo $success;
}
catch (PDOException $e)
{
echo "Failed because: " . $e->getMessage();
}
}
$db = new PDO('mysql:host=localhost;dbname='dbanme';charset=utf8', 'dbuser', 'dbpass');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Set error mode
$query = "INSERT INTO users(login,pass,email,county) VALUES(:username,:password,:email,:count)";
$values = array(':username' => $_POST['username'],
':password' => $_POST['password1'],
':email' => $_POST['email'],
':county' => $_POST['county']
);
doQuery($db, $query, $values);
I hope this worked!

Windows Azure MaxSizeInByte Statement

i want to get the current max size of my DB. I have found the statements an checked it out. It works fine in VS2012 SQL Explorer. But when im using php im geting no data.
This is my function:
function getLoad() {
$conn = connect();
$string = 'DATABASEPROPERTYEX ( 'database' , 'MaxSizeInBytes' )';
$stmt = $conn->query($string);
return $stmt->fetchAll(PDO::FETCH_NUM);
}
The problem is that i get an error in fetching the $stmt. Error is:
can not fetchAll(11)
This code will print the database edition and max size in GB:
<?php
function get_database_properties($server, $database, $username, $password) {
try {
$conn = new PDO ("sqlsrv:server=tcp:{$server}.database.windows.net,1433; Database={$database}", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(constant('PDO::SQLSRV_ATTR_DIRECT_QUERY'), true);
$query = "SELECT CONVERT(NVARCHAR(128), DATABASEPROPERTYEX ('{$database}', 'Edition')) as 'Edition', " .
"CONVERT(DECIMAL,DATABASEPROPERTYEX ('{$database}', 'MaxSizeInBytes'))/1024/1024/1024 AS 'MaxSizeInGB'";
$stmt = $conn->query($query);
$row = $stmt->fetch();
$conn = null;
return $row;
}
catch (Exception $e) {
die(print_r($e));
}
}
$db_properties = get_database_properties("yourserver", "yourdatabase", "youruser", "yourpassword");
print("Edition={$db_properties['Edition']} MaxSizeInGB={$db_properties['MaxSizeInGB']}\n");
?>

Returning a single value using PDO MYSQL

I am crossing over to PDO and want to, simply put, return a single value from a table (and I feel really stupid for not getting it right). I am not getting any errors, but also no values, where there should be :)
try {
$sql = "SELECT `column_name` FROM `table` ORDER BY `id` DESC LIMIT 1";
$query = $this->handler->query($sql);
$result = $query->fetchColumn();
print_r($result);
}
catch(PDOException $e) {
return false;
}
return true;
Print the error message:
catch(PDOException $e) {
print_r($e->getMessage());
return false;
}
As shown this would work, if you have correctly connected to the database.
Check that your object is successfully connecting to the database, and that you have the correct column name and table name.
A snippet from one of my DB classes:
/**********************************************************************
* Try to connect to mySQL database
*/
public function connect($dbuser, $dbpassword, $dbhost ,$dbname)
{
try {
$this->dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpassword);
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return true;
} catch (PDOException $e) {
$this->setError($e->getMessage());
}
}

Categories