How to use lastInsertId in this case? - php

What I want is to get and store the last inserted ID, but I am not sure how. The scenario is, after a user add a record he/she will be redirected to a page that will show him/her of the summary of what he/she saved. But I am not sure how I can do that, to retrieved the recently added record.
I have a class which look like this record.php
<?php
class Record {
private $conn;
private $table_name_1 = "name_of_the_table_1";
private $table_name_2 = "name_of_the_table_2";
public $name;
public $age;
public function __construct($db){
$this->conn = $db;
}
function newRecord(){
$query = "INSERT INTO " . $this->table_name_1 . " SET name=:name;
INSERT INTO " . $this->table_name_2 . " SET age=:age";
$stmt = $this->conn->prepare($query);
$this->name=$this->name;
$this->age=$this->age;
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':age', $this->age);
if($stmt->execute()){
return true;
}else{
return false;
}
}
}
?>
now I have another php form that create and add record, the code is something like this add_record.php
<?php
inlude_once 'db.php'
inlude_once 'record.php'
$database = new Database();
$db = $database->getConnection();
$record = new Record($db);
?>
<?php
if($_POST) {
$record->name=$_POST['name'];
$record->age=$_POST['age'];
if(record->record()){
header("Location:{$home_url}view_recently_added_record.php?action=record_saved");
}
else{
echo "Unable to save";
}
}
?>
The idea is to save the query to two different table and the same time automatically record the auto increment ID of table 1 to table 2 so that they have a relationship. I am thinking I can do that if I can store immediately the ID from table 1 and assigned it a variable maybe so it can be automatically saved to table two using a new query or function maybe. Is this possible? does it make sense? and another thing I wanted to display the recently recorded data immediately to the user. Thank you.

You can return $stmt->insert_id or -1 insteaf of boolean in the newRecord function:
function newRecord(){
...
if($stmt->execute()){
return $stmt->insert_id;
}else{
return -1;
}
}
and use the value to redirect like this:
$newrecord = record->newRecord();
if($newrecord != -1) {
header("Location:{$home_url}view_recently_added_record.php?action=record_saved&id=".$newrecord);
}
else{
echo "Unable to save";
}

Related

Dropping and creating a MySQL view in PHP not working

I'm having a problem with some PHP / MySQL code.
I need a view called gameview for a Star Wars game I'm writing.
If I created the view in MySQL then the code runs perfectly. However, I need this view to be dropped every time the game starts. So if I start without the view "gameview" present in the DB, the page cannot be displayed due to the view not existing. However, the moment I manually add the view into MySQL, it works. I can't see why.
Class code
<?php
class gameView
{
protected $Conn;
public function __construct($Conn)
{
$this->Conn = $Conn;
}
public function dropGameView()
{
$drop = "DROP VIEW if EXISTS gameview;";
$stmt = $this->Conn->prepare($drop);
$stmt->execute(array());
}
public function createGameView()
{
$view = "CREATE VIEW gameview AS SELECT id, name, image, quote FROM person;";
$stmt = $this->Conn->prepare($view);
$stmt->execute(array());
}
public function useGameView()
{
$query = "SELECT * from gameview";
$stmt = $this->Conn->prepare($query);
$stmt->execute(array());
$gameView = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $gameView;
}
}
?>
PHP code
<?php
$gameView = new gameView($Conn);
$finalCharacter = $gameView->useGameView();
$smarty->assign('game_view', $finalCharacter);
?>
Well.... stone the crows. I thought this would be too simple to work, but it did!
<?php
$gameView = new gameView($Conn);
$dropGameView = $gameView->dropGameView();
$smarty->assign('drop_gameview', $dropGameView);
$createGameView = $gameView->createGameView();
$smarty->assign('create_gameview', $createGameView);
$finalCharacter = $gameView->useGameView();
$smarty->assign('game_view', $finalCharacter);
?>
Now to crack on and use the view.

wierd behaviour of unset php

