PHP PDO::lastInsertId() returns 0 - php

Thanks in advance for reading this, I couldn't find an answer that solved my problem... I don't understand what I'm doing differently than the tutorials/suggestions I found:
SQL Table
CREATE TABLE IF NOT EXISTS `LastInsertID` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` char(150) NOT NULL,
`email` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;
PHP File
<?php
// Connect to database
$user = "foo";
$pswd = "bar";
$db = new PDO( 'mysql:host=localhost;dbname=test', $user, $pswd );
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare request
$rq = $db->prepare('INSERT INTO `LastInsertID` VALUES(NULL,:name,:email)');
// Begin and commit request
$db->beginTransaction();
$values = array('name'=>'Foo','email'=>'bar#baz.com');
$rq->execute($values);
$db->commit();
// Echo last ID
echo $db->lastInsertId();
?>
This returns 0 when it should return 6. Where is the problem?

You must use $db->lastInsertId() before you commit if you are in a transaction. Even if you rollback a transaction, the id is "used" or skipped, which is why you should not depend on IDs to be sequential.

Use this
INSERT INTO `LastInsertID` (name, email) VALUES(:name,:email)
instead
INSERT INTO `LastInsertID` VALUES(NULL,:name,:email)
I have removed the NULL.

Related

How to execute a SQL file on a MySQL database using PDO?

I want to create the database from .sql file but I do not know how to do it. Is it possible to do that?
file connect database PDO
<?php
require "db.sql";
$dsn = "mysql:host=localhost;dbname=DBNAME;charset=utf8";
$user= 'root';
$pass= '';
try {
$connect = new PDO($dsn, $user, $pass);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connect->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo " error ,not connected data base :".$e->getMessage();
}
file db.sql
CREATE DATABASE IF NOT EXISTS DBNAME;
CREATE TABLE `nameTable` (
`id` int(11) NOT NULL AUTO_INCREMENT ,
PRIMARY KEY (`id`),
`pseudo` varchar(35) NOT NULL,
`password` varchar(255) NOT NULL,
`nameWebsite` varchar(255) NOT NULL DEFAULT 'xxxx'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `nameTable` (`id`, `pseudo`, `password`) VALUES
(1, 'admin', 'admin');

Cannot create table with PHP

I want to create a table with variables passed into my php file. However, the SQL does not work when I pass in '12345' and works when I pass in 'a12345' instead.
This is my error that is given.
Error creating the table
query was
CREATE TABLE 123456 ( humidity VARCHAR(50) NOT NULL, temperature VARCHAR(50)
NOT NULL, gasquality VARCHAR(50) NOT NULL, timestamp DATETIME NOT NULL
DEFAULT CURRENT_TIMESTAMP)
mysqlerror:You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near
'123456 ( humidity VARCHAR(50) NOT NULL, temperature VARCHAR(50) NOT NULL,
gasq' at line 1
Creating database failed!
and my function that creates the table
function CreateTableNode(&$formvars)
{
$serialno = $formvars['serialno'];
$qry = "CREATE TABLE ".$serialno." (".
" humidity VARCHAR(50) NOT NULL, ".
" temperature VARCHAR(50) NOT NULL, ".
" gasquality VARCHAR(50) NOT NULL, ".
" timestamp DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)";
if(!mysqli_query($this->connection,$qry))
{
$this->HandleDBError("Error creating the table \nquery was\n $qry");
return false;
}
return true;
}
I want to be able to create tables with numeric names like '12345' or '154124' for other purposes. Thanks alot!
My suggestion:
Provide a prefix to the table you created.
Moreover, I couldn't
see the primary key in your table. However, it is not necessary to
have it but if your table design doesn't have a primary key, you need
to rethink your design. It plays a vital role to join tables.
Your code can be rewritten as:
function CreateTableNode (&$formvars) {
$host = 'localhost';
$database = 'test';
$dbuser = 'root';
$dbpass = '';
try {
$pdo = new PDO('mysql:host=localhost; dbname=test', $dbuser, $dbpass);
} catch (PDOException $e) {
print "ERROR! : " . $e->getMessage() . "<br/>";
die();
}
$serialno = $formvars['serialno'];
$qry = "CREATE TABLE ".$serialno." ("."
`id` INT NOT NULL AUTO_INCREMENT ,
`humidity` VARCHAR(50) NOT NULL ,
`temperature` VARCHAR(50) NOT NULL ,
`gasquality` VARCHAR(50) NOT NULL ,
`timestamp` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ,
PRIMARY KEY (`id`)
)";
$stmt = $pdo->prepare($qry);
$stmt->execute();
$pdo = null;
return true;
}
You just need to wrap some elements in the query with quotes as the duplicated thread mentioned by underscore_d says:
$qry = "CREATE TABLE '$serialno' (
'humidity' VARCHAR(50) NOT NULL,
'temperature' VARCHAR(50) NOT NULL,
'gasquality' VARCHAR(50) NOT NULL,
'timestamp' DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)";
This will fix your syntax errror in the query.
Marking to close the question as duplicated
The name of the entity was expected. (near "123456" at position 13)
Try adding a prefix to the table name as such
"t_12345"
CREATE TABLE t_12345
MySql does not allow numeric values as table name.
MySQL doesn't allow the creation of tables with names made solely of digits unless the name is quotes. See here
Identifiers may begin with a digit but unless quoted may not consist solely of digits.
Try quoting the name with backticks (`) or prefix the table name.
The error says "Creating database failed!".
So I assume you haven't selected the database in the connection query. You should do that or select it with "use mydatabase;" first. Of course, you may need to create the database first.
With PDO it would look like:
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
Please see dbname=myDB which preselects the right db for you.
Reference: https://www.w3schools.com/php/php_mysql_connect.asp
Using mysql functions, you can use:
mysql_select_db($dbname)
Reference: http://php.net/manual/en/function.mysql-select-db.php

