Unable get Last Insert Id - php

I have downloaded follwing code from one of Google Codes but problem is in getting Last Insert ID.
Please see in run() function
This method is used to run free-form SQL statements that can't be handled by the included delete, insert, select, or update methods. If no SQL errors are produced, this method will return the number of affected rows for DELETE, INSERT, and UPDATE statements, or an associate array of results for SELECT, DESCRIBE, and PRAGMA statements.
<?php
class db extends PDO {
private $error;
private $sql;
private $bind;
private $errorCallbackFunction;
private $errorMsgFormat;
public $lastid;
public function __construct($dsn, $user = "", $passwd = "") {
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
parent::__construct($dsn, $user, $passwd, $options);
} catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
private function filter($table, $info) {
$driver = $this->getAttribute(PDO::ATTR_DRIVER_NAME);
if ($driver == 'sqlite') {
$sql = "PRAGMA table_info('" . $table . "');";
$key = "name";
} elseif ($driver == 'mysql') {
$sql = "DESCRIBE " . $table . ";";
$key = "Field";
} else {
$sql = "SELECT column_name FROM information_schema.columns WHERE table_name = '" . $table . "';";
$key = "column_name";
}
if (false !== ($list = $this->run($sql))) {
$fields = array();
foreach ($list as $record)
$fields[] = $record[$key];
return array_values(array_intersect($fields, array_keys($info)));
}
return array();
}
private function cleanup($bind) {
if (!is_array($bind)) {
if (!empty($bind))
$bind = array($bind);
else
$bind = array();
}
return $bind;
}
public function insert($table, $info) {
$fields = $this->filter($table, $info);
$sql = "INSERT INTO " . $table . " (" . implode($fields, ", ") . ") VALUES (:" . implode($fields, ", :") . ");";
$bind = array();
foreach ($fields as $field)
$bind[":$field"] = $info[$field];
return $this->run($sql, $bind);
}
public function run($sql, $bind = "") {
$this->sql = trim($sql);
$this->bind = $this->cleanup($bind);
$this->error = "";
try {
$pdostmt = $this->prepare($this->sql);
if ($pdostmt->execute($this->bind) !== false) {
if (preg_match("/^(" . implode("|", array("select", "describe", "pragma")) . ") /i", $this->sql))
return $pdostmt->fetchAll(PDO::FETCH_ASSOC);
elseif (preg_match("/^(" . implode("|", array("delete", "insert", "update")) . ") /i", $this->sql)) {
echo $this->lastInsertId();
return $pdostmt->rowCount();
}
}
} catch (PDOException $e) {
$this->error = $e->getMessage();
return false;
}
}
}
?>
Code i use to Insert Record
$insert = array(
"userid" => 12345,
"first_name" => "Bhavik",
"last_name" => "Patel",
"email" => "bhavik#sjmtechs.com",
"password" => "202cb962ac59075b964b07152d234b70"
$db->insert("users",$insert);
echo $db->lastid;

In the insert() function, you've never set $lastid, so it never has the correct value. You'll need something like this:
Change this line in the insert() function:
return $this->run($sql, $bind);
To this:
$rows = $this->run($sql, $bind);
$this->lastid = $this->lastInsertId();
return $rows;
You should also be able to access the lastInsertId() from outside of the class, even without the above modifications, like so:
$db->insert("users",$insert);
echo $db->lastInsertId();

Related

Create my oracle oci class in php. But data show 1 first record only

This code from my PHP Project.
and create oracle connection class.
modified from mysql connection class(work fine).
class databaseOracle
{
public $oci;
public $connected = false;
public $parameters;
public $result;
function __construct($host, $dbPort, $dbName, $userDB, $passwordDB)
{
try {
$ociDB = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = " . $host . ")(PORT = " . $dbPort . ")))(CONNECT_DATA=(SID=" . $dbName . ")))";
$this->oci = oci_connect($userDB, $passwordDB, $ociDB, 'AL32UTF8');
if (!$this->oci) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
echo "Database oracle connection Failed.</br>";
exit();
} else {
echo "Database oracle connection success.</br>";
}
} catch (EngineExcpetion $e) {
echo "Error : " . $e->getMessage() . "</br>";
}
// exit();
}
public function bind($para, $value)
{
$this->parameters[count($this->parameters)] = ":" . $para . "\x7F" . $value;
}
public function bindParams($parray)
{
if (empty($this->parameters) && is_array($parray)) {
$columns = array_keys($parray);
foreach ($columns as $i => &$column) {
$this->bind($column, $parray[$column]);
}
}
}
public function queryString($showQuery = 0, $query = "", $parameters = "")
{
$this->result = null;
if ($showQuery == 1) {
require_once('SQLFormatter.php');
echo SqlFormatter::format($query);
var_dump($parameters);
}
$this->result = oci_parse($this->oci, $query);
# Add parameters to the parameter array
$this->bindParams($parameters);
# Bind parameters
if (!empty($this->parameters)) {
foreach ($this->parameters as $param) {
$parameters = explode("\x7F", $param);
oci_bind_by_name($this->result, $parameters[0], $parameters[1]);
}
}
oci_execute($this->result);
$r = oci_fetch_array($this->result, OCI_ASSOC + OCI_RETURN_LOBS + OCI_RETURN_NULLS);
$this->parameters = array();
return $r;
}
}
$oracleDB = new databaseOracle($ociHost, $ociPort, $ociDB, $ociUsername, $ociPassword);
$query = $oracleDB->queryString(0,"SELECT * from SOME_TABLE where CREATED_BY = :created FETCH NEXT 50 ROWS ONLY",array("created" => "2"));
print_r($query);
my problem
i'm create class of oracle connection. modify from mysql connection class.
it's can query and read record from oracle database. example 50 record
but array result of query show first row only.