I am developing an e-commerce website on which i need to store sessions inside database.I did that by implementing SessionHandlerInterface Class that is provided by the php itself.However it works totally fine and did store sessions inside the database , as well as read them properly.
However I am facing problem when I am using unset to unset a session variable.Sometimes it does work.Sometimes it doesn't.
For example:If i have a session variable by the name ABC unset might delete it from the database or it doesn't deletes the variable.
<?php
//inc.session.php
require_once 'RemoteAddress.php';
class SysSession implements SessionHandlerInterface
{
private $remote_write;
private $remote_read;
private $link;
private $ip_address_write;
private $ip_address_read;
public function open($savePath, $sessionName)
{
$link = new mysqli("localhost","root","","cakenbake");
if($link){
$this->link = $link;
return true;
}else{
return false;
}
}
public function close()
{
mysqli_close($this->link);
return true;
}
public function read($id)
{
$this->remote_read=new RemoteAddress();
$this->ip_address_read=$this->remote_read->getIpAddress();
$stmt=$this->link->prepare("SELECT `Session_Data`,`ip_address` FROM Session WHERE `Session_Id` = ? AND `Session_Expires` > '".date('Y-m-d H:i:s')."'");
$stmt->bind_param("s",$id);
$stmt->execute();
//$result = mysqli_query($this->link,"SELECT Session_Data FROM Session WHERE Session_Id = '".$id."' AND Session_Expires > '".date('Y-m-d H:i:s')."'");
/*$result=$this->link->prepare("Some query inside")
* This shows up an error stating prepare method not found
*
*/
$res=$stmt->get_result();
if($row=$res->fetch_assoc()){
if($this->ip_address_read==$row['ip_address'])
return $row['Session_Data'];
else return "";
}else{
return "";
}
}
public function write($id, $data)
{
$this->remote_write=new RemoteAddress();
$this->ip_address_write=$this->remote_write->getIpAddress();
if(!empty($data))
{
$DateTime = date('Y-m-d H:i:s');
$NewDateTime = date('Y-m-d H:i:s',strtotime($DateTime.' + 1 hour'));
$stmt=$this->link->prepare("REPLACE INTO Session SET Session_Id = ?, Session_Expires = '".$NewDateTime."', Session_Data = '".$data."', ip_address = '".$this->ip_address_write."'");
$stmt->bind_param("s",$id);
// $result = mysqli_query($this->link,"REPLACE INTO Session SET Session_Id = '".$id."', Session_Expires = '".$NewDateTime."', Session_Data = '".$data."'");
if($stmt->execute()){
return true;
}else{
return false;
}
}
}
public function destroy($id)
{
$stmt = $this->link->prepare("DELETE FROM Session WHERE Session_Id =?");
$stmt->bind_param("s",$id);
if($stmt->execute()){
return true;
}else{
return false;
}
}
public function gc($maxlifetime)
{
$result = $this->link->query("DELETE FROM Session WHERE ((UNIX_TIMESTAMP(Session_Expires) + ".$maxlifetime.") < UNIX_TIMESTAMP(NOW()))");
if($result){
return true;
}else{
return false;
}
}
}
$handler = new SysSession();
session_set_save_handler($handler, true);
?>
The above code stores and read sessions from the database.
Structure of the session table.
What could be the possible reason for this weird behaviour. Do i have to implement unset function as well?.
How should i resolve this problem?
If you could suggest me someother already written code for storing in database.That would work as well but i dont need any frameworks such as codeigniter and Yii2.
If you need more information regarding this problem.I will update my question.
Thanks in advance!
The problem is not with the unset function but with your write function.The write function is responsible for any updates that are made to the specific session id.
The wierd behiviour is not with the unset but it is with the write funciton you have implemented.
See ,the !empty constraint checks if your data is empty or not.What i can guess is that your database for that specific id must be empty after the removal of the specific variable .So the write tries to update your row with an empty value but with that constraint it isn't able to do so.
Just remove the !empty tag and it will work like a charm.

Mysqli last insert id not work