PHP, MySQL query executed but table not updated

I'm trying to insert some data to my DB when the page loads.
What I currently have:
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$link = #mysql_connect($servername, $username, $password);
mysql_select_db("download_time", $link);
$sql = "INSERT INTO timestamp (id, time) VALUES ('1', 'testing');";
mysql_query($sql, $link);
mysql_close($link);
The script runs just fine and returns no errors anywhere, I've triple checked the connection and that's fine too. Running INSERT INTO timestamp (id, time) VALUES ('1', 'testing'); through webmin I'm able to get data to be inserted just fine.
DB Structure:
CREATE TABLE `timestamp` (
`id` int(10) NOT NULL DEFAULT '1',
`time` varchar(246) DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I see some things that are wrong:
1) You're using mysql_* API
2) You're setting a primary key in the schema creation but you're giving a default of '1', that's wrong, a Primary Key doesn't have a default beause they're Auto Increment, you cannot have Two Identical Primary keys.
Change your schema creation to this:
CREATE TABLE `timestamp` (
`id` int(10) AUTO_INCREMENT PRIMARY KEY,
`time` varchar(246) DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
And the query to this
$sql = "INSERT INTO timestamp (id, time) VALUES (null, 'testing');";
insert into timestamp (time) values ('testing') leave id in MySQL hands

How to lock a table during an operation use php/yii

My table:
CREATE TABLE IF NOT EXISTS `detail_transaction` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`code` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`id_product` int(11) NOT NULL,
`id_store` int(11) NOT NULL,
`input_quality` int(11) NOT NULL,
`output_quality` int(11) NOT NULL,
`quality_in_store` int(11) NOT NULL,
PRIMARY KEY (`id`)
)
I have the problem is below:
I get record have max_id, and then before i insert new record, having
another process insert new record was inserted.
I think: I will lock table during "I select a record have max_id" to "I completed to insert new next record"(don't run any task work with this table). And to do this method. Please help me! How to do this by php code or Yii.
You could use transactions:
$transaction = Yii::app()->db->beginTransaction();
try {
foreach ($items as $item) {
$item->attr = value;
$item->save();
}
$transaction->commit();
// actions to do on success (redirect, alert, etc.)
} catch (Exception $e) {
$transaction->rollBack();
// other actions to perform on fail (redirect, alert, etc.)
}
This source code is from this post: using transaction in a loop in yii
I'm not exactly sure what you want to achieve, but I'm sure it will work out if you just use transactions - http://www.yiiframework.com/doc-2.0/yii-db-transaction.html. Otherwise, you can always call a LOCK TABLE query - http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html.
$connection = Yii::app()->db;
$lock = $connection-> createCommand('LOCK TABLES `detail_transactions` WRITE');
// do your magic
$unlock = $connection-> createCommand('UNLOCK TABLES');
In Yii2, you can lock/unlock a table like this
$db = Yii::$app->getDb();
$db ->createCommand('LOCK TABLES `YOUR_TABLE` WRITE')->execute();
// access YOUR_TABLE here
// something like YOUR_TABLE_MODEL::find()->where(["something" => "blah"])->one()
$db ->createCommand('UNLOCK TABLES')->execute();

How to convert sqlite to mysql using PHP

I have converted sqlite database into mysql.
so then i need convert sqlite+php code into mysql+php code. do you have any document which containing methods to convert sqlite to mysql.
thanks..
this is my code
<?php
try {
//open the database
$db = new PDO('sqlite:cars.sqlite'); //will create the file in current directory. Current directory must be writable
//create the database if does not exist
$db->exec("CREATE TABLE IF NOT EXISTS cars (id INTEGER PRIMARY KEY, manufacturer TEXT, year INTEGER, price INTEGER)");
//select all data from the table
$select = $db->prepare('SELECT * FROM cars ORDER BY id ASC LIMIT 100');
$select->execute();
$out = array(
'cars' => $select->fetchAll(PDO::FETCH_ASSOC)
);
echo json_encode($out);
// close the database connection
$db = NULL;
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
?>
mysql table:cars
CREATE TABLE IF NOT EXISTS `cars` (
`id` int(11) NOT NULL DEFAULT '0',
`manufacturer` text,
`year` int(11) DEFAULT '0',
`price` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
as you are using PDO, just create Mysql PDO object, change this part:
$db = new PDO('sqlite:cars.sqlite');
to something like:
$dsn = 'mysql:dbname=yourdbname;host=127.0.0.1';
$user = 'yourdbuser';
$password = 'yourdbpass';
$dbh = new PDO($dsn, $user, $password);
and you're done. You dont need to change anything other.
PDO is portable connection object, it can be used with several different database. more about PDO: http://php.net/manual/en/pdo.construct.php

Categories