Exception when i'm saving data in mysql

I have problem with save data in mysql.
I have such a class to connect with databases:
class Db
{
private $_hostname;
private $_database;
private $_username;
private $_password;
private $_port;
private $_pdo;
private $_sQuery;
private $_bConnected = false;
private $_parameters;
private $_config;
private $_psException;
public function __construct()
{
$this->_config = Registry::register("Core\Utilities\Config");
$this->_psException = new PsException();
$this->_hostname = $this->_config->db_host;
$this->_database = $this->_config->db_db;
$this->_username = $this->_config->db_user;
$this->_password = $this->_config->db_pass;
$this->_port = $this->_config->db_port;
$this->Connect($this->_hostname, $this->_database, $this->_username, $this->_password, $this->_port);
$this->_parameters = array();
}
private function Connect($hostname, $database, $username, $password, $port)
{
try {
$options = array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'");
$this->_pdo = new \PDO("mysql:host={$hostname};dbname={$database};port={$port};charset=utf8", $username, $password, $options);
$this->_pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->_pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
$this->_pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
$this->_pdo->query('SET NAMES utf8');
$this->_bConnected = true;
} catch (PDOException $ex) {
$this->_psException->registerError("Failed to connect to the database: " . $ex->getMessage());
} catch (Exception $e) {
$this->_psException->registerError("Failed to connect to the database: " . $e->getCode() . "." . $e->getMessage());
}
}
public function CloseConnection()
{
$this->_pdo = null;
}
private function Init($query, $parameters = "")
{
if (!$this->_bConnected) {
$this->Connect();
}
try {
$this->_sQuery = $this->_pdo->prepare($query);
$this->bindMore($parameters);
if (!empty($this->_parameters)) {
foreach ($this->_parameters as $param) {
$parameters = explode("\x7F", $param);
$this->_sQuery->bindParam($parameters[0], $parameters[1]);
}
}
$this->success = $this->_sQuery->execute();
} catch (PDOException $e) {
$this->ExceptionLog($e->getMessage(), $query);
}
$this->_parameters = array();
}
public function bind($para, $value)
{
$this->_parameters[sizeof($this->_parameters)] = ":" . $para . "\x7F" . ($value);
}
public function bindMore($parray)
{
if (empty($this->_parameters) && is_array($parray)) {
$columns = array_keys($parray);
foreach ($columns as $i => &$column) {
$this->bind($column, $parray[$column]);
}
}
}
public function query($query, $params = null, $fetchmode = \PDO::FETCH_ASSOC)
{
$query = trim($query);
$this->Init($query, $params);
$rawStatement = explode(" ", $query);
$statement = strtolower($rawStatement[0]);
if ($statement === 'select' || $statement === 'show') {
return $this->_sQuery->fetchAll($fetchmode);
} elseif ($statement === 'insert' || $statement === 'update' || $statement === 'delete') {
return $this->_sQuery->rowCount();
} else {
return null;
}
}
public function lastInsertId()
{
return $this->_pdo->lastInsertId();
}
public function column($query, $params = null)
{
$this->Init($query, $params);
$Columns = $this->_sQuery->fetchAll(\PDO::FETCH_NUM);
$column = null;
foreach ($Columns as $cells) {
$column[] = $cells[0];
}
return $column;
}
public function row($query, $params = null, $fetchmode = \PDO::FETCH_ASSOC)
{
$this->Init($query, $params);
return $this->_sQuery->fetch($fetchmode);
}
public function single($query, $params = null)
{
$this->Init($query, $params);
return $this->_sQuery->fetchColumn();
}
private function ExceptionLog($message, $sql = "")
{
$message .= 'Unhandled Exception. $message';
if (!empty($sql)) {
$message .= "\r\nQuery SQL : " . $sql;
}
$this->_psException->registerError($message);
}
}
and the method to write:
$queryValue["enable"] = $dataValues['enable'];
$queryValue["number"] = $dataValues['number'];
$queryValue["description"] = $dataValues['description'];
$queryValue["date"] = $dataValues['date'];
$queryValue["visible_on_the_front"] = $dataValues['visible_on_the_front'];
$queryValue["id_category_page"] = $dataValues['id_category_page'];
$queryValue["visible_on_the_front2"] = $dataValues['visible_on_the_front2'];
$this->_db->query("INSERT INTO psGalleryCategories (visible_on_the_front2, id_category_page, visible_on_the_front, date, description, enable, number) VALUES (:visible_on_the_front2, :id_category_page, :visible_on_the_front, :date, :description, :enable, :number);", $queryValue);
When he writes such a string of characters:
'';fwefewfpew'f'wef'wefew.''fewvdsniu*&&^&^#^7ef125e2'""''
I have error:
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'f'wef'wefew.''fewvdsniu*&&^&^#^7ef125e2''' at line 1 in /Applications/XAMPP/xamppfiles/htdocs/um/apps/core/utilities/DbClass.php:78 Stack trace: #0 /Applications/XAMPP/xamppfiles/htdocs/um/apps/core/utilities/DbClass.php(78): PDOStatement->execute() #1 /Applications/XAMPP/xamppfiles/htdocs/um/apps/core/utilities/DbClass.php(139): Core\Utilities\Db->Init('SELECT COUNT(ti...', NULL) #2 /Applications/XAMPP/xamppfiles/htdocs/um/apps/core/models/ModelClass.php(24): Core\Utilities\Db->row('SELECT COUNT(ti...') #3 /Applications/XAMPP/xamppfiles/htdocs/um/apps/backend/models/GalleryModel.php(230): Core\Models\Model->createSeoUrl(''';fwefewfpew'f...', 'title_pl', 'psGalleryCatego...') #4 /Applications/XAMPP/xamppfiles/htdocs/um/apps/backend/controllers/GalleryList.php(14 in /Applications/XAMPP/xamppfiles/htdocs/um/apps/core/utilities/DbClass.php on line 78
How to fix this error?
I do not have any problems with normal string. Problem is with combination ',/, "", etc (special characters).
Please help me.