I am trying to get last query insert id.but my code always return zero.
My Code
private function Cnn()
{
return mysqli_connect('localhost','root','root','db');
}
protected function MyCommandInsertId($sql)
{
if(mysqli_query($this->Cnn(),$sql))
{
return mysqli_insert_id($this->Cnn());
}
$this->err = mysqli_error($this->Cnn());
return false;
}
public function Insert()
{
$sql = "insert general_info(name,email,password)
values('".$this->ms($this->name)."','".$this->ms($this->email)."','".md5($this->password)."')";
//print''.$sql.'';
$last_insert_id=$this->MyCommandInsertId($sql);
}
here return mysqli_insert_id($this->Cnn()); always return zero
Please check the definition of mysqli_insert_id:-
The mysqli_insert_id() function returns the id (generated with AUTO_INCREMENT) used in the last query.
It means either column in your table that have AUTO_INCREMENT value is not exist.
Or
No insertion of data happen programmatically on your table in the curren program flow. Since no insert query is fired in your code, it returned Zero.
Note:- Just do an insert query first in your code and then check what is the output given by mysqli_insert_id. Then you can understand easily what i am trying to say.Thanks
A working example of my local is here:-
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
function Cnn()
{
$conn = mysqli_connect('localhost','root','','stack');
return $conn;
}
function MyCommandInsertId($sql)
{
$conn = Cnn();
if(mysqli_query($conn,$sql))
{
$lastid = mysqli_insert_id($conn);
return $lastid;
}else{
$err = mysqli_error($conn);
return $err;
}
}
function Insert()
{
$sql = "INSERT INTO bom(bom_description,product_id,finish_product,bom_quantity,UOM) values('Table cleaner','','','','')";
$st_insert_id = MyCommandInsertId($sql);
echo $st_insert_id;
}
Insert();
?>
Output:- http://prntscr.com/9u2iyv (inserted id) and http://prntscr.com/9u2j6i(table view after insertion)
According to
http://php.net/manual/en/mysqli.insert-id.php
There 2 possible problems
no previous query on the connection
the query did not update an AUTO_INCREMENT value
solutions:
Check there is an new record inserted in your table
Check that whether your field is AUTO_INCREMENT or not.
By CBroe, you are make a new connect.
So, it considers you did not insert the new record.
rewrite the function Cnn() and change it into a private variable.
In my case, my sqli was declared outside the current function scope
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
What I needed to do was to add global in front of my $conn
function want() {
///...... query stuff
global $conn;
$conn->insert_id; // Now works
}

PHP, how can I check if the query runs successfully else redirect to other page with out showing error

this is the create function as i have added the database class.
id------int
name----var
fname---var
phone---number
i will run here the query which is not valid the (phone) value should be number so i will insert text to have wrong query.
public function create(){
$sql = "Insert into tbl_one (name,fname,phone) values('nameN','nameF',error)";
if($database->query($sql)){
$this->id = $database->insert_id();
} else {
redirect_to('index.php');
}
now here how i can make if the query is false it should redirect me to one page,
currently it will show the mysql_error and will give detail why it's wrong but i dont want
it i want it just check the query if false redirect me to other page.
do i need another function or that where i should get the hint to move on
you have to replace error with 0
public function create(){
$sql = "Insert into tbl_one (name,fname,phone) values('nameN','nameF',0)";
if($database->query($sql)){
$this->id = $database->insert_id();
} else {
redirect_to('index.php');
}
use exception handling
try {
$sql = "Insert into tbl_one (name,fname,phone) values('nameN','nameF',error)";
$database->query($sql);
$this->id = $database->insert_id();
}catch(Exception $e){
//log exception...$e
redirect_to('index.php');
}

The lifecycle of an object in PHP

I have two PHP scripts that I included below. Both of them attempt to do the same thing, but one works and one does not. I'm looking for someone to explain what PHP is doing under the covers. I'm new to PHP and I suspect that my Java experience is poisoning my thought process when I work in PHP.
What I'm attempting to do is functionally very simple -- Insert a question into a mySQL database table, retrieve the primary key of the inserted row, and then insert five answers into another table with a foreign key relationship to the question.
My original logic looked like this:
ManageQuestions.php:
<?php
session_start();
include('query.php');
echo "begin <br>";
if (isset($_POST['submit'])) {
echo "manageQuestion <br>";
$query = new Query;
$query->createTransaction();
$query->executeCreateUpdateDelete("INSERT INTO question (question) VALUES ('".$_POST['question']."'); ");
$question_pid = $query->getLastInsertedId();
$query->commitTransaction(); // Need to figure out how to do dirty reads so I can remove this.
echo $question_pid."<br>";
$result = $query->executeRead("SELECT question_pid FROM question where question_pid = '".$question_pid."';");
echo count($result)."<br>";
//if (count($result) === 1) {
$query->createTransaction(); // Need to figure out how to do dirty reads so I can remove this.
foreach($_POST['answer'] as $answer) {
$correctAnswers = 0;
$query->executeCreateUpdateDelete("INSERT INTO answer (question_fid, answer, isCorrect) VALUES ('".$question_pid."','".$answer['answer']."','".$answer['isCorrect']."')");
if ($answer['isCorrect'] === 1) {
$correctAnswers = $correctAnaswers + 1;
if ($correctAnswers > 1){
echo "Failed to insert answers";
$query->rollBackTransaction();
break;
}
}
}
echo "Success";
$query->commitTransaction();
/* } else {
echo "Failed to insert question";
$query->rollBackTransaction();
} */
}
?>
Query.php:
<?php
session_start();
class Query
{
private $host="<censored>";
private $username="<censored>";
private $password="<censored>";
private $db_name="<censored>";
private $pdo;
private $pdo_statement;
private $pdo_exception;
public function executeCreateUpdateDelete($pQuery)
{
$this->pdo_statement = $this->pdo->prepare($pQuery);
return $this->pdo_statement->execute();
}
public function executeRead($pQuery)
{
try
{
$dbh = new PDO("mysql:host=$this->host;dbname=$this->db_name", $this->username, $this->password);
$result = $dbh->query($pQuery);
$dbh = null;
return $result->fetchAll();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function createTransaction()
{
$this->pdo = new PDO("mysql:host=$this->host;dbname=$this->db_name", $this->username, $this->password);
$this->pdo->beginTransaction();
}
public function commitTransaction()
{
$this->pdo->commit();
}
public function rollBackTransaction()
{
$this->pdo->rollBack();
}
public function getLastInsertedId()
{
$this->pdo->lastInsertId();
}
}
?>
When I rewrote my logic to not use a separate query class, I was able to do what I wanted to do. The only thing I've been able to find online about the life cycle of a PHP object is that it begins at the start of a script and ends at the end of a script. Does that imply that my query object is instantiated every time I call one of its methods and garbage collected when that particular method ends? Moving the logic out of that class and into the script caused my logic to work. This is what it looks like now:
ManageQuestions.php:
<?php
session_start();
include('query.php');
echo "Begin <br>";
if (isset($_POST['submit'])) {
echo "manageQuestion <br>";
$host="<censored>";
$username="<censored>";
$password="<censored>";
$db_name="<censored>";
$pdo = new PDO("mysql:host=$host;dbname=$db_name", $username, $password);
$stmt = $pdo->prepare("INSERT INTO question (question) VALUES ('".$_POST['question']."'); ");
$stmt->execute();
$question_pid = $pdo->lastInsertId();
echo $question_pid."<br>";
$stmt = $pdo->query("SELECT question_pid FROM question where question_pid = '".$question_pid."';");
$result = $stmt->fetchAll();
echo count($result)."<br>";
foreach($_POST['answer'] as $answer) {
$correctAnswers = 0;
$stmt = $pdo->prepare("INSERT INTO answer (question_fid, answer, isCorrect) VALUES ('".$question_pid."','".$answer['answer']."','".$answer['isCorrect']."')");
$stmt->execute();
}
echo "Success";
}
?>
Even though this fixed my issue, I don't understand why. If someone could explain that, I would be extremely grateful.
Cheers!
Does that imply that my query object is instantiated every time I call one of its methods and garbage collected when that particular method ends?
No. It's per request, not per method call. So the query object is instantiated every time the script is called and it gets unset (and not necessarily garbage collected) when the script ends.
However you could better manage the resource of the PDO object inside your Query class because you create a new instance (which would mean that it connects again to the database server which is not that cheap). So some lazy loading does not seem bad:
class Query
{
...
/** #var PDO */
private $pdo;
...
private function getPdo() {
if (!$this->pdo) {
$this->pdo = new PDO("mysql:host=$this->host;dbname=$this->db_name", $this->username, $this->password);
}
return $this->pdo;
}
public function executeRead($pQuery)
{
try {
$dbh = $this->getPdo();
$result = $dbh->query($pQuery);
return $result->fetchAll();
} catch (PDOException $e) {
echo $e->getMessage();
}
}
public function createTransaction()
{
$this->getPdo()->beginTransaction();
}
...

Categories