SQL connection dies after one call

I have a custom class that takes a sql connection as a parameter. I use that to populate the class, and then I'm trying to use it again to modify the results on screen. But after the first use, I can't use it anymore.
connection.php:
$conn = new mysqli('localhost', 'root', '', 'loveConnections');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
personalityProfile.php (front end)
if (!isset($_SESSION['interests'])) {
$interests = new Interests($conn, $_SESSION['id']);
$_SESSION['interests'] = $interests;
} else {
$interests = $_SESSION['interests'];
}
interestsObject.php
class Interests {
// properties
public $conn;
public $id;
public $interestsArray = [];
public function __construct($conn, $memberId = null, $intArray = [
'basketball' => false,
'bowling' => false,
'movies' => false,
]) {
$this->conn = $conn;
$this->id = $memberId;
$this->interestsArray = $intArray;
$this->popArraySql();
}
public function popArraySql() {
$memInterests = [];
$sql = "SELECT i.interest
FROM memberInfo m
Join MemberInterestLink mi on (mi.memberID_FK = m.memberID_PK)
Join interests i on (mi.interestID_FK = i.interestID_PK)
WHERE memberID_PK = $this->id";
$result = $this->conn->query($sql);
$this->conn works perfectly here
foreach ($result as $row) {
array_push($memInterests, $row['interest']);
}
foreach ($this->interestsArray as $key => $value) {
for ($i=0; $i<sizeof($memInterests); $i++) {
if ($memInterests[$i] === $key) {
$this->interestsArray[$key] = true;
}
}
}
}
public function insertUpdateQuery() {
var_dump($this->conn);
foreach ($this->interestsArray as $key => $val) {
echo $key . "<br>";
$select = "SELECT interestID_PK from interests where interest = '" . $key . "'";
echo $select;
$result = $this->conn->query($select);
when I try and use it later though, I get a Warning: mysqli::query(): Couldn't fetch mysqli. Additionally, if I try and var_dump it, I get Warning: var_dump(): Property access is not allowed yet
var_dump($result);
if ($val === true) {
$insert = "INSERT INTO MemberInterestLink (memberID_FK, interestID_FK) VALUES ($this->id, $interestKey)";
$this->conn->query($insert);
} else {
$delete = "DELETE FROM MemberInterestLink WHERE interestID_FK = $interestKey";
$this->conn->query($delete);
}
}
}
}
I never close the connection, which is what most of the related answers suggested the cause may be. It's like my $conn variable just stops working after the first use.

Mysqli query function insert duplicate lines

I have been trying to insert a new line to mysql db but insert(){...} function has inserted duplicate lines.
I also have tried several methods to insert but it doesn't works. All of the methods have inserted duplicate rows .
How can I fix the problem? Do you have any idea?
Thank you for your help & advice.
protected $db;
public function __construct() {
try {
$this->db = new mysqli('localhost', 'root', '', 'trigger');
$this->db->set_charset("utf8");
} catch (mysqli_sql_exception $e) {
throw new SmartyException('Mysql Resource failed: ' . $e->getMessage());
}
}
public function select($table, $rows = "", $where = "", $return_type = "") {
if (empty($rows)) {
$rows = "*";
}
if (empty($where)) {
$where = "";
} else {
$where = "where " . $where;
}
try {
$query = $this->db->query("SELECT $rows FROM $table $where");
if ($return_type == "json") {
return json_encode($query);
} else {
return $query;
}
} catch (mysqli_sql_exception $exc) {
return $exc->getMessage();
}
}
public function insert($table, $params) {
$_keyArr = array();
$_valueArr = array();
foreach ($params as $key => $value) {
$_keyArr[] .= $key;
$_valueArr[] .= $value;
}
$keys = implode("`,`", $_keyArr);
$values = implode("','", $_valueArr);
$query = $this->db->query("INSERT INTO `$table` (`$keys`) VALUES('$values')");
try {
return $query;
} catch (mysqli_sql_exception $ex) {
return $ex->getMessage();
}
}
-------------Answer to matt-------------
I call with following code:
if ($this->db->insert("table_name", array("path" => "test", "flow_name" => "test"))) {
echo 'ok';
} else {
echo 'not ok';
}
-------------Answer to Pavel-------------
"REPLACE INTO" didn't work. The problem occured again.
Just use REPLACE INTO instead INSERT INTO
$query = $this->db->query("REPLACE INTO `$table` (`$keys`) VALUES('$values')");

I'm using Unit Of Work Design Pattern with PHP for my project

I'm working on a project which is using Unit of work design pattern. It includes Storage,EntityCollection,..... Code of unit of work includes PDO Adapter code file. But the adapter is not complete for running queries. I have found the files from somewhere.
I can't build queries what I want. Every time I'm writing code I faces to many problems related query. So can you please help me to make it more flexible... For example i want to run like : $db->select()->where('id>:id')->andWhere('')->orWHere()->orderBy()->groupBy()->having()->fetch()/fetchOne(); or similar to it.
<?php
namespace D\Adapter;
class PdoAdapter implements \D\DB\DatabaseInterface {
protected $config = array();
protected $database;
protected $connection;
protected $statement;
protected $fetchMode = \PDO::FETCH_ASSOC;
public function __construct($dsn, $username = null, $password = null, array $driverOptions = array()) {
$this->config = compact("dsn", "username", "password", "driverOptions");
$this->database = $driverOptions['db_name'];
}
public function getStatement() {
if ($this->statement === null) {
throw new \PDOException(
"There is no PDOStatement object for use.");
}
return $this->statement;
}
public function connect() {
// if there is a PDO object already, return early
if ($this->connection) {
return;
}
try {
$this->connection = new \PDO(
$this->config["dsn"], $this->config["username"], $this->config["password"], $this->config["driverOptions"]);
$this->connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->connection->setAttribute(
\PDO::ATTR_EMULATE_PREPARES, false);
} catch (\PDOException $e) {
throw new \RunTimeException($e->getMessage());
}
}
public function disconnect() {
$this->connection = null;
}
public function prepare($sql, array $options = array()) {
$this->connect();
try {
$this->statement = $this->connection->prepare($sql, $options);
return $this;
} catch (\PDOException $e) {
throw new \RunTimeException($e->getMessage());
}
}
public function execute(array $parameters = array()) {
try {
$this->getStatement()->execute($parameters);
return $this;
} catch (\PDOException $e) {
throw new \RunTimeException($e->getMessage());
}
}
public function countAffectedRows() {
try {
return $this->getStatement()->rowCount();
} catch (\PDOException $e) {
throw new \RunTimeException($e->getMessage());
}
}
/**
* countAffectedRows iin Alias
*/
public function count() {
try {
return $this->getStatement()->rowCount();
} catch (\PDOException $e) {
throw new \RunTimeException($e->getMessage());
}
}
public function getLastInsertId($name = null) {
$this->connect();
return $this->connection->lastInsertId($name);
}
public function fetch($fetchStyle = null, $cursorOrientation = null, $cursorOffset = null) {
if ($fetchStyle === null) {
$fetchStyle = $this->fetchMode;
}
try {
return $this->getStatement()->fetch($fetchStyle, $cursorOrientation, $cursorOffset);
} catch (\PDOException $e) {
throw new \RunTimeException($e->getMessage());
}
}
public function fetchAll($fetchStyle = null, $column = 0) {
if ($fetchStyle === null) {
$fetchStyle = $this->fetchMode;
}
try {
return $fetchStyle === \PDO::FETCH_COLUMN ? $this->getStatement()->fetchAll($fetchStyle, $column) : $this->getStatement()->fetchAll($fetchStyle);
} catch (\PDOException $e) {
throw new \RunTimeException($e->getMessage());
}
}
public function select($table, $bind = array(), $where = "", $options = array()) {
if (count($bind) > 0) {
foreach ($bind as $col => $value) {
unset($bind[$col]);
$bind[":" . $col] = $value;
}
}
if (isset($options['fields'])) {
$fields = $options['fields'];
} else {
$fields = '*';
}
$sql = "SELECT " . $fields . " FROM " . $table . " ";
if (strlen($where) > 2) {
$sql .= "WHERE " . $where;
}
// set_flash($sql);
$this->prepare($sql)
->execute($bind);
return $this;
}
public function query($sql, array $bind = array()) {
if (is_array($bind)) {
foreach ($bind as $col => $value) {
unset($bind[$col]);
$bind[":" . $col] = $value;
}
}
$this->prepare($sql)
->execute($bind);
return $this;
}
public function insert($table, array $bind) {
$cols = implode(", ", array_keys($bind));
$values = implode(", :", array_keys($bind));
foreach ($bind as $col => $value) {
unset($bind[$col]);
$bind[":" . $col] = $value;
}
$sql = "INSERT INTO " . $table
. " (" . $cols . ") VALUES (:" . $values . ")";
return (int) $this->prepare($sql)
->execute($bind)
->getLastInsertId();
}
public function update($table, array $bind, $where = "") {
$set = array();
foreach ($bind as $col => $value) {
unset($bind[$col]);
$bind[":" . $col] = $value;
$set[] = $col . " = :" . $col;
}
$sql = "UPDATE " . $table . " SET " . implode(", ", $set)
. (($where) ? " WHERE " . $where : " ");
return $this->prepare($sql)
->execute($bind)
->countAffectedRows();
}
public function delete($table, $where = "") {
$sql = "DELETE FROM " . $table . (($where) ? " WHERE " . $where : " ");
return $this->prepare($sql)
->execute()
->countAffectedRows();
}
public function fetchAllTables() {
$sql = "SHOW TABLES FROM " . $this->database;
$this->prepare($sql)
->execute();
return $this;
}
public function fetchAllFields($table) {
$sql = "SHOW FIELDS FROM " . $table;
$this->prepare($sql)
->execute();
return $this;
}
}
---FULL code is here---
https://github.com/batmunkhcom/mbm/tree/master/src/D
First of all the concern of an UnitOfWork Pattern is to track everything you do during a business transaction that can affect the database. After transactions, it figures out everything that needs to be done to alter the database as a result of your work. Your class has other concerns.
It looks like a godclass (antipattern). It has more than one responsibility: Connection, PeparedStatement, Execution, and other helpers. Its quite difficult to scale and maintain. Try to split all responsibilities to different classes in SOLID way with corresponding design pattern.
Your idea faced in your code is already done by other frameworks. Its very hard work to implement it again. For example you can try Doctrine ORM/DBAL Framework.

Categories